xref: /linux/net/netfilter/nft_set_pipapo.c (revision a0b0f6c7d7f29f1ade9ec59699d02e3b153ee8e4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 /* PIPAPO: PIle PAcket POlicies: set for arbitrary concatenations of ranges
4  *
5  * Copyright (c) 2019-2020 Red Hat GmbH
6  *
7  * Author: Stefano Brivio <sbrivio@redhat.com>
8  */
9 
10 /**
11  * DOC: Theory of Operation
12  *
13  *
14  * Problem
15  * -------
16  *
17  * Match packet bytes against entries composed of ranged or non-ranged packet
18  * field specifiers, mapping them to arbitrary references. For example:
19  *
20  * ::
21  *
22  *               --- fields --->
23  *      |    [net],[port],[net]... => [reference]
24  *   entries [net],[port],[net]... => [reference]
25  *      |    [net],[port],[net]... => [reference]
26  *      V    ...
27  *
28  * where [net] fields can be IP ranges or netmasks, and [port] fields are port
29  * ranges. Arbitrary packet fields can be matched.
30  *
31  *
32  * Algorithm Overview
33  * ------------------
34  *
35  * This algorithm is loosely inspired by [Ligatti 2010], and fundamentally
36  * relies on the consideration that every contiguous range in a space of b bits
37  * can be converted into b * 2 netmasks, from Theorem 3 in [Rottenstreich 2010],
38  * as also illustrated in Section 9 of [Kogan 2014].
39  *
40  * Classification against a number of entries, that require matching given bits
41  * of a packet field, is performed by grouping those bits in sets of arbitrary
42  * size, and classifying packet bits one group at a time.
43  *
44  * Example:
45  *   to match the source port (16 bits) of a packet, we can divide those 16 bits
46  *   in 4 groups of 4 bits each. Given the entry:
47  *      0000 0001 0101 1001
48  *   and a packet with source port:
49  *      0000 0001 1010 1001
50  *   first and second groups match, but the third doesn't. We conclude that the
51  *   packet doesn't match the given entry.
52  *
53  * Translate the set to a sequence of lookup tables, one per field. Each table
54  * has two dimensions: bit groups to be matched for a single packet field, and
55  * all the possible values of said groups (buckets). Input entries are
56  * represented as one or more rules, depending on the number of composing
57  * netmasks for the given field specifier, and a group match is indicated as a
58  * set bit, with number corresponding to the rule index, in all the buckets
59  * whose value matches the entry for a given group.
60  *
61  * Rules are mapped between fields through an array of x, n pairs, with each
62  * item mapping a matched rule to one or more rules. The position of the pair in
63  * the array indicates the matched rule to be mapped to the next field, x
64  * indicates the first rule index in the next field, and n the amount of
65  * next-field rules the current rule maps to.
66  *
67  * The mapping array for the last field maps to the desired references.
68  *
69  * To match, we perform table lookups using the values of grouped packet bits,
70  * and use a sequence of bitwise operations to progressively evaluate rule
71  * matching.
72  *
73  * A stand-alone, reference implementation, also including notes about possible
74  * future optimisations, is available at:
75  *    https://pipapo.lameexcu.se/
76  *
77  * Insertion
78  * ---------
79  *
80  * - For each packet field:
81  *
82  *   - divide the b packet bits we want to classify into groups of size t,
83  *     obtaining ceil(b / t) groups
84  *
85  *      Example: match on destination IP address, with t = 4: 32 bits, 8 groups
86  *      of 4 bits each
87  *
88  *   - allocate a lookup table with one column ("bucket") for each possible
89  *     value of a group, and with one row for each group
90  *
91  *      Example: 8 groups, 2^4 buckets:
92  *
93  * ::
94  *
95  *                     bucket
96  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
97  *        0
98  *        1
99  *        2
100  *        3
101  *        4
102  *        5
103  *        6
104  *        7
105  *
106  *   - map the bits we want to classify for the current field, for a given
107  *     entry, to a single rule for non-ranged and netmask set items, and to one
108  *     or multiple rules for ranges. Ranges are expanded to composing netmasks
109  *     by pipapo_expand().
110  *
111  *      Example: 2 entries, 10.0.0.5:1024 and 192.168.1.0-192.168.2.1:2048
112  *      - rule #0: 10.0.0.5
113  *      - rule #1: 192.168.1.0/24
114  *      - rule #2: 192.168.2.0/31
115  *
116  *   - insert references to the rules in the lookup table, selecting buckets
117  *     according to bit values of a rule in the given group. This is done by
118  *     pipapo_insert().
119  *
120  *      Example: given:
121  *      - rule #0: 10.0.0.5 mapping to buckets
122  *        < 0 10  0 0   0 0  0 5 >
123  *      - rule #1: 192.168.1.0/24 mapping to buckets
124  *        < 12 0  10 8  0 1  < 0..15 > < 0..15 > >
125  *      - rule #2: 192.168.2.0/31 mapping to buckets
126  *        < 12 0  10 8  0 2  0 < 0..1 > >
127  *
128  *      these bits are set in the lookup table:
129  *
130  * ::
131  *
132  *                     bucket
133  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
134  *        0    0                                              1,2
135  *        1   1,2                                      0
136  *        2    0                                      1,2
137  *        3    0                              1,2
138  *        4  0,1,2
139  *        5    0   1   2
140  *        6  0,1,2 1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
141  *        7   1,2 1,2  1   1   1  0,1  1   1   1   1   1   1   1   1   1   1
142  *
143  *   - if this is not the last field in the set, fill a mapping array that maps
144  *     rules from the lookup table to rules belonging to the same entry in
145  *     the next lookup table, done by pipapo_map().
146  *
147  *     Note that as rules map to contiguous ranges of rules, given how netmask
148  *     expansion and insertion is performed, &union nft_pipapo_map_bucket stores
149  *     this information as pairs of first rule index, rule count.
150  *
151  *      Example: 2 entries, 10.0.0.5:1024 and 192.168.1.0-192.168.2.1:2048,
152  *      given lookup table #0 for field 0 (see example above):
153  *
154  * ::
155  *
156  *                     bucket
157  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
158  *        0    0                                              1,2
159  *        1   1,2                                      0
160  *        2    0                                      1,2
161  *        3    0                              1,2
162  *        4  0,1,2
163  *        5    0   1   2
164  *        6  0,1,2 1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
165  *        7   1,2 1,2  1   1   1  0,1  1   1   1   1   1   1   1   1   1   1
166  *
167  *      and lookup table #1 for field 1 with:
168  *      - rule #0: 1024 mapping to buckets
169  *        < 0  0  4  0 >
170  *      - rule #1: 2048 mapping to buckets
171  *        < 0  0  5  0 >
172  *
173  * ::
174  *
175  *                     bucket
176  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
177  *        0   0,1
178  *        1   0,1
179  *        2                    0   1
180  *        3   0,1
181  *
182  *      we need to map rules for 10.0.0.5 in lookup table #0 (rule #0) to 1024
183  *      in lookup table #1 (rule #0) and rules for 192.168.1.0-192.168.2.1
184  *      (rules #1, #2) to 2048 in lookup table #2 (rule #1):
185  *
186  * ::
187  *
188  *       rule indices in current field: 0    1    2
189  *       map to rules in next field:    0    1    1
190  *
191  *   - if this is the last field in the set, fill a mapping array that maps
192  *     rules from the last lookup table to element pointers, also done by
193  *     pipapo_map().
194  *
195  *     Note that, in this implementation, we have two elements (start, end) for
196  *     each entry. The pointer to the end element is stored in this array, and
197  *     the pointer to the start element is linked from it.
198  *
199  *      Example: entry 10.0.0.5:1024 has a corresponding &struct nft_pipapo_elem
200  *      pointer, 0x66, and element for 192.168.1.0-192.168.2.1:2048 is at 0x42.
201  *      From the rules of lookup table #1 as mapped above:
202  *
203  * ::
204  *
205  *       rule indices in last field:    0    1
206  *       map to elements:             0x66  0x42
207  *
208  *
209  * Matching
210  * --------
211  *
212  * We use a result bitmap, with the size of a single lookup table bucket, to
213  * represent the matching state that applies at every algorithm step. This is
214  * done by pipapo_lookup().
215  *
216  * - For each packet field:
217  *
218  *   - start with an all-ones result bitmap (res_map in pipapo_lookup())
219  *
220  *   - perform a lookup into the table corresponding to the current field,
221  *     for each group, and at every group, AND the current result bitmap with
222  *     the value from the lookup table bucket
223  *
224  * ::
225  *
226  *      Example: 192.168.1.5 < 12 0  10 8  0 1  0 5 >, with lookup table from
227  *      insertion examples.
228  *      Lookup table buckets are at least 3 bits wide, we'll assume 8 bits for
229  *      convenience in this example. Initial result bitmap is 0xff, the steps
230  *      below show the value of the result bitmap after each group is processed:
231  *
232  *                     bucket
233  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
234  *        0    0                                              1,2
235  *        result bitmap is now: 0xff & 0x6 [bucket 12] = 0x6
236  *
237  *        1   1,2                                      0
238  *        result bitmap is now: 0x6 & 0x6 [bucket 0] = 0x6
239  *
240  *        2    0                                      1,2
241  *        result bitmap is now: 0x6 & 0x6 [bucket 10] = 0x6
242  *
243  *        3    0                              1,2
244  *        result bitmap is now: 0x6 & 0x6 [bucket 8] = 0x6
245  *
246  *        4  0,1,2
247  *        result bitmap is now: 0x6 & 0x7 [bucket 0] = 0x6
248  *
249  *        5    0   1   2
250  *        result bitmap is now: 0x6 & 0x2 [bucket 1] = 0x2
251  *
252  *        6  0,1,2 1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
253  *        result bitmap is now: 0x2 & 0x7 [bucket 0] = 0x2
254  *
255  *        7   1,2 1,2  1   1   1  0,1  1   1   1   1   1   1   1   1   1   1
256  *        final result bitmap for this field is: 0x2 & 0x3 [bucket 5] = 0x2
257  *
258  *   - at the next field, start with a new, all-zeroes result bitmap. For each
259  *     bit set in the previous result bitmap, fill the new result bitmap
260  *     (fill_map in pipapo_lookup()) with the rule indices from the
261  *     corresponding buckets of the mapping field for this field, done by
262  *     pipapo_refill()
263  *
264  *      Example: with mapping table from insertion examples, with the current
265  *      result bitmap from the previous example, 0x02:
266  *
267  * ::
268  *
269  *       rule indices in current field: 0    1    2
270  *       map to rules in next field:    0    1    1
271  *
272  *      the new result bitmap will be 0x02: rule 1 was set, and rule 1 will be
273  *      set.
274  *
275  *      We can now extend this example to cover the second iteration of the step
276  *      above (lookup and AND bitmap): assuming the port field is
277  *      2048 < 0  0  5  0 >, with starting result bitmap 0x2, and lookup table
278  *      for "port" field from pre-computation example:
279  *
280  * ::
281  *
282  *                     bucket
283  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
284  *        0   0,1
285  *        1   0,1
286  *        2                    0   1
287  *        3   0,1
288  *
289  *       operations are: 0x2 & 0x3 [bucket 0] & 0x3 [bucket 0] & 0x2 [bucket 5]
290  *       & 0x3 [bucket 0], resulting bitmap is 0x2.
291  *
292  *   - if this is the last field in the set, look up the value from the mapping
293  *     array corresponding to the final result bitmap
294  *
295  *      Example: 0x2 resulting bitmap from 192.168.1.5:2048, mapping array for
296  *      last field from insertion example:
297  *
298  * ::
299  *
300  *       rule indices in last field:    0    1
301  *       map to elements:             0x66  0x42
302  *
303  *      the matching element is at 0x42.
304  *
305  *
306  * References
307  * ----------
308  *
309  * [Ligatti 2010]
310  *      A Packet-classification Algorithm for Arbitrary Bitmask Rules, with
311  *      Automatic Time-space Tradeoffs
312  *      Jay Ligatti, Josh Kuhn, and Chris Gage.
313  *      Proceedings of the IEEE International Conference on Computer
314  *      Communication Networks (ICCCN), August 2010.
315  *      https://www.cse.usf.edu/~ligatti/papers/grouper-conf.pdf
316  *
317  * [Rottenstreich 2010]
318  *      Worst-Case TCAM Rule Expansion
319  *      Ori Rottenstreich and Isaac Keslassy.
320  *      2010 Proceedings IEEE INFOCOM, San Diego, CA, 2010.
321  *      http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.212.4592&rep=rep1&type=pdf
322  *
323  * [Kogan 2014]
324  *      SAX-PAC (Scalable And eXpressive PAcket Classification)
325  *      Kirill Kogan, Sergey Nikolenko, Ori Rottenstreich, William Culhane,
326  *      and Patrick Eugster.
327  *      Proceedings of the 2014 ACM conference on SIGCOMM, August 2014.
328  *      https://www.sigcomm.org/sites/default/files/ccr/papers/2014/August/2619239-2626294.pdf
329  */
330 
331 #include <linux/kernel.h>
332 #include <linux/init.h>
333 #include <linux/module.h>
334 #include <linux/netlink.h>
335 #include <linux/netfilter.h>
336 #include <linux/netfilter/nf_tables.h>
337 #include <net/netfilter/nf_tables_core.h>
338 #include <uapi/linux/netfilter/nf_tables.h>
339 #include <linux/bitmap.h>
340 #include <linux/bitops.h>
341 
342 #include "nft_set_pipapo_avx2.h"
343 #include "nft_set_pipapo.h"
344 
345 /**
346  * pipapo_refill() - For each set bit, set bits from selected mapping table item
347  * @map:	Bitmap to be scanned for set bits
348  * @len:	Length of bitmap in longs
349  * @rules:	Number of rules in field
350  * @dst:	Destination bitmap
351  * @mt:		Mapping table containing bit set specifiers
352  * @match_only:	Find a single bit and return, don't fill
353  *
354  * Iteration over set bits with __builtin_ctzl(): Daniel Lemire, public domain.
355  *
356  * For each bit set in map, select the bucket from mapping table with index
357  * corresponding to the position of the bit set. Use start bit and amount of
358  * bits specified in bucket to fill region in dst.
359  *
360  * Return: -1 on no match, bit position on 'match_only', 0 otherwise.
361  */
pipapo_refill(unsigned long * map,unsigned int len,unsigned int rules,unsigned long * dst,const union nft_pipapo_map_bucket * mt,bool match_only)362 int pipapo_refill(unsigned long *map, unsigned int len, unsigned int rules,
363 		  unsigned long *dst,
364 		  const union nft_pipapo_map_bucket *mt, bool match_only)
365 {
366 	unsigned long bitset;
367 	unsigned int k;
368 	int ret = -1;
369 
370 	for (k = 0; k < len; k++) {
371 		bitset = map[k];
372 		while (bitset) {
373 			unsigned long t = bitset & -bitset;
374 			int r = __builtin_ctzl(bitset);
375 			int i = k * BITS_PER_LONG + r;
376 
377 			if (unlikely(i >= rules)) {
378 				map[k] = 0;
379 				return -1;
380 			}
381 
382 			if (match_only) {
383 				bitmap_clear(map, i, 1);
384 				return i;
385 			}
386 
387 			ret = 0;
388 
389 			bitmap_set(dst, mt[i].to, mt[i].n);
390 
391 			bitset ^= t;
392 		}
393 		map[k] = 0;
394 	}
395 
396 	return ret;
397 }
398 
399 /**
400  * pipapo_get_slow() - Get matching element reference given key data
401  * @m:		storage containing the set elements
402  * @data:	Key data to be matched against existing elements
403  * @genmask:	If set, check that element is active in given genmask
404  * @tstamp:	timestamp to check for expired elements
405  *
406  * For more details, see DOC: Theory of Operation.
407  *
408  * This is the main lookup function.  It matches key data against either
409  * the working match set or the uncommitted copy, depending on what the
410  * caller passed to us.
411  * nft_pipapo_get (lookup from userspace/control plane) and nft_pipapo_lookup
412  * (datapath lookup) pass the active copy.
413  * The insertion path will pass the uncommitted working copy.
414  *
415  * Return: pointer to &struct nft_pipapo_elem on match, NULL otherwise.
416  */
pipapo_get_slow(const struct nft_pipapo_match * m,const u8 * data,u8 genmask,u64 tstamp)417 static struct nft_pipapo_elem *pipapo_get_slow(const struct nft_pipapo_match *m,
418 					       const u8 *data, u8 genmask,
419 					       u64 tstamp)
420 {
421 	unsigned long *res_map, *fill_map, *map;
422 	struct nft_pipapo_scratch *scratch;
423 	const struct nft_pipapo_field *f;
424 	bool map_index;
425 	int i;
426 
427 	local_bh_disable();
428 
429 	scratch = *raw_cpu_ptr(m->scratch);
430 	if (unlikely(!scratch))
431 		goto out;
432 	__local_lock_nested_bh(&scratch->bh_lock);
433 
434 	map_index = scratch->map_index;
435 
436 	map = NFT_PIPAPO_LT_ALIGN(&scratch->__map[0]);
437 	res_map  = map + (map_index ? m->bsize_max : 0);
438 	fill_map = map + (map_index ? 0 : m->bsize_max);
439 
440 	pipapo_resmap_init(m, res_map);
441 
442 	nft_pipapo_for_each_field(f, i, m) {
443 		bool last = i == m->field_count - 1;
444 		int b;
445 
446 		/* For each bit group: select lookup table bucket depending on
447 		 * packet bytes value, then AND bucket value
448 		 */
449 		if (likely(f->bb == 8))
450 			pipapo_and_field_buckets_8bit(f, res_map, data);
451 		else
452 			pipapo_and_field_buckets_4bit(f, res_map, data);
453 		NFT_PIPAPO_GROUP_BITS_ARE_8_OR_4;
454 
455 		/* Now populate the bitmap for the next field, unless this is
456 		 * the last field, in which case return the matched 'ext'
457 		 * pointer if any.
458 		 *
459 		 * Now res_map contains the matching bitmap, and fill_map is the
460 		 * bitmap for the next field.
461 		 */
462 next_match:
463 		b = pipapo_refill(res_map, f->bsize, f->rules, fill_map, f->mt,
464 				  last);
465 		if (b < 0) {
466 			scratch->map_index = map_index;
467 			__local_unlock_nested_bh(&scratch->bh_lock);
468 			local_bh_enable();
469 
470 			return NULL;
471 		}
472 
473 		if (last) {
474 			struct nft_pipapo_elem *e;
475 
476 			e = f->mt[b].e;
477 			if (unlikely(__nft_set_elem_expired(&e->ext, tstamp) ||
478 				     !nft_set_elem_active(&e->ext, genmask)))
479 				goto next_match;
480 
481 			/* Last field: we're just returning the key without
482 			 * filling the initial bitmap for the next field, so the
483 			 * current inactive bitmap is clean and can be reused as
484 			 * *next* bitmap (not initial) for the next packet.
485 			 */
486 			scratch->map_index = map_index;
487 			__local_unlock_nested_bh(&scratch->bh_lock);
488 			local_bh_enable();
489 			return e;
490 		}
491 
492 		/* Swap bitmap indices: res_map is the initial bitmap for the
493 		 * next field, and fill_map is guaranteed to be all-zeroes at
494 		 * this point.
495 		 */
496 		map_index = !map_index;
497 		swap(res_map, fill_map);
498 
499 		data += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
500 	}
501 
502 	__local_unlock_nested_bh(&scratch->bh_lock);
503 out:
504 	local_bh_enable();
505 	return NULL;
506 }
507 
508 /**
509  * pipapo_get() - Get matching element reference given key data
510  * @m:		Storage containing the set elements
511  * @data:	Key data to be matched against existing elements
512  * @genmask:	If set, check that element is active in given genmask
513  * @tstamp:	Timestamp to check for expired elements
514  *
515  * This is a dispatcher function, either calling out the generic C
516  * implementation or, if available, the AVX2 one.
517  * This helper is only called from the control plane, with either RCU
518  * read lock or transaction mutex held.
519  *
520  * Return: pointer to &struct nft_pipapo_elem on match, NULL otherwise.
521  */
pipapo_get(const struct nft_pipapo_match * m,const u8 * data,u8 genmask,u64 tstamp)522 static struct nft_pipapo_elem *pipapo_get(const struct nft_pipapo_match *m,
523 					  const u8 *data, u8 genmask,
524 					  u64 tstamp)
525 {
526 	struct nft_pipapo_elem *e;
527 
528 	local_bh_disable();
529 
530 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
531 	if (boot_cpu_has(X86_FEATURE_AVX2) && irq_fpu_usable()) {
532 		e = pipapo_get_avx2(m, data, genmask, tstamp);
533 		local_bh_enable();
534 		return e;
535 	}
536 #endif
537 	e = pipapo_get_slow(m, data, genmask, tstamp);
538 	local_bh_enable();
539 	return e;
540 }
541 
542 /**
543  * nft_pipapo_lookup() - Dataplane fronted for main lookup function
544  * @net:	Network namespace
545  * @set:	nftables API set representation
546  * @key:	pointer to nft registers containing key data
547  *
548  * This function is called from the data path.  It will search for
549  * an element matching the given key in the current active copy.
550  * Unlike other set types, this uses 0 instead of nft_genmask_cur().
551  *
552  * This is because new (future) elements are not reachable from
553  * priv->match, they get added to priv->clone instead.
554  * When the commit phase flips the generation bitmask, the
555  * 'now old' entries are skipped but without the 'now current'
556  * elements becoming visible. Using nft_genmask_cur() thus creates
557  * inconsistent state: matching old entries get skipped but thew
558  * newly matching entries are unreachable.
559  *
560  * GENMASK_ANY doesn't work for the same reason: old-gen entries get
561  * skipped, new-gen entries are only reachable from priv->clone.
562  *
563  * nft_pipapo_commit swaps ->clone and ->match shortly after the
564  * genbit flip.  As ->clone doesn't contain the old entries in the first
565  * place, lookup will only find the now-current ones.
566  *
567  * Return: ntables API extension pointer or NULL if no match.
568  */
569 const struct nft_set_ext *
nft_pipapo_lookup(const struct net * net,const struct nft_set * set,const u32 * key)570 nft_pipapo_lookup(const struct net *net, const struct nft_set *set,
571 		  const u32 *key)
572 {
573 	struct nft_pipapo *priv = nft_set_priv(set);
574 	const struct nft_pipapo_match *m;
575 	const struct nft_pipapo_elem *e;
576 
577 	m = rcu_dereference(priv->match);
578 	e = pipapo_get_slow(m, (const u8 *)key, 0, get_jiffies_64());
579 
580 	return e ? &e->ext : NULL;
581 }
582 
583 /**
584  * nft_pipapo_get() - Get matching element reference given key data
585  * @net:	Network namespace
586  * @set:	nftables API set representation
587  * @elem:	nftables API element representation containing key data
588  * @flags:	Unused
589  *
590  * This function is called from the control plane path under
591  * RCU read lock.
592  *
593  * Return: set element private pointer or ERR_PTR(-ENOENT).
594  */
595 static struct nft_elem_priv *
nft_pipapo_get(const struct net * net,const struct nft_set * set,const struct nft_set_elem * elem,unsigned int flags)596 nft_pipapo_get(const struct net *net, const struct nft_set *set,
597 	       const struct nft_set_elem *elem, unsigned int flags)
598 {
599 	struct nft_pipapo *priv = nft_set_priv(set);
600 	struct nft_pipapo_match *m = rcu_dereference(priv->match);
601 	struct nft_pipapo_elem *e;
602 
603 	e = pipapo_get(m, (const u8 *)elem->key.val.data,
604 		       nft_genmask_cur(net), get_jiffies_64());
605 	if (!e)
606 		return ERR_PTR(-ENOENT);
607 
608 	return &e->priv;
609 }
610 
611 /**
612  * pipapo_realloc_mt() - Reallocate mapping table if needed upon resize
613  * @f:		Field containing mapping table
614  * @old_rules:	Amount of existing mapped rules
615  * @rules:	Amount of new rules to map
616  *
617  * Return: 0 on success, negative error code on failure.
618  */
pipapo_realloc_mt(struct nft_pipapo_field * f,unsigned int old_rules,unsigned int rules)619 static int pipapo_realloc_mt(struct nft_pipapo_field *f,
620 			     unsigned int old_rules, unsigned int rules)
621 {
622 	union nft_pipapo_map_bucket *new_mt = NULL, *old_mt = f->mt;
623 	const unsigned int extra = PAGE_SIZE / sizeof(*new_mt);
624 	unsigned int rules_alloc = rules;
625 
626 	might_sleep();
627 
628 	if (unlikely(rules == 0))
629 		goto out_free;
630 
631 	/* growing and enough space left, no action needed */
632 	if (rules > old_rules && f->rules_alloc > rules)
633 		return 0;
634 
635 	/* downsize and extra slack has not grown too large */
636 	if (rules < old_rules) {
637 		unsigned int remove = f->rules_alloc - rules;
638 
639 		if (remove < (2u * extra))
640 			return 0;
641 	}
642 
643 	/* If set needs more than one page of memory for rules then
644 	 * allocate another extra page to avoid frequent reallocation.
645 	 */
646 	if (rules > extra &&
647 	    check_add_overflow(rules, extra, &rules_alloc))
648 		return -EOVERFLOW;
649 
650 	if (rules_alloc > (INT_MAX / sizeof(*new_mt)))
651 		return -ENOMEM;
652 
653 	new_mt = kvmalloc_objs(*new_mt, rules_alloc, GFP_KERNEL_ACCOUNT);
654 	if (!new_mt)
655 		return -ENOMEM;
656 
657 	if (old_mt)
658 		memcpy(new_mt, old_mt, min(old_rules, rules) * sizeof(*new_mt));
659 
660 	if (rules > old_rules) {
661 		memset(new_mt + old_rules, 0,
662 		       (rules - old_rules) * sizeof(*new_mt));
663 	}
664 out_free:
665 	f->rules_alloc = rules_alloc;
666 	f->mt = new_mt;
667 
668 	kvfree(old_mt);
669 
670 	return 0;
671 }
672 
673 
674 /**
675  * lt_calculate_size() - Get storage size for lookup table with overflow check
676  * @groups:	Amount of bit groups
677  * @bb:		Number of bits grouped together in lookup table buckets
678  * @bsize:	Size of each bucket in lookup table, in longs
679  *
680  * Return: allocation size including alignment overhead, negative on overflow
681  */
lt_calculate_size(unsigned int groups,unsigned int bb,unsigned int bsize)682 static ssize_t lt_calculate_size(unsigned int groups, unsigned int bb,
683 				 unsigned int bsize)
684 {
685 	ssize_t ret = groups * NFT_PIPAPO_BUCKETS(bb) * sizeof(long);
686 
687 	if (check_mul_overflow(ret, bsize, &ret))
688 		return -1;
689 	if (check_add_overflow(ret, NFT_PIPAPO_ALIGN_HEADROOM, &ret))
690 		return -1;
691 	if (ret > INT_MAX)
692 		return -1;
693 
694 	return ret;
695 }
696 
697 /**
698  * pipapo_resize() - Resize lookup or mapping table, or both
699  * @f:		Field containing lookup and mapping tables
700  * @old_rules:	Previous amount of rules in field
701  * @rules:	New amount of rules
702  *
703  * Increase, decrease or maintain tables size depending on new amount of rules,
704  * and copy data over. In case the new size is smaller, throw away data for
705  * highest-numbered rules.
706  *
707  * Return: 0 on success, -ENOMEM on allocation failure.
708  */
pipapo_resize(struct nft_pipapo_field * f,unsigned int old_rules,unsigned int rules)709 static int pipapo_resize(struct nft_pipapo_field *f,
710 			 unsigned int old_rules, unsigned int rules)
711 {
712 	long *new_lt = NULL, *new_p, *old_lt = f->lt, *old_p;
713 	unsigned int new_bucket_size, copy;
714 	int group, bucket, err;
715 	ssize_t lt_size;
716 
717 	if (rules >= NFT_PIPAPO_RULE0_MAX)
718 		return -ENOSPC;
719 
720 	new_bucket_size = DIV_ROUND_UP(rules, BITS_PER_LONG);
721 #ifdef NFT_PIPAPO_ALIGN
722 	new_bucket_size = roundup(new_bucket_size,
723 				  NFT_PIPAPO_ALIGN / sizeof(*new_lt));
724 #endif
725 
726 	if (new_bucket_size == f->bsize)
727 		goto mt;
728 
729 	if (new_bucket_size > f->bsize)
730 		copy = f->bsize;
731 	else
732 		copy = new_bucket_size;
733 
734 	lt_size = lt_calculate_size(f->groups, f->bb, new_bucket_size);
735 	if (lt_size < 0)
736 		return -ENOMEM;
737 
738 	new_lt = kvzalloc(lt_size, GFP_KERNEL_ACCOUNT);
739 	if (!new_lt)
740 		return -ENOMEM;
741 
742 	new_p = NFT_PIPAPO_LT_ALIGN(new_lt);
743 	old_p = NFT_PIPAPO_LT_ALIGN(old_lt);
744 
745 	for (group = 0; group < f->groups; group++) {
746 		for (bucket = 0; bucket < NFT_PIPAPO_BUCKETS(f->bb); bucket++) {
747 			memcpy(new_p, old_p, copy * sizeof(*new_p));
748 			new_p += copy;
749 			old_p += copy;
750 
751 			if (new_bucket_size > f->bsize)
752 				new_p += new_bucket_size - f->bsize;
753 			else
754 				old_p += f->bsize - new_bucket_size;
755 		}
756 	}
757 
758 mt:
759 	err = pipapo_realloc_mt(f, old_rules, rules);
760 	if (err) {
761 		kvfree(new_lt);
762 		return err;
763 	}
764 
765 	if (new_lt) {
766 		f->bsize = new_bucket_size;
767 		f->lt = new_lt;
768 		kvfree(old_lt);
769 	}
770 
771 	return 0;
772 }
773 
774 /**
775  * pipapo_bucket_set() - Set rule bit in bucket given group and group value
776  * @f:		Field containing lookup table
777  * @rule:	Rule index
778  * @group:	Group index
779  * @v:		Value of bit group
780  */
pipapo_bucket_set(struct nft_pipapo_field * f,int rule,int group,int v)781 static void pipapo_bucket_set(struct nft_pipapo_field *f, int rule, int group,
782 			      int v)
783 {
784 	unsigned long *pos;
785 
786 	pos = NFT_PIPAPO_LT_ALIGN(f->lt);
787 	pos += f->bsize * NFT_PIPAPO_BUCKETS(f->bb) * group;
788 	pos += f->bsize * v;
789 
790 	__set_bit(rule, pos);
791 }
792 
793 /**
794  * pipapo_lt_4b_to_8b() - Switch lookup table group width from 4 bits to 8 bits
795  * @old_groups:	Number of current groups
796  * @bsize:	Size of one bucket, in longs
797  * @old_lt:	Pointer to the current lookup table
798  * @new_lt:	Pointer to the new, pre-allocated lookup table
799  *
800  * Each bucket with index b in the new lookup table, belonging to group g, is
801  * filled with the bit intersection between:
802  * - bucket with index given by the upper 4 bits of b, from group g, and
803  * - bucket with index given by the lower 4 bits of b, from group g + 1
804  *
805  * That is, given buckets from the new lookup table N(x, y) and the old lookup
806  * table O(x, y), with x bucket index, and y group index:
807  *
808  *	N(b, g) := O(b / 16, g) & O(b % 16, g + 1)
809  *
810  * This ensures equivalence of the matching results on lookup. Two examples in
811  * pictures:
812  *
813  *              bucket
814  *  group  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 ... 254 255
815  *    0                ^
816  *    1                |                                                 ^
817  *   ...             ( & )                                               |
818  *                  /     \                                              |
819  *                 /       \                                         .-( & )-.
820  *                /  bucket \                                        |       |
821  *      group  0 / 1   2   3 \ 4   5   6   7   8   9  10  11  12  13 |14  15 |
822  *        0     /             \                                      |       |
823  *        1                    \                                     |       |
824  *        2                                                          |     --'
825  *        3                                                          '-
826  *       ...
827  */
pipapo_lt_4b_to_8b(int old_groups,int bsize,unsigned long * old_lt,unsigned long * new_lt)828 static void pipapo_lt_4b_to_8b(int old_groups, int bsize,
829 			       unsigned long *old_lt, unsigned long *new_lt)
830 {
831 	int g, b, i;
832 
833 	for (g = 0; g < old_groups / 2; g++) {
834 		int src_g0 = g * 2, src_g1 = g * 2 + 1;
835 
836 		for (b = 0; b < NFT_PIPAPO_BUCKETS(8); b++) {
837 			int src_b0 = b / NFT_PIPAPO_BUCKETS(4);
838 			int src_b1 = b % NFT_PIPAPO_BUCKETS(4);
839 			int src_i0 = src_g0 * NFT_PIPAPO_BUCKETS(4) + src_b0;
840 			int src_i1 = src_g1 * NFT_PIPAPO_BUCKETS(4) + src_b1;
841 
842 			for (i = 0; i < bsize; i++) {
843 				*new_lt = old_lt[src_i0 * bsize + i] &
844 					  old_lt[src_i1 * bsize + i];
845 				new_lt++;
846 			}
847 		}
848 	}
849 }
850 
851 /**
852  * pipapo_lt_8b_to_4b() - Switch lookup table group width from 8 bits to 4 bits
853  * @old_groups:	Number of current groups
854  * @bsize:	Size of one bucket, in longs
855  * @old_lt:	Pointer to the current lookup table
856  * @new_lt:	Pointer to the new, pre-allocated lookup table
857  *
858  * Each bucket with index b in the new lookup table, belonging to group g, is
859  * filled with the bit union of:
860  * - all the buckets with index such that the upper four bits of the lower byte
861  *   equal b, from group g, with g odd
862  * - all the buckets with index such that the lower four bits equal b, from
863  *   group g, with g even
864  *
865  * That is, given buckets from the new lookup table N(x, y) and the old lookup
866  * table O(x, y), with x bucket index, and y group index:
867  *
868  *	- with g odd:  N(b, g) := U(O(x, g) for each x : x = (b & 0xf0) >> 4)
869  *	- with g even: N(b, g) := U(O(x, g) for each x : x = b & 0x0f)
870  *
871  * where U() denotes the arbitrary union operation (binary OR of n terms). This
872  * ensures equivalence of the matching results on lookup.
873  */
pipapo_lt_8b_to_4b(int old_groups,int bsize,unsigned long * old_lt,unsigned long * new_lt)874 static void pipapo_lt_8b_to_4b(int old_groups, int bsize,
875 			       unsigned long *old_lt, unsigned long *new_lt)
876 {
877 	int g, b, bsrc, i;
878 
879 	memset(new_lt, 0, old_groups * 2 * NFT_PIPAPO_BUCKETS(4) * bsize *
880 			  sizeof(unsigned long));
881 
882 	for (g = 0; g < old_groups * 2; g += 2) {
883 		int src_g = g / 2;
884 
885 		for (b = 0; b < NFT_PIPAPO_BUCKETS(4); b++) {
886 			for (bsrc = NFT_PIPAPO_BUCKETS(8) * src_g;
887 			     bsrc < NFT_PIPAPO_BUCKETS(8) * (src_g + 1);
888 			     bsrc++) {
889 				if (((bsrc & 0xf0) >> 4) != b)
890 					continue;
891 
892 				for (i = 0; i < bsize; i++)
893 					new_lt[i] |= old_lt[bsrc * bsize + i];
894 			}
895 
896 			new_lt += bsize;
897 		}
898 
899 		for (b = 0; b < NFT_PIPAPO_BUCKETS(4); b++) {
900 			for (bsrc = NFT_PIPAPO_BUCKETS(8) * src_g;
901 			     bsrc < NFT_PIPAPO_BUCKETS(8) * (src_g + 1);
902 			     bsrc++) {
903 				if ((bsrc & 0x0f) != b)
904 					continue;
905 
906 				for (i = 0; i < bsize; i++)
907 					new_lt[i] |= old_lt[bsrc * bsize + i];
908 			}
909 
910 			new_lt += bsize;
911 		}
912 	}
913 }
914 
915 /**
916  * pipapo_lt_bits_adjust() - Adjust group size for lookup table if needed
917  * @f:		Field containing lookup table
918  */
pipapo_lt_bits_adjust(struct nft_pipapo_field * f)919 static void pipapo_lt_bits_adjust(struct nft_pipapo_field *f)
920 {
921 	unsigned int groups, bb;
922 	unsigned long *new_lt;
923 	ssize_t lt_size;
924 
925 	lt_size = f->groups * NFT_PIPAPO_BUCKETS(f->bb) * f->bsize *
926 		  sizeof(*f->lt);
927 
928 	if (f->bb == NFT_PIPAPO_GROUP_BITS_SMALL_SET &&
929 	    lt_size > NFT_PIPAPO_LT_SIZE_HIGH) {
930 		groups = f->groups * 2;
931 		bb = NFT_PIPAPO_GROUP_BITS_LARGE_SET;
932 
933 		lt_size = lt_calculate_size(groups, bb, f->bsize);
934 		if (lt_size < 0)
935 			return;
936 	} else if (f->bb == NFT_PIPAPO_GROUP_BITS_LARGE_SET &&
937 		   lt_size < NFT_PIPAPO_LT_SIZE_LOW) {
938 		groups = f->groups / 2;
939 		bb = NFT_PIPAPO_GROUP_BITS_SMALL_SET;
940 
941 		lt_size = lt_calculate_size(groups, bb, f->bsize);
942 		if (lt_size < 0)
943 			return;
944 
945 		/* Don't increase group width if the resulting lookup table size
946 		 * would exceed the upper size threshold for a "small" set.
947 		 */
948 		if (lt_size > NFT_PIPAPO_LT_SIZE_HIGH)
949 			return;
950 	} else {
951 		return;
952 	}
953 
954 	new_lt = kvzalloc(lt_size, GFP_KERNEL_ACCOUNT);
955 	if (!new_lt)
956 		return;
957 
958 	NFT_PIPAPO_GROUP_BITS_ARE_8_OR_4;
959 	if (f->bb == 4 && bb == 8) {
960 		pipapo_lt_4b_to_8b(f->groups, f->bsize,
961 				   NFT_PIPAPO_LT_ALIGN(f->lt),
962 				   NFT_PIPAPO_LT_ALIGN(new_lt));
963 	} else if (f->bb == 8 && bb == 4) {
964 		pipapo_lt_8b_to_4b(f->groups, f->bsize,
965 				   NFT_PIPAPO_LT_ALIGN(f->lt),
966 				   NFT_PIPAPO_LT_ALIGN(new_lt));
967 	} else {
968 		BUG();
969 	}
970 
971 	f->groups = groups;
972 	f->bb = bb;
973 	kvfree(f->lt);
974 	f->lt = new_lt;
975 }
976 
977 /**
978  * pipapo_insert() - Insert new rule in field given input key and mask length
979  * @f:		Field containing lookup table
980  * @k:		Input key for classification, without nftables padding
981  * @mask_bits:	Length of mask; matches field length for non-ranged entry
982  *
983  * Insert a new rule reference in lookup buckets corresponding to k and
984  * mask_bits.
985  *
986  * Return: 1 on success (one rule inserted), negative error code on failure.
987  */
pipapo_insert(struct nft_pipapo_field * f,const uint8_t * k,int mask_bits)988 static int pipapo_insert(struct nft_pipapo_field *f, const uint8_t *k,
989 			 int mask_bits)
990 {
991 	unsigned int rule = f->rules, group, ret, bit_offset = 0;
992 
993 	ret = pipapo_resize(f, f->rules, f->rules + 1);
994 	if (ret)
995 		return ret;
996 
997 	f->rules++;
998 
999 	for (group = 0; group < f->groups; group++) {
1000 		int i, v;
1001 		u8 mask;
1002 
1003 		v = k[group / (BITS_PER_BYTE / f->bb)];
1004 		v &= GENMASK(BITS_PER_BYTE - bit_offset - 1, 0);
1005 		v >>= (BITS_PER_BYTE - bit_offset) - f->bb;
1006 
1007 		bit_offset += f->bb;
1008 		bit_offset %= BITS_PER_BYTE;
1009 
1010 		if (mask_bits >= (group + 1) * f->bb) {
1011 			/* Not masked */
1012 			pipapo_bucket_set(f, rule, group, v);
1013 		} else if (mask_bits <= group * f->bb) {
1014 			/* Completely masked */
1015 			for (i = 0; i < NFT_PIPAPO_BUCKETS(f->bb); i++)
1016 				pipapo_bucket_set(f, rule, group, i);
1017 		} else {
1018 			/* The mask limit falls on this group */
1019 			mask = GENMASK(f->bb - 1, 0);
1020 			mask >>= mask_bits - group * f->bb;
1021 			for (i = 0; i < NFT_PIPAPO_BUCKETS(f->bb); i++) {
1022 				if ((i & ~mask) == (v & ~mask))
1023 					pipapo_bucket_set(f, rule, group, i);
1024 			}
1025 		}
1026 	}
1027 
1028 	pipapo_lt_bits_adjust(f);
1029 
1030 	return 1;
1031 }
1032 
1033 /**
1034  * pipapo_step_diff() - Check if setting @step bit in netmask would change it
1035  * @base:	Mask we are expanding
1036  * @step:	Step bit for given expansion step
1037  * @len:	Total length of mask space (set and unset bits), bytes
1038  *
1039  * Convenience function for mask expansion.
1040  *
1041  * Return: true if step bit changes mask (i.e. isn't set), false otherwise.
1042  */
pipapo_step_diff(u8 * base,int step,int len)1043 static bool pipapo_step_diff(u8 *base, int step, int len)
1044 {
1045 	/* Network order, byte-addressed */
1046 #ifdef __BIG_ENDIAN__
1047 	return !(BIT(step % BITS_PER_BYTE) & base[step / BITS_PER_BYTE]);
1048 #else
1049 	return !(BIT(step % BITS_PER_BYTE) &
1050 		 base[len - 1 - step / BITS_PER_BYTE]);
1051 #endif
1052 }
1053 
1054 /**
1055  * pipapo_step_after_end() - Check if mask exceeds range end with given step
1056  * @base:	Mask we are expanding
1057  * @end:	End of range
1058  * @step:	Step bit for given expansion step, highest bit to be set
1059  * @len:	Total length of mask space (set and unset bits), bytes
1060  *
1061  * Convenience function for mask expansion.
1062  *
1063  * Return: true if mask exceeds range setting step bits, false otherwise.
1064  */
pipapo_step_after_end(const u8 * base,const u8 * end,int step,int len)1065 static bool pipapo_step_after_end(const u8 *base, const u8 *end, int step,
1066 				  int len)
1067 {
1068 	u8 tmp[NFT_PIPAPO_MAX_BYTES];
1069 	int i;
1070 
1071 	memcpy(tmp, base, len);
1072 
1073 	/* Network order, byte-addressed */
1074 	for (i = 0; i <= step; i++)
1075 #ifdef __BIG_ENDIAN__
1076 		tmp[i / BITS_PER_BYTE] |= BIT(i % BITS_PER_BYTE);
1077 #else
1078 		tmp[len - 1 - i / BITS_PER_BYTE] |= BIT(i % BITS_PER_BYTE);
1079 #endif
1080 
1081 	return memcmp(tmp, end, len) > 0;
1082 }
1083 
1084 /**
1085  * pipapo_base_sum() - Sum step bit to given len-sized netmask base with carry
1086  * @base:	Netmask base
1087  * @step:	Step bit to sum
1088  * @len:	Netmask length, bytes
1089  */
pipapo_base_sum(u8 * base,int step,int len)1090 static void pipapo_base_sum(u8 *base, int step, int len)
1091 {
1092 	bool carry = false;
1093 	int i;
1094 
1095 	/* Network order, byte-addressed */
1096 #ifdef __BIG_ENDIAN__
1097 	for (i = step / BITS_PER_BYTE; i < len; i++) {
1098 #else
1099 	for (i = len - 1 - step / BITS_PER_BYTE; i >= 0; i--) {
1100 #endif
1101 		if (carry)
1102 			base[i]++;
1103 		else
1104 			base[i] += 1 << (step % BITS_PER_BYTE);
1105 
1106 		if (base[i])
1107 			break;
1108 
1109 		carry = true;
1110 	}
1111 }
1112 
1113 /**
1114  * pipapo_expand() - Expand to composing netmasks, insert into lookup table
1115  * @f:		Field containing lookup table
1116  * @start:	Start of range
1117  * @end:	End of range
1118  * @len:	Length of value in bits
1119  *
1120  * Expand range to composing netmasks and insert corresponding rule references
1121  * in lookup buckets.
1122  *
1123  * Return: number of inserted rules on success, negative error code on failure.
1124  */
1125 static int pipapo_expand(struct nft_pipapo_field *f,
1126 			 const u8 *start, const u8 *end, int len)
1127 {
1128 	int step, masks = 0, bytes = DIV_ROUND_UP(len, BITS_PER_BYTE);
1129 	u8 base[NFT_PIPAPO_MAX_BYTES];
1130 
1131 	memcpy(base, start, bytes);
1132 	while (memcmp(base, end, bytes) <= 0) {
1133 		int err;
1134 
1135 		step = 0;
1136 		while (pipapo_step_diff(base, step, bytes)) {
1137 			if (pipapo_step_after_end(base, end, step, bytes))
1138 				break;
1139 
1140 			step++;
1141 			if (step >= len) {
1142 				if (!masks) {
1143 					err = pipapo_insert(f, base, 0);
1144 					if (err < 0)
1145 						return err;
1146 					masks = 1;
1147 				}
1148 				goto out;
1149 			}
1150 		}
1151 
1152 		err = pipapo_insert(f, base, len - step);
1153 
1154 		if (err < 0)
1155 			return err;
1156 
1157 		masks++;
1158 		pipapo_base_sum(base, step, bytes);
1159 	}
1160 out:
1161 	return masks;
1162 }
1163 
1164 /**
1165  * pipapo_map() - Insert rules in mapping tables, mapping them between fields
1166  * @m:		Matching data, including mapping table
1167  * @map:	Table of rule maps: array of first rule and amount of rules
1168  *		in next field a given rule maps to, for each field
1169  * @e:		For last field, nft_set_ext pointer matching rules map to
1170  */
1171 static void pipapo_map(struct nft_pipapo_match *m,
1172 		       union nft_pipapo_map_bucket map[NFT_PIPAPO_MAX_FIELDS],
1173 		       struct nft_pipapo_elem *e)
1174 {
1175 	struct nft_pipapo_field *f;
1176 	int i, j;
1177 
1178 	for (i = 0, f = m->f; i < m->field_count - 1; i++, f++) {
1179 		for (j = 0; j < map[i].n; j++) {
1180 			f->mt[map[i].to + j].to = map[i + 1].to;
1181 			f->mt[map[i].to + j].n = map[i + 1].n;
1182 		}
1183 	}
1184 
1185 	/* Last field: map to ext instead of mapping to next field */
1186 	for (j = 0; j < map[i].n; j++)
1187 		f->mt[map[i].to + j].e = e;
1188 }
1189 
1190 /**
1191  * pipapo_free_scratch() - Free per-CPU map at original address
1192  * @m:		Matching data
1193  * @cpu:	CPU number
1194  */
1195 static void pipapo_free_scratch(const struct nft_pipapo_match *m, unsigned int cpu)
1196 {
1197 	struct nft_pipapo_scratch *s;
1198 
1199 	s = *per_cpu_ptr(m->scratch, cpu);
1200 
1201 	kvfree(s);
1202 }
1203 
1204 /**
1205  * pipapo_realloc_scratch() - Reallocate scratch maps for partial match results
1206  * @clone:	Copy of matching data with pending insertions and deletions
1207  * @bsize_max:	Maximum bucket size, scratch maps cover two buckets
1208  *
1209  * Return: 0 on success, -ENOMEM on failure.
1210  */
1211 static int pipapo_realloc_scratch(struct nft_pipapo_match *clone,
1212 				  unsigned long bsize_max)
1213 {
1214 	int i;
1215 
1216 	for_each_possible_cpu(i) {
1217 		struct nft_pipapo_scratch *scratch;
1218 
1219 		scratch = kvzalloc_node(struct_size(scratch, __map, bsize_max * 2) +
1220 					NFT_PIPAPO_ALIGN_HEADROOM,
1221 					GFP_KERNEL_ACCOUNT, cpu_to_node(i));
1222 		if (!scratch) {
1223 			/* On failure, there's no need to undo previous
1224 			 * allocations: this means that some scratch maps have
1225 			 * a bigger allocated size now (this is only called on
1226 			 * insertion), but the extra space won't be used by any
1227 			 * CPU as new elements are not inserted and m->bsize_max
1228 			 * is not updated.
1229 			 */
1230 			return -ENOMEM;
1231 		}
1232 
1233 		pipapo_free_scratch(clone, i);
1234 		local_lock_init(&scratch->bh_lock);
1235 		*per_cpu_ptr(clone->scratch, i) = scratch;
1236 	}
1237 
1238 	return 0;
1239 }
1240 
1241 static bool nft_pipapo_transaction_mutex_held(const struct nft_set *set)
1242 {
1243 #ifdef CONFIG_PROVE_LOCKING
1244 	const struct net *net = read_pnet(&set->net);
1245 
1246 	return lockdep_is_held(&nft_pernet(net)->commit_mutex);
1247 #else
1248 	return true;
1249 #endif
1250 }
1251 
1252 static struct nft_pipapo_match *pipapo_clone(struct nft_pipapo_match *old);
1253 
1254 /**
1255  * pipapo_maybe_clone() - Build clone for pending data changes, if not existing
1256  * @set:	nftables API set representation
1257  *
1258  * Return: newly created or existing clone, if any. NULL on allocation failure
1259  */
1260 static struct nft_pipapo_match *pipapo_maybe_clone(const struct nft_set *set)
1261 {
1262 	struct nft_pipapo *priv = nft_set_priv(set);
1263 	struct nft_pipapo_match *m;
1264 
1265 	if (priv->clone)
1266 		return priv->clone;
1267 
1268 	m = rcu_dereference_protected(priv->match,
1269 				      nft_pipapo_transaction_mutex_held(set));
1270 	priv->clone = pipapo_clone(m);
1271 
1272 	return priv->clone;
1273 }
1274 
1275 /**
1276  * nft_pipapo_insert() - Validate and insert ranged elements
1277  * @net:	Network namespace
1278  * @set:	nftables API set representation
1279  * @elem:	nftables API element representation containing key data
1280  * @elem_priv:	Filled with pointer to &struct nft_set_ext in inserted element
1281  *
1282  * Return: 0 on success, error pointer on failure.
1283  */
1284 static int nft_pipapo_insert(const struct net *net, const struct nft_set *set,
1285 			     const struct nft_set_elem *elem,
1286 			     struct nft_elem_priv **elem_priv)
1287 {
1288 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
1289 	union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1290 	const u8 *start = (const u8 *)elem->key.val.data, *end;
1291 	struct nft_pipapo_match *m = pipapo_maybe_clone(set);
1292 	u8 genmask = nft_genmask_next(net);
1293 	struct nft_pipapo_elem *e, *dup;
1294 	u64 tstamp = nft_net_tstamp(net);
1295 	struct nft_pipapo_field *f;
1296 	const u8 *start_p, *end_p;
1297 	int i, bsize_max, err = 0;
1298 
1299 	if (!m)
1300 		return -ENOMEM;
1301 
1302 	if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END))
1303 		end = (const u8 *)nft_set_ext_key_end(ext)->data;
1304 	else
1305 		end = start;
1306 
1307 	dup = pipapo_get(m, start, genmask, tstamp);
1308 	if (dup) {
1309 		/* Check if we already have the same exact entry */
1310 		const struct nft_data *dup_key, *dup_end;
1311 
1312 		dup_key = nft_set_ext_key(&dup->ext);
1313 		if (nft_set_ext_exists(&dup->ext, NFT_SET_EXT_KEY_END))
1314 			dup_end = nft_set_ext_key_end(&dup->ext);
1315 		else
1316 			dup_end = dup_key;
1317 
1318 		if (!memcmp(start, dup_key->data, set->klen) &&
1319 		    !memcmp(end, dup_end->data, set->klen)) {
1320 			*elem_priv = &dup->priv;
1321 			return -EEXIST;
1322 		}
1323 
1324 		return -ENOTEMPTY;
1325 	}
1326 
1327 	/* Look for partially overlapping entries */
1328 	dup = pipapo_get(m, end, nft_genmask_next(net), tstamp);
1329 	if (dup) {
1330 		*elem_priv = &dup->priv;
1331 		return -ENOTEMPTY;
1332 	}
1333 
1334 	/* Validate */
1335 	start_p = start;
1336 	end_p = end;
1337 
1338 	/* some helpers return -1, or 0 >= for valid rule pos,
1339 	 * so we cannot support more than INT_MAX rules at this time.
1340 	 */
1341 	BUILD_BUG_ON(NFT_PIPAPO_RULE0_MAX > INT_MAX);
1342 
1343 	nft_pipapo_for_each_field(f, i, m) {
1344 		if (f->rules >= NFT_PIPAPO_RULE0_MAX)
1345 			return -ENOSPC;
1346 
1347 		if (memcmp(start_p, end_p,
1348 			   f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f)) > 0)
1349 			return -EINVAL;
1350 
1351 		start_p += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1352 		end_p += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1353 	}
1354 
1355 	/* Insert */
1356 	bsize_max = m->bsize_max;
1357 
1358 	nft_pipapo_for_each_field(f, i, m) {
1359 		int ret;
1360 
1361 		rulemap[i].to = f->rules;
1362 
1363 		ret = memcmp(start, end,
1364 			     f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f));
1365 		if (!ret)
1366 			ret = pipapo_insert(f, start, f->groups * f->bb);
1367 		else
1368 			ret = pipapo_expand(f, start, end, f->groups * f->bb);
1369 
1370 		if (ret < 0)
1371 			return ret;
1372 
1373 		if (f->bsize > bsize_max)
1374 			bsize_max = f->bsize;
1375 
1376 		rulemap[i].n = ret;
1377 
1378 		start += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1379 		end += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1380 	}
1381 
1382 	if (!*get_cpu_ptr(m->scratch) || bsize_max > m->bsize_max) {
1383 		put_cpu_ptr(m->scratch);
1384 
1385 		err = pipapo_realloc_scratch(m, bsize_max);
1386 		if (err)
1387 			return err;
1388 
1389 		m->bsize_max = bsize_max;
1390 	} else {
1391 		put_cpu_ptr(m->scratch);
1392 	}
1393 
1394 	e = nft_elem_priv_cast(elem->priv);
1395 	*elem_priv = &e->priv;
1396 
1397 	pipapo_map(m, rulemap, e);
1398 
1399 	return 0;
1400 }
1401 
1402 /**
1403  * pipapo_clone() - Clone matching data to create new working copy
1404  * @old:	Existing matching data
1405  *
1406  * Return: copy of matching data passed as 'old' or NULL.
1407  */
1408 static struct nft_pipapo_match *pipapo_clone(struct nft_pipapo_match *old)
1409 {
1410 	struct nft_pipapo_field *dst, *src;
1411 	struct nft_pipapo_match *new;
1412 	int i;
1413 
1414 	new = kmalloc_flex(*new, f, old->field_count, GFP_KERNEL_ACCOUNT);
1415 	if (!new)
1416 		return NULL;
1417 
1418 	new->field_count = old->field_count;
1419 	new->bsize_max = old->bsize_max;
1420 
1421 	new->scratch = alloc_percpu(*new->scratch);
1422 	if (!new->scratch)
1423 		goto out_scratch;
1424 
1425 	for_each_possible_cpu(i)
1426 		*per_cpu_ptr(new->scratch, i) = NULL;
1427 
1428 	if (pipapo_realloc_scratch(new, old->bsize_max))
1429 		goto out_scratch_realloc;
1430 
1431 	rcu_head_init(&new->rcu);
1432 
1433 	src = old->f;
1434 	dst = new->f;
1435 
1436 	for (i = 0; i < old->field_count; i++) {
1437 		unsigned long *new_lt;
1438 		ssize_t lt_size;
1439 
1440 		memcpy(dst, src, offsetof(struct nft_pipapo_field, lt));
1441 
1442 		lt_size = lt_calculate_size(src->groups, src->bb, src->bsize);
1443 		if (lt_size < 0)
1444 			goto out_lt;
1445 
1446 		new_lt = kvzalloc(lt_size, GFP_KERNEL_ACCOUNT);
1447 		if (!new_lt)
1448 			goto out_lt;
1449 
1450 		dst->lt = new_lt;
1451 
1452 		memcpy(NFT_PIPAPO_LT_ALIGN(new_lt),
1453 		       NFT_PIPAPO_LT_ALIGN(src->lt),
1454 		       src->bsize * sizeof(*dst->lt) *
1455 		       src->groups * NFT_PIPAPO_BUCKETS(src->bb));
1456 
1457 		if (src->rules > 0) {
1458 			if (src->rules_alloc > (INT_MAX / sizeof(*src->mt)))
1459 				goto out_mt;
1460 
1461 			dst->mt = kvmalloc_objs(*src->mt, src->rules_alloc,
1462 						GFP_KERNEL_ACCOUNT);
1463 			if (!dst->mt)
1464 				goto out_mt;
1465 
1466 			memcpy(dst->mt, src->mt, src->rules * sizeof(*src->mt));
1467 		} else {
1468 			dst->mt = NULL;
1469 			dst->rules_alloc = 0;
1470 		}
1471 
1472 		src++;
1473 		dst++;
1474 	}
1475 
1476 	return new;
1477 
1478 out_mt:
1479 	kvfree(dst->lt);
1480 out_lt:
1481 	for (dst--; i > 0; i--) {
1482 		kvfree(dst->mt);
1483 		kvfree(dst->lt);
1484 		dst--;
1485 	}
1486 out_scratch_realloc:
1487 	for_each_possible_cpu(i)
1488 		pipapo_free_scratch(new, i);
1489 out_scratch:
1490 	free_percpu(new->scratch);
1491 	kfree(new);
1492 
1493 	return NULL;
1494 }
1495 
1496 /**
1497  * pipapo_rules_same_key() - Get number of rules originated from the same entry
1498  * @f:		Field containing mapping table
1499  * @first:	Index of first rule in set of rules mapping to same entry
1500  *
1501  * Using the fact that all rules in a field that originated from the same entry
1502  * will map to the same set of rules in the next field, or to the same element
1503  * reference, return the cardinality of the set of rules that originated from
1504  * the same entry as the rule with index @first, @first rule included.
1505  *
1506  * In pictures:
1507  *				rules
1508  *	field #0		0    1    2    3    4
1509  *		map to:		0    1   2-4  2-4  5-9
1510  *				.    .    .......   . ...
1511  *				|    |    |    | \   \
1512  *				|    |    |    |  \   \
1513  *				|    |    |    |   \   \
1514  *				'    '    '    '    '   \
1515  *	in field #1		0    1    2    3    4    5 ...
1516  *
1517  * if this is called for rule 2 on field #0, it will return 3, as also rules 2
1518  * and 3 in field 0 map to the same set of rules (2, 3, 4) in the next field.
1519  *
1520  * For the last field in a set, we can rely on associated entries to map to the
1521  * same element references.
1522  *
1523  * Return: Number of rules that originated from the same entry as @first.
1524  */
1525 static unsigned int pipapo_rules_same_key(struct nft_pipapo_field *f, unsigned int first)
1526 {
1527 	struct nft_pipapo_elem *e = NULL; /* Keep gcc happy */
1528 	unsigned int r;
1529 
1530 	for (r = first; r < f->rules; r++) {
1531 		if (r != first && e != f->mt[r].e)
1532 			return r - first;
1533 
1534 		e = f->mt[r].e;
1535 	}
1536 
1537 	if (r != first)
1538 		return r - first;
1539 
1540 	return 0;
1541 }
1542 
1543 /**
1544  * pipapo_unmap() - Remove rules from mapping tables, renumber remaining ones
1545  * @mt:		Mapping array
1546  * @rules:	Original amount of rules in mapping table
1547  * @start:	First rule index to be removed
1548  * @n:		Amount of rules to be removed
1549  * @to_offset:	First rule index, in next field, this group of rules maps to
1550  * @is_last:	If this is the last field, delete reference from mapping array
1551  *
1552  * This is used to unmap rules from the mapping table for a single field,
1553  * maintaining consistency and compactness for the existing ones.
1554  *
1555  * In pictures: let's assume that we want to delete rules 2 and 3 from the
1556  * following mapping array:
1557  *
1558  *                 rules
1559  *               0      1      2      3      4
1560  *      map to:  4-10   4-10   11-15  11-15  16-18
1561  *
1562  * the result will be:
1563  *
1564  *                 rules
1565  *               0      1      2
1566  *      map to:  4-10   4-10   11-13
1567  *
1568  * for fields before the last one. In case this is the mapping table for the
1569  * last field in a set, and rules map to pointers to &struct nft_pipapo_elem:
1570  *
1571  *                      rules
1572  *                        0      1      2      3      4
1573  *  element pointers:  0x42   0x42   0x33   0x33   0x44
1574  *
1575  * the result will be:
1576  *
1577  *                      rules
1578  *                        0      1      2
1579  *  element pointers:  0x42   0x42   0x44
1580  */
1581 static void pipapo_unmap(union nft_pipapo_map_bucket *mt, unsigned int rules,
1582 			 unsigned int start, unsigned int n,
1583 			 unsigned int to_offset, bool is_last)
1584 {
1585 	int i;
1586 
1587 	memmove(mt + start, mt + start + n, (rules - start - n) * sizeof(*mt));
1588 	memset(mt + rules - n, 0, n * sizeof(*mt));
1589 
1590 	if (is_last)
1591 		return;
1592 
1593 	for (i = start; i < rules - n; i++)
1594 		mt[i].to -= to_offset;
1595 }
1596 
1597 /**
1598  * pipapo_drop() - Delete entry from lookup and mapping tables, given rule map
1599  * @m:		Matching data
1600  * @rulemap:	Table of rule maps, arrays of first rule and amount of rules
1601  *		in next field a given entry maps to, for each field
1602  *
1603  * For each rule in lookup table buckets mapping to this set of rules, drop
1604  * all bits set in lookup table mapping. In pictures, assuming we want to drop
1605  * rules 0 and 1 from this lookup table:
1606  *
1607  *                     bucket
1608  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
1609  *        0    0                                              1,2
1610  *        1   1,2                                      0
1611  *        2    0                                      1,2
1612  *        3    0                              1,2
1613  *        4  0,1,2
1614  *        5    0   1   2
1615  *        6  0,1,2 1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
1616  *        7   1,2 1,2  1   1   1  0,1  1   1   1   1   1   1   1   1   1   1
1617  *
1618  * rule 2 becomes rule 0, and the result will be:
1619  *
1620  *                     bucket
1621  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
1622  *        0                                                    0
1623  *        1    0
1624  *        2                                            0
1625  *        3                                    0
1626  *        4    0
1627  *        5            0
1628  *        6    0
1629  *        7    0   0
1630  *
1631  * once this is done, call unmap() to drop all the corresponding rule references
1632  * from mapping tables.
1633  */
1634 static void pipapo_drop(struct nft_pipapo_match *m,
1635 			union nft_pipapo_map_bucket rulemap[])
1636 {
1637 	struct nft_pipapo_field *f;
1638 	int i;
1639 
1640 	nft_pipapo_for_each_field(f, i, m) {
1641 		bool last = i == m->field_count - 1;
1642 		int g;
1643 
1644 		for (g = 0; g < f->groups; g++) {
1645 			unsigned long *pos;
1646 			int b;
1647 
1648 			pos = NFT_PIPAPO_LT_ALIGN(f->lt) + g *
1649 			      NFT_PIPAPO_BUCKETS(f->bb) * f->bsize;
1650 
1651 			for (b = 0; b < NFT_PIPAPO_BUCKETS(f->bb); b++) {
1652 				bitmap_cut(pos, pos, rulemap[i].to,
1653 					   rulemap[i].n,
1654 					   f->bsize * BITS_PER_LONG);
1655 
1656 				pos += f->bsize;
1657 			}
1658 		}
1659 
1660 		pipapo_unmap(f->mt, f->rules, rulemap[i].to, rulemap[i].n,
1661 			     last ? 0 : rulemap[i + 1].n, last);
1662 		if (pipapo_resize(f, f->rules, f->rules - rulemap[i].n)) {
1663 			/* We can ignore this, a failure to shrink tables down
1664 			 * doesn't make tables invalid.
1665 			 */
1666 			;
1667 		}
1668 		f->rules -= rulemap[i].n;
1669 
1670 		pipapo_lt_bits_adjust(f);
1671 	}
1672 }
1673 
1674 static void nft_pipapo_gc_deactivate(struct net *net, struct nft_set *set,
1675 				     struct nft_pipapo_elem *e)
1676 
1677 {
1678 	nft_setelem_data_deactivate(net, set, &e->priv);
1679 }
1680 
1681 /**
1682  * pipapo_gc_scan() - Drop expired entries from set and link them to gc list
1683  * @set:	nftables API set representation
1684  * @m:		Matching data
1685  */
1686 static void pipapo_gc_scan(struct nft_set *set, struct nft_pipapo_match *m)
1687 {
1688 	struct nft_pipapo *priv = nft_set_priv(set);
1689 	struct net *net = read_pnet(&set->net);
1690 	unsigned int rules_f0, first_rule = 0;
1691 	u64 tstamp = nft_net_tstamp(net);
1692 	struct nft_pipapo_elem *e;
1693 	struct nft_trans_gc *gc;
1694 
1695 	gc = nft_trans_gc_alloc(set, 0, GFP_KERNEL);
1696 	if (!gc)
1697 		return;
1698 
1699 	list_add(&gc->list, &priv->gc_head);
1700 
1701 	while ((rules_f0 = pipapo_rules_same_key(m->f, first_rule))) {
1702 		union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1703 		const struct nft_pipapo_field *f;
1704 		unsigned int i, start, rules_fx;
1705 
1706 		start = first_rule;
1707 		rules_fx = rules_f0;
1708 
1709 		nft_pipapo_for_each_field(f, i, m) {
1710 			rulemap[i].to = start;
1711 			rulemap[i].n = rules_fx;
1712 
1713 			if (i < m->field_count - 1) {
1714 				rules_fx = f->mt[start].n;
1715 				start = f->mt[start].to;
1716 			}
1717 		}
1718 
1719 		/* Pick the last field, and its last index */
1720 		f--;
1721 		i--;
1722 		e = f->mt[rulemap[i].to].e;
1723 
1724 		/* synchronous gc never fails, there is no need to set on
1725 		 * NFT_SET_ELEM_DEAD_BIT.
1726 		 */
1727 		if (__nft_set_elem_expired(&e->ext, tstamp)) {
1728 			if (!nft_trans_gc_space(gc)) {
1729 				gc = nft_trans_gc_alloc(set, 0, GFP_KERNEL);
1730 				if (!gc)
1731 					return;
1732 
1733 				list_add(&gc->list, &priv->gc_head);
1734 			}
1735 
1736 			nft_pipapo_gc_deactivate(net, set, e);
1737 			pipapo_drop(m, rulemap);
1738 			nft_trans_gc_elem_add(gc, e);
1739 
1740 			/* And check again current first rule, which is now the
1741 			 * first we haven't checked.
1742 			 */
1743 		} else {
1744 			first_rule += rules_f0;
1745 		}
1746 	}
1747 
1748 	priv->last_gc = jiffies;
1749 }
1750 
1751 /**
1752  * pipapo_gc_queue() - Free expired elements
1753  * @set:	nftables API set representation
1754  */
1755 static void pipapo_gc_queue(struct nft_set *set)
1756 {
1757 	struct nft_pipapo *priv = nft_set_priv(set);
1758 	struct nft_trans_gc *gc, *next;
1759 
1760 	/* always do a catchall cycle: */
1761 	gc = nft_trans_gc_alloc(set, 0, GFP_KERNEL);
1762 	if (gc) {
1763 		gc = nft_trans_gc_catchall_sync(gc);
1764 		if (gc)
1765 			nft_trans_gc_queue_sync_done(gc);
1766 	}
1767 
1768 	/* always purge queued gc elements. */
1769 	list_for_each_entry_safe(gc, next, &priv->gc_head, list) {
1770 		list_del(&gc->list);
1771 		nft_trans_gc_queue_sync_done(gc);
1772 	}
1773 }
1774 
1775 /**
1776  * pipapo_free_fields() - Free per-field tables contained in matching data
1777  * @m:		Matching data
1778  */
1779 static void pipapo_free_fields(struct nft_pipapo_match *m)
1780 {
1781 	struct nft_pipapo_field *f;
1782 	int i;
1783 
1784 	nft_pipapo_for_each_field(f, i, m) {
1785 		kvfree(f->lt);
1786 		kvfree(f->mt);
1787 	}
1788 }
1789 
1790 static void pipapo_free_match(struct nft_pipapo_match *m)
1791 {
1792 	int i;
1793 
1794 	for_each_possible_cpu(i)
1795 		pipapo_free_scratch(m, i);
1796 
1797 	free_percpu(m->scratch);
1798 	pipapo_free_fields(m);
1799 
1800 	kfree(m);
1801 }
1802 
1803 /**
1804  * pipapo_reclaim_match - RCU callback to free fields from old matching data
1805  * @rcu:	RCU head
1806  */
1807 static void pipapo_reclaim_match(struct rcu_head *rcu)
1808 {
1809 	struct nft_pipapo_match *m;
1810 
1811 	m = container_of(rcu, struct nft_pipapo_match, rcu);
1812 	pipapo_free_match(m);
1813 }
1814 
1815 /**
1816  * nft_pipapo_commit() - Replace lookup data with current working copy
1817  * @set:	nftables API set representation
1818  *
1819  * While at it, check if we should perform garbage collection on the working
1820  * copy before committing it for lookup, and don't replace the table if the
1821  * working copy doesn't have pending changes.
1822  *
1823  * We also need to create a new working copy for subsequent insertions and
1824  * deletions.
1825  *
1826  * After the live copy has been replaced by the clone, we can safely queue
1827  * expired elements that have been collected by pipapo_gc_scan() for
1828  * memory reclaim.
1829  */
1830 static void nft_pipapo_commit(struct nft_set *set)
1831 {
1832 	struct nft_pipapo *priv = nft_set_priv(set);
1833 	struct nft_pipapo_match *old;
1834 
1835 	if (!priv->clone)
1836 		return;
1837 
1838 	if (time_after_eq(jiffies, priv->last_gc + nft_set_gc_interval(set)))
1839 		pipapo_gc_scan(set, priv->clone);
1840 
1841 	old = rcu_replace_pointer(priv->match, priv->clone,
1842 				  nft_pipapo_transaction_mutex_held(set));
1843 	priv->clone = NULL;
1844 
1845 	if (old)
1846 		call_rcu(&old->rcu, pipapo_reclaim_match);
1847 
1848 	pipapo_gc_queue(set);
1849 }
1850 
1851 static void nft_pipapo_abort(const struct nft_set *set)
1852 {
1853 	struct nft_pipapo *priv = nft_set_priv(set);
1854 
1855 	if (!priv->clone)
1856 		return;
1857 	pipapo_free_match(priv->clone);
1858 	priv->clone = NULL;
1859 }
1860 
1861 /**
1862  * nft_pipapo_activate() - Mark element reference as active given key, commit
1863  * @net:	Network namespace
1864  * @set:	nftables API set representation
1865  * @elem_priv:	nftables API element representation containing key data
1866  *
1867  * On insertion, elements are added to a copy of the matching data currently
1868  * in use for lookups, and not directly inserted into current lookup data. Both
1869  * nft_pipapo_insert() and nft_pipapo_activate() are called once for each
1870  * element, hence we can't purpose either one as a real commit operation.
1871  */
1872 static void nft_pipapo_activate(const struct net *net,
1873 				const struct nft_set *set,
1874 				struct nft_elem_priv *elem_priv)
1875 {
1876 	struct nft_pipapo_elem *e = nft_elem_priv_cast(elem_priv);
1877 
1878 	nft_clear(net, &e->ext);
1879 }
1880 
1881 /**
1882  * nft_pipapo_deactivate() - Search for element and make it inactive
1883  * @net:	Network namespace
1884  * @set:	nftables API set representation
1885  * @elem:	nftables API element representation containing key data
1886  *
1887  * Return: deactivated element if found, NULL otherwise.
1888  */
1889 static struct nft_elem_priv *
1890 nft_pipapo_deactivate(const struct net *net, const struct nft_set *set,
1891 		      const struct nft_set_elem *elem)
1892 {
1893 	struct nft_pipapo_match *m = pipapo_maybe_clone(set);
1894 	struct nft_pipapo_elem *e;
1895 
1896 	/* removal must occur on priv->clone, if we are low on memory
1897 	 * we have no choice and must fail the removal request.
1898 	 */
1899 	if (!m)
1900 		return NULL;
1901 
1902 	e = pipapo_get(m, (const u8 *)elem->key.val.data,
1903 		       nft_genmask_next(net), nft_net_tstamp(net));
1904 	if (!e)
1905 		return NULL;
1906 
1907 	nft_set_elem_change_active(net, set, &e->ext);
1908 
1909 	return &e->priv;
1910 }
1911 
1912 /**
1913  * nft_pipapo_flush() - make element inactive
1914  * @net:	Network namespace
1915  * @set:	nftables API set representation
1916  * @elem_priv:	nftables API element representation containing key data
1917  *
1918  * This is functionally the same as nft_pipapo_deactivate(), with a slightly
1919  * different interface, and it's also called once for each element in a set
1920  * being flushed, so we can't implement, strictly speaking, a flush operation,
1921  * which would otherwise be as simple as allocating an empty copy of the
1922  * matching data.
1923  *
1924  * Note that we could in theory do that, mark the set as flushed, and ignore
1925  * subsequent calls, but we would leak all the elements after the first one,
1926  * because they wouldn't then be freed as result of API calls.
1927  *
1928  * Return: true if element was found and deactivated.
1929  */
1930 static void nft_pipapo_flush(const struct net *net, const struct nft_set *set,
1931 			     struct nft_elem_priv *elem_priv)
1932 {
1933 	struct nft_pipapo_elem *e = nft_elem_priv_cast(elem_priv);
1934 
1935 	nft_set_elem_change_active(net, set, &e->ext);
1936 }
1937 
1938 /**
1939  * pipapo_get_boundaries() - Get byte interval for associated rules
1940  * @f:		Field including lookup table
1941  * @first_rule:	First rule (lowest index)
1942  * @rule_count:	Number of associated rules
1943  * @left:	Byte expression for left boundary (start of range)
1944  * @right:	Byte expression for right boundary (end of range)
1945  *
1946  * Given the first rule and amount of rules that originated from the same entry,
1947  * build the original range associated with the entry, and calculate the length
1948  * of the originating netmask.
1949  *
1950  * In pictures:
1951  *
1952  *                     bucket
1953  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
1954  *        0                                                   1,2
1955  *        1   1,2
1956  *        2                                           1,2
1957  *        3                                   1,2
1958  *        4   1,2
1959  *        5        1   2
1960  *        6   1,2  1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
1961  *        7   1,2 1,2  1   1   1   1   1   1   1   1   1   1   1   1   1   1
1962  *
1963  * this is the lookup table corresponding to the IPv4 range
1964  * 192.168.1.0-192.168.2.1, which was expanded to the two composing netmasks,
1965  * rule #1: 192.168.1.0/24, and rule #2: 192.168.2.0/31.
1966  *
1967  * This function fills @left and @right with the byte values of the leftmost
1968  * and rightmost bucket indices for the lowest and highest rule indices,
1969  * respectively. If @first_rule is 1 and @rule_count is 2, we obtain, in
1970  * nibbles:
1971  *   left:  < 12, 0, 10, 8, 0, 1, 0, 0 >
1972  *   right: < 12, 0, 10, 8, 0, 2, 2, 1 >
1973  * corresponding to bytes:
1974  *   left:  < 192, 168, 1, 0 >
1975  *   right: < 192, 168, 2, 1 >
1976  * with mask length irrelevant here, unused on return, as the range is already
1977  * defined by its start and end points. The mask length is relevant for a single
1978  * ranged entry instead: if @first_rule is 1 and @rule_count is 1, we ignore
1979  * rule 2 above: @left becomes < 192, 168, 1, 0 >, @right becomes
1980  * < 192, 168, 1, 255 >, and the mask length, calculated from the distances
1981  * between leftmost and rightmost bucket indices for each group, would be 24.
1982  *
1983  * Return: mask length, in bits.
1984  */
1985 static int pipapo_get_boundaries(struct nft_pipapo_field *f, int first_rule,
1986 				 int rule_count, u8 *left, u8 *right)
1987 {
1988 	int g, mask_len = 0, bit_offset = 0;
1989 	u8 *l = left, *r = right;
1990 
1991 	for (g = 0; g < f->groups; g++) {
1992 		int b, x0, x1;
1993 
1994 		x0 = -1;
1995 		x1 = -1;
1996 		for (b = 0; b < NFT_PIPAPO_BUCKETS(f->bb); b++) {
1997 			unsigned long *pos;
1998 
1999 			pos = NFT_PIPAPO_LT_ALIGN(f->lt) +
2000 			      (g * NFT_PIPAPO_BUCKETS(f->bb) + b) * f->bsize;
2001 			if (test_bit(first_rule, pos) && x0 == -1)
2002 				x0 = b;
2003 			if (test_bit(first_rule + rule_count - 1, pos))
2004 				x1 = b;
2005 		}
2006 
2007 		*l |= x0 << (BITS_PER_BYTE - f->bb - bit_offset);
2008 		*r |= x1 << (BITS_PER_BYTE - f->bb - bit_offset);
2009 
2010 		bit_offset += f->bb;
2011 		if (bit_offset >= BITS_PER_BYTE) {
2012 			bit_offset %= BITS_PER_BYTE;
2013 			l++;
2014 			r++;
2015 		}
2016 
2017 		if (x1 - x0 == 0)
2018 			mask_len += 4;
2019 		else if (x1 - x0 == 1)
2020 			mask_len += 3;
2021 		else if (x1 - x0 == 3)
2022 			mask_len += 2;
2023 		else if (x1 - x0 == 7)
2024 			mask_len += 1;
2025 	}
2026 
2027 	return mask_len;
2028 }
2029 
2030 /**
2031  * pipapo_match_field() - Match rules against byte ranges
2032  * @f:		Field including the lookup table
2033  * @first_rule:	First of associated rules originating from same entry
2034  * @rule_count:	Amount of associated rules
2035  * @start:	Start of range to be matched
2036  * @end:	End of range to be matched
2037  *
2038  * Return: true on match, false otherwise.
2039  */
2040 static bool pipapo_match_field(struct nft_pipapo_field *f,
2041 			       int first_rule, int rule_count,
2042 			       const u8 *start, const u8 *end)
2043 {
2044 	u8 right[NFT_PIPAPO_MAX_BYTES] = { 0 };
2045 	u8 left[NFT_PIPAPO_MAX_BYTES] = { 0 };
2046 
2047 	pipapo_get_boundaries(f, first_rule, rule_count, left, right);
2048 
2049 	return !memcmp(start, left,
2050 		       f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f)) &&
2051 	       !memcmp(end, right, f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f));
2052 }
2053 
2054 /**
2055  * nft_pipapo_remove() - Remove element given key, commit
2056  * @net:	Network namespace
2057  * @set:	nftables API set representation
2058  * @elem_priv:	nftables API element representation containing key data
2059  *
2060  * Similarly to nft_pipapo_activate(), this is used as commit operation by the
2061  * API, but it's called once per element in the pending transaction, so we can't
2062  * implement this as a single commit operation. Closest we can get is to remove
2063  * the matched element here, if any, and commit the updated matching data.
2064  */
2065 static void nft_pipapo_remove(const struct net *net, const struct nft_set *set,
2066 			      struct nft_elem_priv *elem_priv)
2067 {
2068 	struct nft_pipapo *priv = nft_set_priv(set);
2069 	struct nft_pipapo_match *m = priv->clone;
2070 	unsigned int rules_f0, first_rule = 0;
2071 	struct nft_pipapo_elem *e;
2072 	const u8 *data;
2073 
2074 	e = nft_elem_priv_cast(elem_priv);
2075 	data = (const u8 *)nft_set_ext_key(&e->ext);
2076 
2077 	while ((rules_f0 = pipapo_rules_same_key(m->f, first_rule))) {
2078 		union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
2079 		const u8 *match_start, *match_end;
2080 		struct nft_pipapo_field *f;
2081 		int i, start, rules_fx;
2082 
2083 		match_start = data;
2084 
2085 		if (nft_set_ext_exists(&e->ext, NFT_SET_EXT_KEY_END))
2086 			match_end = (const u8 *)nft_set_ext_key_end(&e->ext)->data;
2087 		else
2088 			match_end = data;
2089 
2090 		start = first_rule;
2091 		rules_fx = rules_f0;
2092 
2093 		nft_pipapo_for_each_field(f, i, m) {
2094 			bool last = i == m->field_count - 1;
2095 
2096 			if (!pipapo_match_field(f, start, rules_fx,
2097 						match_start, match_end))
2098 				break;
2099 
2100 			rulemap[i].to = start;
2101 			rulemap[i].n = rules_fx;
2102 
2103 			rules_fx = f->mt[start].n;
2104 			start = f->mt[start].to;
2105 
2106 			match_start += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
2107 			match_end += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
2108 
2109 			if (last && f->mt[rulemap[i].to].e == e) {
2110 				pipapo_drop(m, rulemap);
2111 				return;
2112 			}
2113 		}
2114 
2115 		first_rule += rules_f0;
2116 	}
2117 
2118 	WARN_ON_ONCE(1); /* elem_priv not found */
2119 }
2120 
2121 /**
2122  * nft_pipapo_do_walk() - Walk over elements in m
2123  * @ctx:	nftables API context
2124  * @set:	nftables API set representation
2125  * @m:		matching data pointing to key mapping array
2126  * @iter:	Iterator
2127  *
2128  * As elements are referenced in the mapping array for the last field, directly
2129  * scan that array: there's no need to follow rule mappings from the first
2130  * field. @m is protected either by RCU read lock or by transaction mutex.
2131  */
2132 static void nft_pipapo_do_walk(const struct nft_ctx *ctx, struct nft_set *set,
2133 			       const struct nft_pipapo_match *m,
2134 			       struct nft_set_iter *iter)
2135 {
2136 	const struct nft_pipapo_field *f;
2137 	unsigned int i, r;
2138 
2139 	for (i = 0, f = m->f; i < m->field_count - 1; i++, f++)
2140 		;
2141 
2142 	for (r = 0; r < f->rules; r++) {
2143 		struct nft_pipapo_elem *e;
2144 
2145 		if (r < f->rules - 1 && f->mt[r + 1].e == f->mt[r].e)
2146 			continue;
2147 
2148 		if (iter->count < iter->skip)
2149 			goto cont;
2150 
2151 		e = f->mt[r].e;
2152 
2153 		iter->err = iter->fn(ctx, set, iter, &e->priv);
2154 		if (iter->err < 0)
2155 			return;
2156 
2157 cont:
2158 		iter->count++;
2159 	}
2160 }
2161 
2162 /**
2163  * nft_pipapo_walk() - Walk over elements
2164  * @ctx:	nftables API context
2165  * @set:	nftables API set representation
2166  * @iter:	Iterator
2167  *
2168  * Test if destructive action is needed or not, clone active backend if needed
2169  * and call the real function to work on the data.
2170  */
2171 static void nft_pipapo_walk(const struct nft_ctx *ctx, struct nft_set *set,
2172 			    struct nft_set_iter *iter)
2173 {
2174 	struct nft_pipapo *priv = nft_set_priv(set);
2175 	const struct nft_pipapo_match *m;
2176 
2177 	switch (iter->type) {
2178 	case NFT_ITER_UPDATE_CLONE:
2179 		m = pipapo_maybe_clone(set);
2180 		if (!m) {
2181 			iter->err = -ENOMEM;
2182 			return;
2183 		}
2184 		nft_pipapo_do_walk(ctx, set, m, iter);
2185 		break;
2186 	case NFT_ITER_UPDATE:
2187 		if (priv->clone)
2188 			m = priv->clone;
2189 		else
2190 			m = rcu_dereference_protected(priv->match,
2191 						      nft_pipapo_transaction_mutex_held(set));
2192 		nft_pipapo_do_walk(ctx, set, m, iter);
2193 		break;
2194 	case NFT_ITER_READ:
2195 		rcu_read_lock();
2196 		m = rcu_dereference(priv->match);
2197 		nft_pipapo_do_walk(ctx, set, m, iter);
2198 		rcu_read_unlock();
2199 		break;
2200 	default:
2201 		iter->err = -EINVAL;
2202 		WARN_ON_ONCE(1);
2203 		break;
2204 	}
2205 }
2206 
2207 /**
2208  * nft_pipapo_privsize() - Return the size of private data for the set
2209  * @nla:	netlink attributes, ignored as size doesn't depend on them
2210  * @desc:	Set description, ignored as size doesn't depend on it
2211  *
2212  * Return: size of private data for this set implementation, in bytes
2213  */
2214 static u64 nft_pipapo_privsize(const struct nlattr * const nla[],
2215 			       const struct nft_set_desc *desc)
2216 {
2217 	return sizeof(struct nft_pipapo);
2218 }
2219 
2220 /**
2221  * nft_pipapo_estimate() - Set size, space and lookup complexity
2222  * @desc:	Set description, element count and field description used
2223  * @features:	Flags: NFT_SET_INTERVAL needs to be there
2224  * @est:	Storage for estimation data
2225  *
2226  * Return: true if set description is compatible, false otherwise
2227  */
2228 static bool nft_pipapo_estimate(const struct nft_set_desc *desc, u32 features,
2229 				struct nft_set_estimate *est)
2230 {
2231 	if (!(features & NFT_SET_INTERVAL) ||
2232 	    desc->field_count < NFT_PIPAPO_MIN_FIELDS)
2233 		return false;
2234 
2235 	est->size = pipapo_estimate_size(desc);
2236 	if (!est->size)
2237 		return false;
2238 
2239 	est->lookup = NFT_SET_CLASS_O_LOG_N;
2240 
2241 	est->space = NFT_SET_CLASS_O_N;
2242 
2243 	return true;
2244 }
2245 
2246 /**
2247  * nft_pipapo_init() - Initialise data for a set instance
2248  * @set:	nftables API set representation
2249  * @desc:	Set description
2250  * @nla:	netlink attributes
2251  *
2252  * Validate number and size of fields passed as NFTA_SET_DESC_CONCAT netlink
2253  * attributes, initialise internal set parameters, current instance of matching
2254  * data and a copy for subsequent insertions.
2255  *
2256  * Return: 0 on success, negative error code on failure.
2257  */
2258 static int nft_pipapo_init(const struct nft_set *set,
2259 			   const struct nft_set_desc *desc,
2260 			   const struct nlattr * const nla[])
2261 {
2262 	struct nft_pipapo *priv = nft_set_priv(set);
2263 	struct nft_pipapo_match *m;
2264 	struct nft_pipapo_field *f;
2265 	int err, i, field_count;
2266 
2267 	BUILD_BUG_ON(offsetof(struct nft_pipapo_elem, priv) != 0);
2268 
2269 	field_count = desc->field_count ? : 1;
2270 
2271 	BUILD_BUG_ON(NFT_PIPAPO_MAX_FIELDS > 255);
2272 	BUILD_BUG_ON(NFT_PIPAPO_MAX_FIELDS != NFT_REG32_COUNT);
2273 
2274 	if (field_count > NFT_PIPAPO_MAX_FIELDS)
2275 		return -EINVAL;
2276 
2277 	m = kmalloc_flex(*m, f, field_count);
2278 	if (!m)
2279 		return -ENOMEM;
2280 
2281 	m->field_count = field_count;
2282 	m->bsize_max = 0;
2283 
2284 	m->scratch = alloc_percpu(struct nft_pipapo_scratch *);
2285 	if (!m->scratch) {
2286 		err = -ENOMEM;
2287 		goto out_scratch;
2288 	}
2289 	for_each_possible_cpu(i)
2290 		*per_cpu_ptr(m->scratch, i) = NULL;
2291 
2292 	rcu_head_init(&m->rcu);
2293 
2294 	nft_pipapo_for_each_field(f, i, m) {
2295 		unsigned int len = desc->field_len[i] ? : set->klen;
2296 
2297 		/* f->groups is u8 */
2298 		BUILD_BUG_ON((NFT_PIPAPO_MAX_BYTES *
2299 			      BITS_PER_BYTE / NFT_PIPAPO_GROUP_BITS_LARGE_SET) >= 256);
2300 
2301 		f->bb = NFT_PIPAPO_GROUP_BITS_INIT;
2302 		f->groups = len * NFT_PIPAPO_GROUPS_PER_BYTE(f);
2303 
2304 		priv->width += round_up(len, sizeof(u32));
2305 
2306 		f->bsize = 0;
2307 		f->rules = 0;
2308 		f->rules_alloc = 0;
2309 		f->lt = NULL;
2310 		f->mt = NULL;
2311 	}
2312 
2313 	INIT_LIST_HEAD(&priv->gc_head);
2314 	rcu_assign_pointer(priv->match, m);
2315 
2316 	return 0;
2317 
2318 out_scratch:
2319 	kfree(m);
2320 
2321 	return err;
2322 }
2323 
2324 /**
2325  * nft_set_pipapo_match_destroy() - Destroy elements from key mapping array
2326  * @ctx:	context
2327  * @set:	nftables API set representation
2328  * @m:		matching data pointing to key mapping array
2329  */
2330 static void nft_set_pipapo_match_destroy(const struct nft_ctx *ctx,
2331 					 const struct nft_set *set,
2332 					 struct nft_pipapo_match *m)
2333 {
2334 	struct nft_pipapo_field *f;
2335 	unsigned int i, r;
2336 
2337 	for (i = 0, f = m->f; i < m->field_count - 1; i++, f++)
2338 		;
2339 
2340 	for (r = 0; r < f->rules; r++) {
2341 		struct nft_pipapo_elem *e;
2342 
2343 		if (r < f->rules - 1 && f->mt[r + 1].e == f->mt[r].e)
2344 			continue;
2345 
2346 		e = f->mt[r].e;
2347 
2348 		nf_tables_set_elem_destroy(ctx, set, &e->priv);
2349 	}
2350 }
2351 
2352 /**
2353  * nft_pipapo_destroy() - Free private data for set and all committed elements
2354  * @ctx:	context
2355  * @set:	nftables API set representation
2356  */
2357 static void nft_pipapo_destroy(const struct nft_ctx *ctx,
2358 			       const struct nft_set *set)
2359 {
2360 	struct nft_pipapo *priv = nft_set_priv(set);
2361 	struct nft_pipapo_match *m;
2362 
2363 	WARN_ON_ONCE(!list_empty(&priv->gc_head));
2364 
2365 	m = rcu_dereference_protected(priv->match, true);
2366 
2367 	if (priv->clone) {
2368 		nft_set_pipapo_match_destroy(ctx, set, priv->clone);
2369 		pipapo_free_match(priv->clone);
2370 		priv->clone = NULL;
2371 	} else {
2372 		nft_set_pipapo_match_destroy(ctx, set, m);
2373 	}
2374 
2375 	pipapo_free_match(m);
2376 }
2377 
2378 /**
2379  * nft_pipapo_gc_init() - Initialise garbage collection
2380  * @set:	nftables API set representation
2381  *
2382  * Instead of actually setting up a periodic work for garbage collection, as
2383  * this operation requires a swap of matching data with the working copy, we'll
2384  * do that opportunistically with other commit operations if the interval is
2385  * elapsed, so we just need to set the current jiffies timestamp here.
2386  */
2387 static void nft_pipapo_gc_init(const struct nft_set *set)
2388 {
2389 	struct nft_pipapo *priv = nft_set_priv(set);
2390 
2391 	priv->last_gc = jiffies;
2392 }
2393 
2394 const struct nft_set_type nft_set_pipapo_type = {
2395 	.features	= NFT_SET_INTERVAL | NFT_SET_MAP | NFT_SET_OBJECT |
2396 			  NFT_SET_TIMEOUT,
2397 	.ops		= {
2398 		.lookup		= nft_pipapo_lookup,
2399 		.insert		= nft_pipapo_insert,
2400 		.activate	= nft_pipapo_activate,
2401 		.deactivate	= nft_pipapo_deactivate,
2402 		.flush		= nft_pipapo_flush,
2403 		.remove		= nft_pipapo_remove,
2404 		.walk		= nft_pipapo_walk,
2405 		.get		= nft_pipapo_get,
2406 		.privsize	= nft_pipapo_privsize,
2407 		.estimate	= nft_pipapo_estimate,
2408 		.init		= nft_pipapo_init,
2409 		.destroy	= nft_pipapo_destroy,
2410 		.gc_init	= nft_pipapo_gc_init,
2411 		.commit		= nft_pipapo_commit,
2412 		.abort		= nft_pipapo_abort,
2413 		.abort_skip_removal = true,
2414 		.elemsize	= offsetof(struct nft_pipapo_elem, ext),
2415 	},
2416 };
2417 
2418 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
2419 const struct nft_set_type nft_set_pipapo_avx2_type = {
2420 	.features	= NFT_SET_INTERVAL | NFT_SET_MAP | NFT_SET_OBJECT |
2421 			  NFT_SET_TIMEOUT,
2422 	.ops		= {
2423 		.lookup		= nft_pipapo_avx2_lookup,
2424 		.insert		= nft_pipapo_insert,
2425 		.activate	= nft_pipapo_activate,
2426 		.deactivate	= nft_pipapo_deactivate,
2427 		.flush		= nft_pipapo_flush,
2428 		.remove		= nft_pipapo_remove,
2429 		.walk		= nft_pipapo_walk,
2430 		.get		= nft_pipapo_get,
2431 		.privsize	= nft_pipapo_privsize,
2432 		.estimate	= nft_pipapo_avx2_estimate,
2433 		.init		= nft_pipapo_init,
2434 		.destroy	= nft_pipapo_destroy,
2435 		.gc_init	= nft_pipapo_gc_init,
2436 		.commit		= nft_pipapo_commit,
2437 		.abort		= nft_pipapo_abort,
2438 		.abort_skip_removal = true,
2439 		.elemsize	= offsetof(struct nft_pipapo_elem, ext),
2440 	},
2441 };
2442 #endif
2443