xref: /openbmc/linux/net/netfilter/nft_set_pipapo.c (revision 36db6e8484ed455bbb320d89a119378897ae991c)
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,int len,int rules,unsigned long * dst,const union nft_pipapo_map_bucket * mt,bool match_only)362 int pipapo_refill(unsigned long *map, int len, int rules, unsigned long *dst,
363 		  const union nft_pipapo_map_bucket *mt, bool match_only)
364 {
365 	unsigned long bitset;
366 	int k, ret = -1;
367 
368 	for (k = 0; k < len; k++) {
369 		bitset = map[k];
370 		while (bitset) {
371 			unsigned long t = bitset & -bitset;
372 			int r = __builtin_ctzl(bitset);
373 			int i = k * BITS_PER_LONG + r;
374 
375 			if (unlikely(i >= rules)) {
376 				map[k] = 0;
377 				return -1;
378 			}
379 
380 			if (match_only) {
381 				bitmap_clear(map, i, 1);
382 				return i;
383 			}
384 
385 			ret = 0;
386 
387 			bitmap_set(dst, mt[i].to, mt[i].n);
388 
389 			bitset ^= t;
390 		}
391 		map[k] = 0;
392 	}
393 
394 	return ret;
395 }
396 
397 /**
398  * nft_pipapo_lookup() - Lookup function
399  * @net:	Network namespace
400  * @set:	nftables API set representation
401  * @key:	nftables API element representation containing key data
402  * @ext:	nftables API extension pointer, filled with matching reference
403  *
404  * For more details, see DOC: Theory of Operation.
405  *
406  * Return: true on match, false otherwise.
407  */
nft_pipapo_lookup(const struct net * net,const struct nft_set * set,const u32 * key,const struct nft_set_ext ** ext)408 bool nft_pipapo_lookup(const struct net *net, const struct nft_set *set,
409 		       const u32 *key, const struct nft_set_ext **ext)
410 {
411 	struct nft_pipapo *priv = nft_set_priv(set);
412 	struct nft_pipapo_scratch *scratch;
413 	unsigned long *res_map, *fill_map;
414 	u8 genmask = nft_genmask_cur(net);
415 	const struct nft_pipapo_match *m;
416 	const struct nft_pipapo_field *f;
417 	const u8 *rp = (const u8 *)key;
418 	bool map_index;
419 	int i;
420 
421 	local_bh_disable();
422 
423 	m = rcu_dereference(priv->match);
424 
425 	if (unlikely(!m || !*raw_cpu_ptr(m->scratch)))
426 		goto out;
427 
428 	scratch = *raw_cpu_ptr(m->scratch);
429 
430 	map_index = scratch->map_index;
431 
432 	res_map  = scratch->map + (map_index ? m->bsize_max : 0);
433 	fill_map = scratch->map + (map_index ? 0 : m->bsize_max);
434 
435 	pipapo_resmap_init(m, res_map);
436 
437 	nft_pipapo_for_each_field(f, i, m) {
438 		bool last = i == m->field_count - 1;
439 		int b;
440 
441 		/* For each bit group: select lookup table bucket depending on
442 		 * packet bytes value, then AND bucket value
443 		 */
444 		if (likely(f->bb == 8))
445 			pipapo_and_field_buckets_8bit(f, res_map, rp);
446 		else
447 			pipapo_and_field_buckets_4bit(f, res_map, rp);
448 		NFT_PIPAPO_GROUP_BITS_ARE_8_OR_4;
449 
450 		rp += f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f);
451 
452 		/* Now populate the bitmap for the next field, unless this is
453 		 * the last field, in which case return the matched 'ext'
454 		 * pointer if any.
455 		 *
456 		 * Now res_map contains the matching bitmap, and fill_map is the
457 		 * bitmap for the next field.
458 		 */
459 next_match:
460 		b = pipapo_refill(res_map, f->bsize, f->rules, fill_map, f->mt,
461 				  last);
462 		if (b < 0) {
463 			scratch->map_index = map_index;
464 			local_bh_enable();
465 
466 			return false;
467 		}
468 
469 		if (last) {
470 			*ext = &f->mt[b].e->ext;
471 			if (unlikely(nft_set_elem_expired(*ext) ||
472 				     !nft_set_elem_active(*ext, genmask)))
473 				goto next_match;
474 
475 			/* Last field: we're just returning the key without
476 			 * filling the initial bitmap for the next field, so the
477 			 * current inactive bitmap is clean and can be reused as
478 			 * *next* bitmap (not initial) for the next packet.
479 			 */
480 			scratch->map_index = map_index;
481 			local_bh_enable();
482 
483 			return true;
484 		}
485 
486 		/* Swap bitmap indices: res_map is the initial bitmap for the
487 		 * next field, and fill_map is guaranteed to be all-zeroes at
488 		 * this point.
489 		 */
490 		map_index = !map_index;
491 		swap(res_map, fill_map);
492 
493 		rp += NFT_PIPAPO_GROUPS_PADDING(f);
494 	}
495 
496 out:
497 	local_bh_enable();
498 	return false;
499 }
500 
501 /**
502  * pipapo_get() - Get matching element reference given key data
503  * @net:	Network namespace
504  * @set:	nftables API set representation
505  * @data:	Key data to be matched against existing elements
506  * @genmask:	If set, check that element is active in given genmask
507  * @tstamp:	timestamp to check for expired elements
508  *
509  * This is essentially the same as the lookup function, except that it matches
510  * key data against the uncommitted copy and doesn't use preallocated maps for
511  * bitmap results.
512  *
513  * Return: pointer to &struct nft_pipapo_elem on match, error pointer otherwise.
514  */
pipapo_get(const struct net * net,const struct nft_set * set,const u8 * data,u8 genmask,u64 tstamp)515 static struct nft_pipapo_elem *pipapo_get(const struct net *net,
516 					  const struct nft_set *set,
517 					  const u8 *data, u8 genmask,
518 					  u64 tstamp)
519 {
520 	struct nft_pipapo_elem *ret = ERR_PTR(-ENOENT);
521 	struct nft_pipapo *priv = nft_set_priv(set);
522 	unsigned long *res_map, *fill_map = NULL;
523 	const struct nft_pipapo_match *m;
524 	const struct nft_pipapo_field *f;
525 	int i;
526 
527 	m = priv->clone;
528 
529 	res_map = kmalloc_array(m->bsize_max, sizeof(*res_map), GFP_ATOMIC);
530 	if (!res_map) {
531 		ret = ERR_PTR(-ENOMEM);
532 		goto out;
533 	}
534 
535 	fill_map = kcalloc(m->bsize_max, sizeof(*res_map), GFP_ATOMIC);
536 	if (!fill_map) {
537 		ret = ERR_PTR(-ENOMEM);
538 		goto out;
539 	}
540 
541 	pipapo_resmap_init(m, res_map);
542 
543 	nft_pipapo_for_each_field(f, i, m) {
544 		bool last = i == m->field_count - 1;
545 		int b;
546 
547 		/* For each bit group: select lookup table bucket depending on
548 		 * packet bytes value, then AND bucket value
549 		 */
550 		if (f->bb == 8)
551 			pipapo_and_field_buckets_8bit(f, res_map, data);
552 		else if (f->bb == 4)
553 			pipapo_and_field_buckets_4bit(f, res_map, data);
554 		else
555 			BUG();
556 
557 		data += f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f);
558 
559 		/* Now populate the bitmap for the next field, unless this is
560 		 * the last field, in which case return the matched 'ext'
561 		 * pointer if any.
562 		 *
563 		 * Now res_map contains the matching bitmap, and fill_map is the
564 		 * bitmap for the next field.
565 		 */
566 next_match:
567 		b = pipapo_refill(res_map, f->bsize, f->rules, fill_map, f->mt,
568 				  last);
569 		if (b < 0)
570 			goto out;
571 
572 		if (last) {
573 			if (__nft_set_elem_expired(&f->mt[b].e->ext, tstamp))
574 				goto next_match;
575 			if ((genmask &&
576 			     !nft_set_elem_active(&f->mt[b].e->ext, genmask)))
577 				goto next_match;
578 
579 			ret = f->mt[b].e;
580 			goto out;
581 		}
582 
583 		data += NFT_PIPAPO_GROUPS_PADDING(f);
584 
585 		/* Swap bitmap indices: fill_map will be the initial bitmap for
586 		 * the next field (i.e. the new res_map), and res_map is
587 		 * guaranteed to be all-zeroes at this point, ready to be filled
588 		 * according to the next mapping table.
589 		 */
590 		swap(res_map, fill_map);
591 	}
592 
593 out:
594 	kfree(fill_map);
595 	kfree(res_map);
596 	return ret;
597 }
598 
599 /**
600  * nft_pipapo_get() - Get matching element reference given key data
601  * @net:	Network namespace
602  * @set:	nftables API set representation
603  * @elem:	nftables API element representation containing key data
604  * @flags:	Unused
605  */
nft_pipapo_get(const struct net * net,const struct nft_set * set,const struct nft_set_elem * elem,unsigned int flags)606 static void *nft_pipapo_get(const struct net *net, const struct nft_set *set,
607 			    const struct nft_set_elem *elem, unsigned int flags)
608 {
609 	return pipapo_get(net, set, (const u8 *)elem->key.val.data,
610 			 nft_genmask_cur(net), get_jiffies_64());
611 }
612 
613 /**
614  * pipapo_resize() - Resize lookup or mapping table, or both
615  * @f:		Field containing lookup and mapping tables
616  * @old_rules:	Previous amount of rules in field
617  * @rules:	New amount of rules
618  *
619  * Increase, decrease or maintain tables size depending on new amount of rules,
620  * and copy data over. In case the new size is smaller, throw away data for
621  * highest-numbered rules.
622  *
623  * Return: 0 on success, -ENOMEM on allocation failure.
624  */
pipapo_resize(struct nft_pipapo_field * f,int old_rules,int rules)625 static int pipapo_resize(struct nft_pipapo_field *f, int old_rules, int rules)
626 {
627 	long *new_lt = NULL, *new_p, *old_lt = f->lt, *old_p;
628 	union nft_pipapo_map_bucket *new_mt, *old_mt = f->mt;
629 	size_t new_bucket_size, copy;
630 	int group, bucket;
631 
632 	new_bucket_size = DIV_ROUND_UP(rules, BITS_PER_LONG);
633 #ifdef NFT_PIPAPO_ALIGN
634 	new_bucket_size = roundup(new_bucket_size,
635 				  NFT_PIPAPO_ALIGN / sizeof(*new_lt));
636 #endif
637 
638 	if (new_bucket_size == f->bsize)
639 		goto mt;
640 
641 	if (new_bucket_size > f->bsize)
642 		copy = f->bsize;
643 	else
644 		copy = new_bucket_size;
645 
646 	new_lt = kvzalloc(f->groups * NFT_PIPAPO_BUCKETS(f->bb) *
647 			  new_bucket_size * sizeof(*new_lt) +
648 			  NFT_PIPAPO_ALIGN_HEADROOM,
649 			  GFP_KERNEL);
650 	if (!new_lt)
651 		return -ENOMEM;
652 
653 	new_p = NFT_PIPAPO_LT_ALIGN(new_lt);
654 	old_p = NFT_PIPAPO_LT_ALIGN(old_lt);
655 
656 	for (group = 0; group < f->groups; group++) {
657 		for (bucket = 0; bucket < NFT_PIPAPO_BUCKETS(f->bb); bucket++) {
658 			memcpy(new_p, old_p, copy * sizeof(*new_p));
659 			new_p += copy;
660 			old_p += copy;
661 
662 			if (new_bucket_size > f->bsize)
663 				new_p += new_bucket_size - f->bsize;
664 			else
665 				old_p += f->bsize - new_bucket_size;
666 		}
667 	}
668 
669 mt:
670 	new_mt = kvmalloc(rules * sizeof(*new_mt), GFP_KERNEL);
671 	if (!new_mt) {
672 		kvfree(new_lt);
673 		return -ENOMEM;
674 	}
675 
676 	memcpy(new_mt, f->mt, min(old_rules, rules) * sizeof(*new_mt));
677 	if (rules > old_rules) {
678 		memset(new_mt + old_rules, 0,
679 		       (rules - old_rules) * sizeof(*new_mt));
680 	}
681 
682 	if (new_lt) {
683 		f->bsize = new_bucket_size;
684 		NFT_PIPAPO_LT_ASSIGN(f, new_lt);
685 		kvfree(old_lt);
686 	}
687 
688 	f->mt = new_mt;
689 	kvfree(old_mt);
690 
691 	return 0;
692 }
693 
694 /**
695  * pipapo_bucket_set() - Set rule bit in bucket given group and group value
696  * @f:		Field containing lookup table
697  * @rule:	Rule index
698  * @group:	Group index
699  * @v:		Value of bit group
700  */
pipapo_bucket_set(struct nft_pipapo_field * f,int rule,int group,int v)701 static void pipapo_bucket_set(struct nft_pipapo_field *f, int rule, int group,
702 			      int v)
703 {
704 	unsigned long *pos;
705 
706 	pos = NFT_PIPAPO_LT_ALIGN(f->lt);
707 	pos += f->bsize * NFT_PIPAPO_BUCKETS(f->bb) * group;
708 	pos += f->bsize * v;
709 
710 	__set_bit(rule, pos);
711 }
712 
713 /**
714  * pipapo_lt_4b_to_8b() - Switch lookup table group width from 4 bits to 8 bits
715  * @old_groups:	Number of current groups
716  * @bsize:	Size of one bucket, in longs
717  * @old_lt:	Pointer to the current lookup table
718  * @new_lt:	Pointer to the new, pre-allocated lookup table
719  *
720  * Each bucket with index b in the new lookup table, belonging to group g, is
721  * filled with the bit intersection between:
722  * - bucket with index given by the upper 4 bits of b, from group g, and
723  * - bucket with index given by the lower 4 bits of b, from group g + 1
724  *
725  * That is, given buckets from the new lookup table N(x, y) and the old lookup
726  * table O(x, y), with x bucket index, and y group index:
727  *
728  *	N(b, g) := O(b / 16, g) & O(b % 16, g + 1)
729  *
730  * This ensures equivalence of the matching results on lookup. Two examples in
731  * pictures:
732  *
733  *              bucket
734  *  group  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 ... 254 255
735  *    0                ^
736  *    1                |                                                 ^
737  *   ...             ( & )                                               |
738  *                  /     \                                              |
739  *                 /       \                                         .-( & )-.
740  *                /  bucket \                                        |       |
741  *      group  0 / 1   2   3 \ 4   5   6   7   8   9  10  11  12  13 |14  15 |
742  *        0     /             \                                      |       |
743  *        1                    \                                     |       |
744  *        2                                                          |     --'
745  *        3                                                          '-
746  *       ...
747  */
pipapo_lt_4b_to_8b(int old_groups,int bsize,unsigned long * old_lt,unsigned long * new_lt)748 static void pipapo_lt_4b_to_8b(int old_groups, int bsize,
749 			       unsigned long *old_lt, unsigned long *new_lt)
750 {
751 	int g, b, i;
752 
753 	for (g = 0; g < old_groups / 2; g++) {
754 		int src_g0 = g * 2, src_g1 = g * 2 + 1;
755 
756 		for (b = 0; b < NFT_PIPAPO_BUCKETS(8); b++) {
757 			int src_b0 = b / NFT_PIPAPO_BUCKETS(4);
758 			int src_b1 = b % NFT_PIPAPO_BUCKETS(4);
759 			int src_i0 = src_g0 * NFT_PIPAPO_BUCKETS(4) + src_b0;
760 			int src_i1 = src_g1 * NFT_PIPAPO_BUCKETS(4) + src_b1;
761 
762 			for (i = 0; i < bsize; i++) {
763 				*new_lt = old_lt[src_i0 * bsize + i] &
764 					  old_lt[src_i1 * bsize + i];
765 				new_lt++;
766 			}
767 		}
768 	}
769 }
770 
771 /**
772  * pipapo_lt_8b_to_4b() - Switch lookup table group width from 8 bits to 4 bits
773  * @old_groups:	Number of current groups
774  * @bsize:	Size of one bucket, in longs
775  * @old_lt:	Pointer to the current lookup table
776  * @new_lt:	Pointer to the new, pre-allocated lookup table
777  *
778  * Each bucket with index b in the new lookup table, belonging to group g, is
779  * filled with the bit union of:
780  * - all the buckets with index such that the upper four bits of the lower byte
781  *   equal b, from group g, with g odd
782  * - all the buckets with index such that the lower four bits equal b, from
783  *   group g, with g even
784  *
785  * That is, given buckets from the new lookup table N(x, y) and the old lookup
786  * table O(x, y), with x bucket index, and y group index:
787  *
788  *	- with g odd:  N(b, g) := U(O(x, g) for each x : x = (b & 0xf0) >> 4)
789  *	- with g even: N(b, g) := U(O(x, g) for each x : x = b & 0x0f)
790  *
791  * where U() denotes the arbitrary union operation (binary OR of n terms). This
792  * ensures equivalence of the matching results on lookup.
793  */
pipapo_lt_8b_to_4b(int old_groups,int bsize,unsigned long * old_lt,unsigned long * new_lt)794 static void pipapo_lt_8b_to_4b(int old_groups, int bsize,
795 			       unsigned long *old_lt, unsigned long *new_lt)
796 {
797 	int g, b, bsrc, i;
798 
799 	memset(new_lt, 0, old_groups * 2 * NFT_PIPAPO_BUCKETS(4) * bsize *
800 			  sizeof(unsigned long));
801 
802 	for (g = 0; g < old_groups * 2; g += 2) {
803 		int src_g = g / 2;
804 
805 		for (b = 0; b < NFT_PIPAPO_BUCKETS(4); b++) {
806 			for (bsrc = NFT_PIPAPO_BUCKETS(8) * src_g;
807 			     bsrc < NFT_PIPAPO_BUCKETS(8) * (src_g + 1);
808 			     bsrc++) {
809 				if (((bsrc & 0xf0) >> 4) != b)
810 					continue;
811 
812 				for (i = 0; i < bsize; i++)
813 					new_lt[i] |= old_lt[bsrc * bsize + i];
814 			}
815 
816 			new_lt += bsize;
817 		}
818 
819 		for (b = 0; b < NFT_PIPAPO_BUCKETS(4); b++) {
820 			for (bsrc = NFT_PIPAPO_BUCKETS(8) * src_g;
821 			     bsrc < NFT_PIPAPO_BUCKETS(8) * (src_g + 1);
822 			     bsrc++) {
823 				if ((bsrc & 0x0f) != b)
824 					continue;
825 
826 				for (i = 0; i < bsize; i++)
827 					new_lt[i] |= old_lt[bsrc * bsize + i];
828 			}
829 
830 			new_lt += bsize;
831 		}
832 	}
833 }
834 
835 /**
836  * pipapo_lt_bits_adjust() - Adjust group size for lookup table if needed
837  * @f:		Field containing lookup table
838  */
pipapo_lt_bits_adjust(struct nft_pipapo_field * f)839 static void pipapo_lt_bits_adjust(struct nft_pipapo_field *f)
840 {
841 	unsigned long *new_lt;
842 	int groups, bb;
843 	size_t lt_size;
844 
845 	lt_size = f->groups * NFT_PIPAPO_BUCKETS(f->bb) * f->bsize *
846 		  sizeof(*f->lt);
847 
848 	if (f->bb == NFT_PIPAPO_GROUP_BITS_SMALL_SET &&
849 	    lt_size > NFT_PIPAPO_LT_SIZE_HIGH) {
850 		groups = f->groups * 2;
851 		bb = NFT_PIPAPO_GROUP_BITS_LARGE_SET;
852 
853 		lt_size = groups * NFT_PIPAPO_BUCKETS(bb) * f->bsize *
854 			  sizeof(*f->lt);
855 	} else if (f->bb == NFT_PIPAPO_GROUP_BITS_LARGE_SET &&
856 		   lt_size < NFT_PIPAPO_LT_SIZE_LOW) {
857 		groups = f->groups / 2;
858 		bb = NFT_PIPAPO_GROUP_BITS_SMALL_SET;
859 
860 		lt_size = groups * NFT_PIPAPO_BUCKETS(bb) * f->bsize *
861 			  sizeof(*f->lt);
862 
863 		/* Don't increase group width if the resulting lookup table size
864 		 * would exceed the upper size threshold for a "small" set.
865 		 */
866 		if (lt_size > NFT_PIPAPO_LT_SIZE_HIGH)
867 			return;
868 	} else {
869 		return;
870 	}
871 
872 	new_lt = kvzalloc(lt_size + NFT_PIPAPO_ALIGN_HEADROOM, GFP_KERNEL);
873 	if (!new_lt)
874 		return;
875 
876 	NFT_PIPAPO_GROUP_BITS_ARE_8_OR_4;
877 	if (f->bb == 4 && bb == 8) {
878 		pipapo_lt_4b_to_8b(f->groups, f->bsize,
879 				   NFT_PIPAPO_LT_ALIGN(f->lt),
880 				   NFT_PIPAPO_LT_ALIGN(new_lt));
881 	} else if (f->bb == 8 && bb == 4) {
882 		pipapo_lt_8b_to_4b(f->groups, f->bsize,
883 				   NFT_PIPAPO_LT_ALIGN(f->lt),
884 				   NFT_PIPAPO_LT_ALIGN(new_lt));
885 	} else {
886 		BUG();
887 	}
888 
889 	f->groups = groups;
890 	f->bb = bb;
891 	kvfree(f->lt);
892 	NFT_PIPAPO_LT_ASSIGN(f, new_lt);
893 }
894 
895 /**
896  * pipapo_insert() - Insert new rule in field given input key and mask length
897  * @f:		Field containing lookup table
898  * @k:		Input key for classification, without nftables padding
899  * @mask_bits:	Length of mask; matches field length for non-ranged entry
900  *
901  * Insert a new rule reference in lookup buckets corresponding to k and
902  * mask_bits.
903  *
904  * Return: 1 on success (one rule inserted), negative error code on failure.
905  */
pipapo_insert(struct nft_pipapo_field * f,const uint8_t * k,int mask_bits)906 static int pipapo_insert(struct nft_pipapo_field *f, const uint8_t *k,
907 			 int mask_bits)
908 {
909 	int rule = f->rules, group, ret, bit_offset = 0;
910 
911 	ret = pipapo_resize(f, f->rules, f->rules + 1);
912 	if (ret)
913 		return ret;
914 
915 	f->rules++;
916 
917 	for (group = 0; group < f->groups; group++) {
918 		int i, v;
919 		u8 mask;
920 
921 		v = k[group / (BITS_PER_BYTE / f->bb)];
922 		v &= GENMASK(BITS_PER_BYTE - bit_offset - 1, 0);
923 		v >>= (BITS_PER_BYTE - bit_offset) - f->bb;
924 
925 		bit_offset += f->bb;
926 		bit_offset %= BITS_PER_BYTE;
927 
928 		if (mask_bits >= (group + 1) * f->bb) {
929 			/* Not masked */
930 			pipapo_bucket_set(f, rule, group, v);
931 		} else if (mask_bits <= group * f->bb) {
932 			/* Completely masked */
933 			for (i = 0; i < NFT_PIPAPO_BUCKETS(f->bb); i++)
934 				pipapo_bucket_set(f, rule, group, i);
935 		} else {
936 			/* The mask limit falls on this group */
937 			mask = GENMASK(f->bb - 1, 0);
938 			mask >>= mask_bits - group * f->bb;
939 			for (i = 0; i < NFT_PIPAPO_BUCKETS(f->bb); i++) {
940 				if ((i & ~mask) == (v & ~mask))
941 					pipapo_bucket_set(f, rule, group, i);
942 			}
943 		}
944 	}
945 
946 	pipapo_lt_bits_adjust(f);
947 
948 	return 1;
949 }
950 
951 /**
952  * pipapo_step_diff() - Check if setting @step bit in netmask would change it
953  * @base:	Mask we are expanding
954  * @step:	Step bit for given expansion step
955  * @len:	Total length of mask space (set and unset bits), bytes
956  *
957  * Convenience function for mask expansion.
958  *
959  * Return: true if step bit changes mask (i.e. isn't set), false otherwise.
960  */
pipapo_step_diff(u8 * base,int step,int len)961 static bool pipapo_step_diff(u8 *base, int step, int len)
962 {
963 	/* Network order, byte-addressed */
964 #ifdef __BIG_ENDIAN__
965 	return !(BIT(step % BITS_PER_BYTE) & base[step / BITS_PER_BYTE]);
966 #else
967 	return !(BIT(step % BITS_PER_BYTE) &
968 		 base[len - 1 - step / BITS_PER_BYTE]);
969 #endif
970 }
971 
972 /**
973  * pipapo_step_after_end() - Check if mask exceeds range end with given step
974  * @base:	Mask we are expanding
975  * @end:	End of range
976  * @step:	Step bit for given expansion step, highest bit to be set
977  * @len:	Total length of mask space (set and unset bits), bytes
978  *
979  * Convenience function for mask expansion.
980  *
981  * Return: true if mask exceeds range setting step bits, false otherwise.
982  */
pipapo_step_after_end(const u8 * base,const u8 * end,int step,int len)983 static bool pipapo_step_after_end(const u8 *base, const u8 *end, int step,
984 				  int len)
985 {
986 	u8 tmp[NFT_PIPAPO_MAX_BYTES];
987 	int i;
988 
989 	memcpy(tmp, base, len);
990 
991 	/* Network order, byte-addressed */
992 	for (i = 0; i <= step; i++)
993 #ifdef __BIG_ENDIAN__
994 		tmp[i / BITS_PER_BYTE] |= BIT(i % BITS_PER_BYTE);
995 #else
996 		tmp[len - 1 - i / BITS_PER_BYTE] |= BIT(i % BITS_PER_BYTE);
997 #endif
998 
999 	return memcmp(tmp, end, len) > 0;
1000 }
1001 
1002 /**
1003  * pipapo_base_sum() - Sum step bit to given len-sized netmask base with carry
1004  * @base:	Netmask base
1005  * @step:	Step bit to sum
1006  * @len:	Netmask length, bytes
1007  */
pipapo_base_sum(u8 * base,int step,int len)1008 static void pipapo_base_sum(u8 *base, int step, int len)
1009 {
1010 	bool carry = false;
1011 	int i;
1012 
1013 	/* Network order, byte-addressed */
1014 #ifdef __BIG_ENDIAN__
1015 	for (i = step / BITS_PER_BYTE; i < len; i++) {
1016 #else
1017 	for (i = len - 1 - step / BITS_PER_BYTE; i >= 0; i--) {
1018 #endif
1019 		if (carry)
1020 			base[i]++;
1021 		else
1022 			base[i] += 1 << (step % BITS_PER_BYTE);
1023 
1024 		if (base[i])
1025 			break;
1026 
1027 		carry = true;
1028 	}
1029 }
1030 
1031 /**
1032  * pipapo_expand() - Expand to composing netmasks, insert into lookup table
1033  * @f:		Field containing lookup table
1034  * @start:	Start of range
1035  * @end:	End of range
1036  * @len:	Length of value in bits
1037  *
1038  * Expand range to composing netmasks and insert corresponding rule references
1039  * in lookup buckets.
1040  *
1041  * Return: number of inserted rules on success, negative error code on failure.
1042  */
1043 static int pipapo_expand(struct nft_pipapo_field *f,
1044 			 const u8 *start, const u8 *end, int len)
1045 {
1046 	int step, masks = 0, bytes = DIV_ROUND_UP(len, BITS_PER_BYTE);
1047 	u8 base[NFT_PIPAPO_MAX_BYTES];
1048 
1049 	memcpy(base, start, bytes);
1050 	while (memcmp(base, end, bytes) <= 0) {
1051 		int err;
1052 
1053 		step = 0;
1054 		while (pipapo_step_diff(base, step, bytes)) {
1055 			if (pipapo_step_after_end(base, end, step, bytes))
1056 				break;
1057 
1058 			step++;
1059 			if (step >= len) {
1060 				if (!masks) {
1061 					err = pipapo_insert(f, base, 0);
1062 					if (err < 0)
1063 						return err;
1064 					masks = 1;
1065 				}
1066 				goto out;
1067 			}
1068 		}
1069 
1070 		err = pipapo_insert(f, base, len - step);
1071 
1072 		if (err < 0)
1073 			return err;
1074 
1075 		masks++;
1076 		pipapo_base_sum(base, step, bytes);
1077 	}
1078 out:
1079 	return masks;
1080 }
1081 
1082 /**
1083  * pipapo_map() - Insert rules in mapping tables, mapping them between fields
1084  * @m:		Matching data, including mapping table
1085  * @map:	Table of rule maps: array of first rule and amount of rules
1086  *		in next field a given rule maps to, for each field
1087  * @e:		For last field, nft_set_ext pointer matching rules map to
1088  */
1089 static void pipapo_map(struct nft_pipapo_match *m,
1090 		       union nft_pipapo_map_bucket map[NFT_PIPAPO_MAX_FIELDS],
1091 		       struct nft_pipapo_elem *e)
1092 {
1093 	struct nft_pipapo_field *f;
1094 	int i, j;
1095 
1096 	for (i = 0, f = m->f; i < m->field_count - 1; i++, f++) {
1097 		for (j = 0; j < map[i].n; j++) {
1098 			f->mt[map[i].to + j].to = map[i + 1].to;
1099 			f->mt[map[i].to + j].n = map[i + 1].n;
1100 		}
1101 	}
1102 
1103 	/* Last field: map to ext instead of mapping to next field */
1104 	for (j = 0; j < map[i].n; j++)
1105 		f->mt[map[i].to + j].e = e;
1106 }
1107 
1108 /**
1109  * pipapo_free_scratch() - Free per-CPU map at original (not aligned) address
1110  * @m:		Matching data
1111  * @cpu:	CPU number
1112  */
1113 static void pipapo_free_scratch(const struct nft_pipapo_match *m, unsigned int cpu)
1114 {
1115 	struct nft_pipapo_scratch *s;
1116 	void *mem;
1117 
1118 	s = *per_cpu_ptr(m->scratch, cpu);
1119 	if (!s)
1120 		return;
1121 
1122 	mem = s;
1123 	mem -= s->align_off;
1124 	kfree(mem);
1125 }
1126 
1127 /**
1128  * pipapo_realloc_scratch() - Reallocate scratch maps for partial match results
1129  * @clone:	Copy of matching data with pending insertions and deletions
1130  * @bsize_max:	Maximum bucket size, scratch maps cover two buckets
1131  *
1132  * Return: 0 on success, -ENOMEM on failure.
1133  */
1134 static int pipapo_realloc_scratch(struct nft_pipapo_match *clone,
1135 				  unsigned long bsize_max)
1136 {
1137 	int i;
1138 
1139 	for_each_possible_cpu(i) {
1140 		struct nft_pipapo_scratch *scratch;
1141 #ifdef NFT_PIPAPO_ALIGN
1142 		void *scratch_aligned;
1143 		u32 align_off;
1144 #endif
1145 		scratch = kzalloc_node(struct_size(scratch, map,
1146 						   bsize_max * 2) +
1147 				       NFT_PIPAPO_ALIGN_HEADROOM,
1148 				       GFP_KERNEL, cpu_to_node(i));
1149 		if (!scratch) {
1150 			/* On failure, there's no need to undo previous
1151 			 * allocations: this means that some scratch maps have
1152 			 * a bigger allocated size now (this is only called on
1153 			 * insertion), but the extra space won't be used by any
1154 			 * CPU as new elements are not inserted and m->bsize_max
1155 			 * is not updated.
1156 			 */
1157 			return -ENOMEM;
1158 		}
1159 
1160 		pipapo_free_scratch(clone, i);
1161 
1162 #ifdef NFT_PIPAPO_ALIGN
1163 		/* Align &scratch->map (not the struct itself): the extra
1164 		 * %NFT_PIPAPO_ALIGN_HEADROOM bytes passed to kzalloc_node()
1165 		 * above guarantee we can waste up to those bytes in order
1166 		 * to align the map field regardless of its offset within
1167 		 * the struct.
1168 		 */
1169 		BUILD_BUG_ON(offsetof(struct nft_pipapo_scratch, map) > NFT_PIPAPO_ALIGN_HEADROOM);
1170 
1171 		scratch_aligned = NFT_PIPAPO_LT_ALIGN(&scratch->map);
1172 		scratch_aligned -= offsetof(struct nft_pipapo_scratch, map);
1173 		align_off = scratch_aligned - (void *)scratch;
1174 
1175 		scratch = scratch_aligned;
1176 		scratch->align_off = align_off;
1177 #endif
1178 		*per_cpu_ptr(clone->scratch, i) = scratch;
1179 	}
1180 
1181 	return 0;
1182 }
1183 
1184 /**
1185  * nft_pipapo_insert() - Validate and insert ranged elements
1186  * @net:	Network namespace
1187  * @set:	nftables API set representation
1188  * @elem:	nftables API element representation containing key data
1189  * @ext2:	Filled with pointer to &struct nft_set_ext in inserted element
1190  *
1191  * Return: 0 on success, error pointer on failure.
1192  */
1193 static int nft_pipapo_insert(const struct net *net, const struct nft_set *set,
1194 			     const struct nft_set_elem *elem,
1195 			     struct nft_set_ext **ext2)
1196 {
1197 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
1198 	union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1199 	const u8 *start = (const u8 *)elem->key.val.data, *end;
1200 	struct nft_pipapo_elem *e = elem->priv, *dup;
1201 	struct nft_pipapo *priv = nft_set_priv(set);
1202 	struct nft_pipapo_match *m = priv->clone;
1203 	u8 genmask = nft_genmask_next(net);
1204 	u64 tstamp = nft_net_tstamp(net);
1205 	struct nft_pipapo_field *f;
1206 	const u8 *start_p, *end_p;
1207 	int i, bsize_max, err = 0;
1208 
1209 	if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END))
1210 		end = (const u8 *)nft_set_ext_key_end(ext)->data;
1211 	else
1212 		end = start;
1213 
1214 	dup = pipapo_get(net, set, start, genmask, tstamp);
1215 	if (!IS_ERR(dup)) {
1216 		/* Check if we already have the same exact entry */
1217 		const struct nft_data *dup_key, *dup_end;
1218 
1219 		dup_key = nft_set_ext_key(&dup->ext);
1220 		if (nft_set_ext_exists(&dup->ext, NFT_SET_EXT_KEY_END))
1221 			dup_end = nft_set_ext_key_end(&dup->ext);
1222 		else
1223 			dup_end = dup_key;
1224 
1225 		if (!memcmp(start, dup_key->data, sizeof(*dup_key->data)) &&
1226 		    !memcmp(end, dup_end->data, sizeof(*dup_end->data))) {
1227 			*ext2 = &dup->ext;
1228 			return -EEXIST;
1229 		}
1230 
1231 		return -ENOTEMPTY;
1232 	}
1233 
1234 	if (PTR_ERR(dup) == -ENOENT) {
1235 		/* Look for partially overlapping entries */
1236 		dup = pipapo_get(net, set, end, nft_genmask_next(net), tstamp);
1237 	}
1238 
1239 	if (PTR_ERR(dup) != -ENOENT) {
1240 		if (IS_ERR(dup))
1241 			return PTR_ERR(dup);
1242 		*ext2 = &dup->ext;
1243 		return -ENOTEMPTY;
1244 	}
1245 
1246 	/* Validate */
1247 	start_p = start;
1248 	end_p = end;
1249 	nft_pipapo_for_each_field(f, i, m) {
1250 		if (f->rules >= (unsigned long)NFT_PIPAPO_RULE0_MAX)
1251 			return -ENOSPC;
1252 
1253 		if (memcmp(start_p, end_p,
1254 			   f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f)) > 0)
1255 			return -EINVAL;
1256 
1257 		start_p += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1258 		end_p += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1259 	}
1260 
1261 	/* Insert */
1262 	priv->dirty = true;
1263 
1264 	bsize_max = m->bsize_max;
1265 
1266 	nft_pipapo_for_each_field(f, i, m) {
1267 		int ret;
1268 
1269 		rulemap[i].to = f->rules;
1270 
1271 		ret = memcmp(start, end,
1272 			     f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f));
1273 		if (!ret)
1274 			ret = pipapo_insert(f, start, f->groups * f->bb);
1275 		else
1276 			ret = pipapo_expand(f, start, end, f->groups * f->bb);
1277 
1278 		if (ret < 0)
1279 			return ret;
1280 
1281 		if (f->bsize > bsize_max)
1282 			bsize_max = f->bsize;
1283 
1284 		rulemap[i].n = ret;
1285 
1286 		start += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1287 		end += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1288 	}
1289 
1290 	if (!*get_cpu_ptr(m->scratch) || bsize_max > m->bsize_max) {
1291 		put_cpu_ptr(m->scratch);
1292 
1293 		err = pipapo_realloc_scratch(m, bsize_max);
1294 		if (err)
1295 			return err;
1296 
1297 		m->bsize_max = bsize_max;
1298 	} else {
1299 		put_cpu_ptr(m->scratch);
1300 	}
1301 
1302 	*ext2 = &e->ext;
1303 
1304 	pipapo_map(m, rulemap, e);
1305 
1306 	return 0;
1307 }
1308 
1309 /**
1310  * pipapo_clone() - Clone matching data to create new working copy
1311  * @old:	Existing matching data
1312  *
1313  * Return: copy of matching data passed as 'old', error pointer on failure
1314  */
1315 static struct nft_pipapo_match *pipapo_clone(struct nft_pipapo_match *old)
1316 {
1317 	struct nft_pipapo_field *dst, *src;
1318 	struct nft_pipapo_match *new;
1319 	int i;
1320 
1321 	new = kmalloc(struct_size(new, f, old->field_count), GFP_KERNEL);
1322 	if (!new)
1323 		return ERR_PTR(-ENOMEM);
1324 
1325 	new->field_count = old->field_count;
1326 	new->bsize_max = old->bsize_max;
1327 
1328 	new->scratch = alloc_percpu(*new->scratch);
1329 	if (!new->scratch)
1330 		goto out_scratch;
1331 
1332 	for_each_possible_cpu(i)
1333 		*per_cpu_ptr(new->scratch, i) = NULL;
1334 
1335 	if (pipapo_realloc_scratch(new, old->bsize_max))
1336 		goto out_scratch_realloc;
1337 
1338 	rcu_head_init(&new->rcu);
1339 
1340 	src = old->f;
1341 	dst = new->f;
1342 
1343 	for (i = 0; i < old->field_count; i++) {
1344 		unsigned long *new_lt;
1345 
1346 		memcpy(dst, src, offsetof(struct nft_pipapo_field, lt));
1347 
1348 		new_lt = kvzalloc(src->groups * NFT_PIPAPO_BUCKETS(src->bb) *
1349 				  src->bsize * sizeof(*dst->lt) +
1350 				  NFT_PIPAPO_ALIGN_HEADROOM,
1351 				  GFP_KERNEL);
1352 		if (!new_lt)
1353 			goto out_lt;
1354 
1355 		NFT_PIPAPO_LT_ASSIGN(dst, new_lt);
1356 
1357 		memcpy(NFT_PIPAPO_LT_ALIGN(new_lt),
1358 		       NFT_PIPAPO_LT_ALIGN(src->lt),
1359 		       src->bsize * sizeof(*dst->lt) *
1360 		       src->groups * NFT_PIPAPO_BUCKETS(src->bb));
1361 
1362 		dst->mt = kvmalloc(src->rules * sizeof(*src->mt), GFP_KERNEL);
1363 		if (!dst->mt)
1364 			goto out_mt;
1365 
1366 		memcpy(dst->mt, src->mt, src->rules * sizeof(*src->mt));
1367 		src++;
1368 		dst++;
1369 	}
1370 
1371 	return new;
1372 
1373 out_mt:
1374 	kvfree(dst->lt);
1375 out_lt:
1376 	for (dst--; i > 0; i--) {
1377 		kvfree(dst->mt);
1378 		kvfree(dst->lt);
1379 		dst--;
1380 	}
1381 out_scratch_realloc:
1382 	for_each_possible_cpu(i)
1383 		pipapo_free_scratch(new, i);
1384 out_scratch:
1385 	free_percpu(new->scratch);
1386 	kfree(new);
1387 
1388 	return ERR_PTR(-ENOMEM);
1389 }
1390 
1391 /**
1392  * pipapo_rules_same_key() - Get number of rules originated from the same entry
1393  * @f:		Field containing mapping table
1394  * @first:	Index of first rule in set of rules mapping to same entry
1395  *
1396  * Using the fact that all rules in a field that originated from the same entry
1397  * will map to the same set of rules in the next field, or to the same element
1398  * reference, return the cardinality of the set of rules that originated from
1399  * the same entry as the rule with index @first, @first rule included.
1400  *
1401  * In pictures:
1402  *				rules
1403  *	field #0		0    1    2    3    4
1404  *		map to:		0    1   2-4  2-4  5-9
1405  *				.    .    .......   . ...
1406  *				|    |    |    | \   \
1407  *				|    |    |    |  \   \
1408  *				|    |    |    |   \   \
1409  *				'    '    '    '    '   \
1410  *	in field #1		0    1    2    3    4    5 ...
1411  *
1412  * if this is called for rule 2 on field #0, it will return 3, as also rules 2
1413  * and 3 in field 0 map to the same set of rules (2, 3, 4) in the next field.
1414  *
1415  * For the last field in a set, we can rely on associated entries to map to the
1416  * same element references.
1417  *
1418  * Return: Number of rules that originated from the same entry as @first.
1419  */
1420 static int pipapo_rules_same_key(struct nft_pipapo_field *f, int first)
1421 {
1422 	struct nft_pipapo_elem *e = NULL; /* Keep gcc happy */
1423 	int r;
1424 
1425 	for (r = first; r < f->rules; r++) {
1426 		if (r != first && e != f->mt[r].e)
1427 			return r - first;
1428 
1429 		e = f->mt[r].e;
1430 	}
1431 
1432 	if (r != first)
1433 		return r - first;
1434 
1435 	return 0;
1436 }
1437 
1438 /**
1439  * pipapo_unmap() - Remove rules from mapping tables, renumber remaining ones
1440  * @mt:		Mapping array
1441  * @rules:	Original amount of rules in mapping table
1442  * @start:	First rule index to be removed
1443  * @n:		Amount of rules to be removed
1444  * @to_offset:	First rule index, in next field, this group of rules maps to
1445  * @is_last:	If this is the last field, delete reference from mapping array
1446  *
1447  * This is used to unmap rules from the mapping table for a single field,
1448  * maintaining consistency and compactness for the existing ones.
1449  *
1450  * In pictures: let's assume that we want to delete rules 2 and 3 from the
1451  * following mapping array:
1452  *
1453  *                 rules
1454  *               0      1      2      3      4
1455  *      map to:  4-10   4-10   11-15  11-15  16-18
1456  *
1457  * the result will be:
1458  *
1459  *                 rules
1460  *               0      1      2
1461  *      map to:  4-10   4-10   11-13
1462  *
1463  * for fields before the last one. In case this is the mapping table for the
1464  * last field in a set, and rules map to pointers to &struct nft_pipapo_elem:
1465  *
1466  *                      rules
1467  *                        0      1      2      3      4
1468  *  element pointers:  0x42   0x42   0x33   0x33   0x44
1469  *
1470  * the result will be:
1471  *
1472  *                      rules
1473  *                        0      1      2
1474  *  element pointers:  0x42   0x42   0x44
1475  */
1476 static void pipapo_unmap(union nft_pipapo_map_bucket *mt, int rules,
1477 			 int start, int n, int to_offset, bool is_last)
1478 {
1479 	int i;
1480 
1481 	memmove(mt + start, mt + start + n, (rules - start - n) * sizeof(*mt));
1482 	memset(mt + rules - n, 0, n * sizeof(*mt));
1483 
1484 	if (is_last)
1485 		return;
1486 
1487 	for (i = start; i < rules - n; i++)
1488 		mt[i].to -= to_offset;
1489 }
1490 
1491 /**
1492  * pipapo_drop() - Delete entry from lookup and mapping tables, given rule map
1493  * @m:		Matching data
1494  * @rulemap:	Table of rule maps, arrays of first rule and amount of rules
1495  *		in next field a given entry maps to, for each field
1496  *
1497  * For each rule in lookup table buckets mapping to this set of rules, drop
1498  * all bits set in lookup table mapping. In pictures, assuming we want to drop
1499  * rules 0 and 1 from this lookup table:
1500  *
1501  *                     bucket
1502  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
1503  *        0    0                                              1,2
1504  *        1   1,2                                      0
1505  *        2    0                                      1,2
1506  *        3    0                              1,2
1507  *        4  0,1,2
1508  *        5    0   1   2
1509  *        6  0,1,2 1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
1510  *        7   1,2 1,2  1   1   1  0,1  1   1   1   1   1   1   1   1   1   1
1511  *
1512  * rule 2 becomes rule 0, and the result will be:
1513  *
1514  *                     bucket
1515  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
1516  *        0                                                    0
1517  *        1    0
1518  *        2                                            0
1519  *        3                                    0
1520  *        4    0
1521  *        5            0
1522  *        6    0
1523  *        7    0   0
1524  *
1525  * once this is done, call unmap() to drop all the corresponding rule references
1526  * from mapping tables.
1527  */
1528 static void pipapo_drop(struct nft_pipapo_match *m,
1529 			union nft_pipapo_map_bucket rulemap[])
1530 {
1531 	struct nft_pipapo_field *f;
1532 	int i;
1533 
1534 	nft_pipapo_for_each_field(f, i, m) {
1535 		int g;
1536 
1537 		for (g = 0; g < f->groups; g++) {
1538 			unsigned long *pos;
1539 			int b;
1540 
1541 			pos = NFT_PIPAPO_LT_ALIGN(f->lt) + g *
1542 			      NFT_PIPAPO_BUCKETS(f->bb) * f->bsize;
1543 
1544 			for (b = 0; b < NFT_PIPAPO_BUCKETS(f->bb); b++) {
1545 				bitmap_cut(pos, pos, rulemap[i].to,
1546 					   rulemap[i].n,
1547 					   f->bsize * BITS_PER_LONG);
1548 
1549 				pos += f->bsize;
1550 			}
1551 		}
1552 
1553 		pipapo_unmap(f->mt, f->rules, rulemap[i].to, rulemap[i].n,
1554 			     rulemap[i + 1].n, i == m->field_count - 1);
1555 		if (pipapo_resize(f, f->rules, f->rules - rulemap[i].n)) {
1556 			/* We can ignore this, a failure to shrink tables down
1557 			 * doesn't make tables invalid.
1558 			 */
1559 			;
1560 		}
1561 		f->rules -= rulemap[i].n;
1562 
1563 		pipapo_lt_bits_adjust(f);
1564 	}
1565 }
1566 
1567 static void nft_pipapo_gc_deactivate(struct net *net, struct nft_set *set,
1568 				     struct nft_pipapo_elem *e)
1569 
1570 {
1571 	struct nft_set_elem elem = {
1572 		.priv	= e,
1573 	};
1574 
1575 	nft_setelem_data_deactivate(net, set, &elem);
1576 }
1577 
1578 /**
1579  * pipapo_gc() - Drop expired entries from set, destroy start and end elements
1580  * @set:	nftables API set representation
1581  * @m:		Matching data
1582  */
1583 static void pipapo_gc(struct nft_set *set, struct nft_pipapo_match *m)
1584 {
1585 	struct nft_pipapo *priv = nft_set_priv(set);
1586 	struct net *net = read_pnet(&set->net);
1587 	u64 tstamp = nft_net_tstamp(net);
1588 	int rules_f0, first_rule = 0;
1589 	struct nft_pipapo_elem *e;
1590 	struct nft_trans_gc *gc;
1591 
1592 	gc = nft_trans_gc_alloc(set, 0, GFP_KERNEL);
1593 	if (!gc)
1594 		return;
1595 
1596 	while ((rules_f0 = pipapo_rules_same_key(m->f, first_rule))) {
1597 		union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1598 		const struct nft_pipapo_field *f;
1599 		int i, start, rules_fx;
1600 
1601 		start = first_rule;
1602 		rules_fx = rules_f0;
1603 
1604 		nft_pipapo_for_each_field(f, i, m) {
1605 			rulemap[i].to = start;
1606 			rulemap[i].n = rules_fx;
1607 
1608 			if (i < m->field_count - 1) {
1609 				rules_fx = f->mt[start].n;
1610 				start = f->mt[start].to;
1611 			}
1612 		}
1613 
1614 		/* Pick the last field, and its last index */
1615 		f--;
1616 		i--;
1617 		e = f->mt[rulemap[i].to].e;
1618 
1619 		/* synchronous gc never fails, there is no need to set on
1620 		 * NFT_SET_ELEM_DEAD_BIT.
1621 		 */
1622 		if (__nft_set_elem_expired(&e->ext, tstamp)) {
1623 			priv->dirty = true;
1624 
1625 			gc = nft_trans_gc_queue_sync(gc, GFP_ATOMIC);
1626 			if (!gc)
1627 				return;
1628 
1629 			nft_pipapo_gc_deactivate(net, set, e);
1630 			pipapo_drop(m, rulemap);
1631 			nft_trans_gc_elem_add(gc, e);
1632 
1633 			/* And check again current first rule, which is now the
1634 			 * first we haven't checked.
1635 			 */
1636 		} else {
1637 			first_rule += rules_f0;
1638 		}
1639 	}
1640 
1641 	gc = nft_trans_gc_catchall_sync(gc);
1642 	if (gc) {
1643 		nft_trans_gc_queue_sync_done(gc);
1644 		priv->last_gc = jiffies;
1645 	}
1646 }
1647 
1648 /**
1649  * pipapo_free_fields() - Free per-field tables contained in matching data
1650  * @m:		Matching data
1651  */
1652 static void pipapo_free_fields(struct nft_pipapo_match *m)
1653 {
1654 	struct nft_pipapo_field *f;
1655 	int i;
1656 
1657 	nft_pipapo_for_each_field(f, i, m) {
1658 		kvfree(f->lt);
1659 		kvfree(f->mt);
1660 	}
1661 }
1662 
1663 static void pipapo_free_match(struct nft_pipapo_match *m)
1664 {
1665 	int i;
1666 
1667 	for_each_possible_cpu(i)
1668 		pipapo_free_scratch(m, i);
1669 
1670 	free_percpu(m->scratch);
1671 	pipapo_free_fields(m);
1672 
1673 	kfree(m);
1674 }
1675 
1676 /**
1677  * pipapo_reclaim_match - RCU callback to free fields from old matching data
1678  * @rcu:	RCU head
1679  */
1680 static void pipapo_reclaim_match(struct rcu_head *rcu)
1681 {
1682 	struct nft_pipapo_match *m;
1683 
1684 	m = container_of(rcu, struct nft_pipapo_match, rcu);
1685 	pipapo_free_match(m);
1686 }
1687 
1688 /**
1689  * nft_pipapo_commit() - Replace lookup data with current working copy
1690  * @set:	nftables API set representation
1691  *
1692  * While at it, check if we should perform garbage collection on the working
1693  * copy before committing it for lookup, and don't replace the table if the
1694  * working copy doesn't have pending changes.
1695  *
1696  * We also need to create a new working copy for subsequent insertions and
1697  * deletions.
1698  */
1699 static void nft_pipapo_commit(struct nft_set *set)
1700 {
1701 	struct nft_pipapo *priv = nft_set_priv(set);
1702 	struct nft_pipapo_match *new_clone, *old;
1703 
1704 	if (time_after_eq(jiffies, priv->last_gc + nft_set_gc_interval(set)))
1705 		pipapo_gc(set, priv->clone);
1706 
1707 	if (!priv->dirty)
1708 		return;
1709 
1710 	new_clone = pipapo_clone(priv->clone);
1711 	if (IS_ERR(new_clone))
1712 		return;
1713 
1714 	priv->dirty = false;
1715 
1716 	old = rcu_access_pointer(priv->match);
1717 	rcu_assign_pointer(priv->match, priv->clone);
1718 	if (old)
1719 		call_rcu(&old->rcu, pipapo_reclaim_match);
1720 
1721 	priv->clone = new_clone;
1722 }
1723 
1724 static bool nft_pipapo_transaction_mutex_held(const struct nft_set *set)
1725 {
1726 #ifdef CONFIG_PROVE_LOCKING
1727 	const struct net *net = read_pnet(&set->net);
1728 
1729 	return lockdep_is_held(&nft_pernet(net)->commit_mutex);
1730 #else
1731 	return true;
1732 #endif
1733 }
1734 
1735 static void nft_pipapo_abort(const struct nft_set *set)
1736 {
1737 	struct nft_pipapo *priv = nft_set_priv(set);
1738 	struct nft_pipapo_match *new_clone, *m;
1739 
1740 	if (!priv->dirty)
1741 		return;
1742 
1743 	m = rcu_dereference_protected(priv->match, nft_pipapo_transaction_mutex_held(set));
1744 
1745 	new_clone = pipapo_clone(m);
1746 	if (IS_ERR(new_clone))
1747 		return;
1748 
1749 	priv->dirty = false;
1750 
1751 	pipapo_free_match(priv->clone);
1752 	priv->clone = new_clone;
1753 }
1754 
1755 /**
1756  * nft_pipapo_activate() - Mark element reference as active given key, commit
1757  * @net:	Network namespace
1758  * @set:	nftables API set representation
1759  * @elem:	nftables API element representation containing key data
1760  *
1761  * On insertion, elements are added to a copy of the matching data currently
1762  * in use for lookups, and not directly inserted into current lookup data. Both
1763  * nft_pipapo_insert() and nft_pipapo_activate() are called once for each
1764  * element, hence we can't purpose either one as a real commit operation.
1765  */
1766 static void nft_pipapo_activate(const struct net *net,
1767 				const struct nft_set *set,
1768 				const struct nft_set_elem *elem)
1769 {
1770 	struct nft_pipapo_elem *e = elem->priv;
1771 
1772 	nft_clear(net, &e->ext);
1773 }
1774 
1775 /**
1776  * pipapo_deactivate() - Check that element is in set, mark as inactive
1777  * @net:	Network namespace
1778  * @set:	nftables API set representation
1779  * @data:	Input key data
1780  * @ext:	nftables API extension pointer, used to check for end element
1781  *
1782  * This is a convenience function that can be called from both
1783  * nft_pipapo_deactivate() and nft_pipapo_flush(), as they are in fact the same
1784  * operation.
1785  *
1786  * Return: deactivated element if found, NULL otherwise.
1787  */
1788 static void *pipapo_deactivate(const struct net *net, const struct nft_set *set,
1789 			       const u8 *data, const struct nft_set_ext *ext)
1790 {
1791 	struct nft_pipapo_elem *e;
1792 
1793 	e = pipapo_get(net, set, data, nft_genmask_next(net), nft_net_tstamp(net));
1794 	if (IS_ERR(e))
1795 		return NULL;
1796 
1797 	nft_set_elem_change_active(net, set, &e->ext);
1798 
1799 	return e;
1800 }
1801 
1802 /**
1803  * nft_pipapo_deactivate() - Call pipapo_deactivate() to make element inactive
1804  * @net:	Network namespace
1805  * @set:	nftables API set representation
1806  * @elem:	nftables API element representation containing key data
1807  *
1808  * Return: deactivated element if found, NULL otherwise.
1809  */
1810 static void *nft_pipapo_deactivate(const struct net *net,
1811 				   const struct nft_set *set,
1812 				   const struct nft_set_elem *elem)
1813 {
1814 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
1815 
1816 	return pipapo_deactivate(net, set, (const u8 *)elem->key.val.data, ext);
1817 }
1818 
1819 /**
1820  * nft_pipapo_flush() - Call pipapo_deactivate() to make element inactive
1821  * @net:	Network namespace
1822  * @set:	nftables API set representation
1823  * @elem:	nftables API element representation containing key data
1824  *
1825  * This is functionally the same as nft_pipapo_deactivate(), with a slightly
1826  * different interface, and it's also called once for each element in a set
1827  * being flushed, so we can't implement, strictly speaking, a flush operation,
1828  * which would otherwise be as simple as allocating an empty copy of the
1829  * matching data.
1830  *
1831  * Note that we could in theory do that, mark the set as flushed, and ignore
1832  * subsequent calls, but we would leak all the elements after the first one,
1833  * because they wouldn't then be freed as result of API calls.
1834  *
1835  * Return: true if element was found and deactivated.
1836  */
1837 static bool nft_pipapo_flush(const struct net *net, const struct nft_set *set,
1838 			     void *elem)
1839 {
1840 	struct nft_pipapo_elem *e = elem;
1841 
1842 	return pipapo_deactivate(net, set, (const u8 *)nft_set_ext_key(&e->ext),
1843 				 &e->ext);
1844 }
1845 
1846 /**
1847  * pipapo_get_boundaries() - Get byte interval for associated rules
1848  * @f:		Field including lookup table
1849  * @first_rule:	First rule (lowest index)
1850  * @rule_count:	Number of associated rules
1851  * @left:	Byte expression for left boundary (start of range)
1852  * @right:	Byte expression for right boundary (end of range)
1853  *
1854  * Given the first rule and amount of rules that originated from the same entry,
1855  * build the original range associated with the entry, and calculate the length
1856  * of the originating netmask.
1857  *
1858  * In pictures:
1859  *
1860  *                     bucket
1861  *      group  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
1862  *        0                                                   1,2
1863  *        1   1,2
1864  *        2                                           1,2
1865  *        3                                   1,2
1866  *        4   1,2
1867  *        5        1   2
1868  *        6   1,2  1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
1869  *        7   1,2 1,2  1   1   1   1   1   1   1   1   1   1   1   1   1   1
1870  *
1871  * this is the lookup table corresponding to the IPv4 range
1872  * 192.168.1.0-192.168.2.1, which was expanded to the two composing netmasks,
1873  * rule #1: 192.168.1.0/24, and rule #2: 192.168.2.0/31.
1874  *
1875  * This function fills @left and @right with the byte values of the leftmost
1876  * and rightmost bucket indices for the lowest and highest rule indices,
1877  * respectively. If @first_rule is 1 and @rule_count is 2, we obtain, in
1878  * nibbles:
1879  *   left:  < 12, 0, 10, 8, 0, 1, 0, 0 >
1880  *   right: < 12, 0, 10, 8, 0, 2, 2, 1 >
1881  * corresponding to bytes:
1882  *   left:  < 192, 168, 1, 0 >
1883  *   right: < 192, 168, 2, 1 >
1884  * with mask length irrelevant here, unused on return, as the range is already
1885  * defined by its start and end points. The mask length is relevant for a single
1886  * ranged entry instead: if @first_rule is 1 and @rule_count is 1, we ignore
1887  * rule 2 above: @left becomes < 192, 168, 1, 0 >, @right becomes
1888  * < 192, 168, 1, 255 >, and the mask length, calculated from the distances
1889  * between leftmost and rightmost bucket indices for each group, would be 24.
1890  *
1891  * Return: mask length, in bits.
1892  */
1893 static int pipapo_get_boundaries(struct nft_pipapo_field *f, int first_rule,
1894 				 int rule_count, u8 *left, u8 *right)
1895 {
1896 	int g, mask_len = 0, bit_offset = 0;
1897 	u8 *l = left, *r = right;
1898 
1899 	for (g = 0; g < f->groups; g++) {
1900 		int b, x0, x1;
1901 
1902 		x0 = -1;
1903 		x1 = -1;
1904 		for (b = 0; b < NFT_PIPAPO_BUCKETS(f->bb); b++) {
1905 			unsigned long *pos;
1906 
1907 			pos = NFT_PIPAPO_LT_ALIGN(f->lt) +
1908 			      (g * NFT_PIPAPO_BUCKETS(f->bb) + b) * f->bsize;
1909 			if (test_bit(first_rule, pos) && x0 == -1)
1910 				x0 = b;
1911 			if (test_bit(first_rule + rule_count - 1, pos))
1912 				x1 = b;
1913 		}
1914 
1915 		*l |= x0 << (BITS_PER_BYTE - f->bb - bit_offset);
1916 		*r |= x1 << (BITS_PER_BYTE - f->bb - bit_offset);
1917 
1918 		bit_offset += f->bb;
1919 		if (bit_offset >= BITS_PER_BYTE) {
1920 			bit_offset %= BITS_PER_BYTE;
1921 			l++;
1922 			r++;
1923 		}
1924 
1925 		if (x1 - x0 == 0)
1926 			mask_len += 4;
1927 		else if (x1 - x0 == 1)
1928 			mask_len += 3;
1929 		else if (x1 - x0 == 3)
1930 			mask_len += 2;
1931 		else if (x1 - x0 == 7)
1932 			mask_len += 1;
1933 	}
1934 
1935 	return mask_len;
1936 }
1937 
1938 /**
1939  * pipapo_match_field() - Match rules against byte ranges
1940  * @f:		Field including the lookup table
1941  * @first_rule:	First of associated rules originating from same entry
1942  * @rule_count:	Amount of associated rules
1943  * @start:	Start of range to be matched
1944  * @end:	End of range to be matched
1945  *
1946  * Return: true on match, false otherwise.
1947  */
1948 static bool pipapo_match_field(struct nft_pipapo_field *f,
1949 			       int first_rule, int rule_count,
1950 			       const u8 *start, const u8 *end)
1951 {
1952 	u8 right[NFT_PIPAPO_MAX_BYTES] = { 0 };
1953 	u8 left[NFT_PIPAPO_MAX_BYTES] = { 0 };
1954 
1955 	pipapo_get_boundaries(f, first_rule, rule_count, left, right);
1956 
1957 	return !memcmp(start, left,
1958 		       f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f)) &&
1959 	       !memcmp(end, right, f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f));
1960 }
1961 
1962 /**
1963  * nft_pipapo_remove() - Remove element given key, commit
1964  * @net:	Network namespace
1965  * @set:	nftables API set representation
1966  * @elem:	nftables API element representation containing key data
1967  *
1968  * Similarly to nft_pipapo_activate(), this is used as commit operation by the
1969  * API, but it's called once per element in the pending transaction, so we can't
1970  * implement this as a single commit operation. Closest we can get is to remove
1971  * the matched element here, if any, and commit the updated matching data.
1972  */
1973 static void nft_pipapo_remove(const struct net *net, const struct nft_set *set,
1974 			      const struct nft_set_elem *elem)
1975 {
1976 	struct nft_pipapo *priv = nft_set_priv(set);
1977 	struct nft_pipapo_match *m = priv->clone;
1978 	struct nft_pipapo_elem *e = elem->priv;
1979 	int rules_f0, first_rule = 0;
1980 	const u8 *data;
1981 
1982 	data = (const u8 *)nft_set_ext_key(&e->ext);
1983 
1984 	while ((rules_f0 = pipapo_rules_same_key(m->f, first_rule))) {
1985 		union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1986 		const u8 *match_start, *match_end;
1987 		struct nft_pipapo_field *f;
1988 		int i, start, rules_fx;
1989 
1990 		match_start = data;
1991 
1992 		if (nft_set_ext_exists(&e->ext, NFT_SET_EXT_KEY_END))
1993 			match_end = (const u8 *)nft_set_ext_key_end(&e->ext)->data;
1994 		else
1995 			match_end = data;
1996 
1997 		start = first_rule;
1998 		rules_fx = rules_f0;
1999 
2000 		nft_pipapo_for_each_field(f, i, m) {
2001 			bool last = i == m->field_count - 1;
2002 
2003 			if (!pipapo_match_field(f, start, rules_fx,
2004 						match_start, match_end))
2005 				break;
2006 
2007 			rulemap[i].to = start;
2008 			rulemap[i].n = rules_fx;
2009 
2010 			rules_fx = f->mt[start].n;
2011 			start = f->mt[start].to;
2012 
2013 			match_start += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
2014 			match_end += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
2015 
2016 			if (last && f->mt[rulemap[i].to].e == e) {
2017 				priv->dirty = true;
2018 				pipapo_drop(m, rulemap);
2019 				return;
2020 			}
2021 		}
2022 
2023 		first_rule += rules_f0;
2024 	}
2025 
2026 	WARN_ON_ONCE(1); /* elem_priv not found */
2027 }
2028 
2029 /**
2030  * nft_pipapo_walk() - Walk over elements
2031  * @ctx:	nftables API context
2032  * @set:	nftables API set representation
2033  * @iter:	Iterator
2034  *
2035  * As elements are referenced in the mapping array for the last field, directly
2036  * scan that array: there's no need to follow rule mappings from the first
2037  * field.
2038  */
2039 static void nft_pipapo_walk(const struct nft_ctx *ctx, struct nft_set *set,
2040 			    struct nft_set_iter *iter)
2041 {
2042 	struct nft_pipapo *priv = nft_set_priv(set);
2043 	const struct nft_pipapo_match *m;
2044 	const struct nft_pipapo_field *f;
2045 	int i, r;
2046 
2047 	WARN_ON_ONCE(iter->type != NFT_ITER_READ &&
2048 		     iter->type != NFT_ITER_UPDATE);
2049 
2050 	rcu_read_lock();
2051 	if (iter->type == NFT_ITER_READ)
2052 		m = rcu_dereference(priv->match);
2053 	else
2054 		m = priv->clone;
2055 
2056 	if (unlikely(!m))
2057 		goto out;
2058 
2059 	for (i = 0, f = m->f; i < m->field_count - 1; i++, f++)
2060 		;
2061 
2062 	for (r = 0; r < f->rules; r++) {
2063 		struct nft_pipapo_elem *e;
2064 		struct nft_set_elem elem;
2065 
2066 		if (r < f->rules - 1 && f->mt[r + 1].e == f->mt[r].e)
2067 			continue;
2068 
2069 		if (iter->count < iter->skip)
2070 			goto cont;
2071 
2072 		e = f->mt[r].e;
2073 
2074 		elem.priv = e;
2075 
2076 		iter->err = iter->fn(ctx, set, iter, &elem);
2077 		if (iter->err < 0)
2078 			goto out;
2079 
2080 cont:
2081 		iter->count++;
2082 	}
2083 
2084 out:
2085 	rcu_read_unlock();
2086 }
2087 
2088 /**
2089  * nft_pipapo_privsize() - Return the size of private data for the set
2090  * @nla:	netlink attributes, ignored as size doesn't depend on them
2091  * @desc:	Set description, ignored as size doesn't depend on it
2092  *
2093  * Return: size of private data for this set implementation, in bytes
2094  */
2095 static u64 nft_pipapo_privsize(const struct nlattr * const nla[],
2096 			       const struct nft_set_desc *desc)
2097 {
2098 	return sizeof(struct nft_pipapo);
2099 }
2100 
2101 /**
2102  * nft_pipapo_estimate() - Set size, space and lookup complexity
2103  * @desc:	Set description, element count and field description used
2104  * @features:	Flags: NFT_SET_INTERVAL needs to be there
2105  * @est:	Storage for estimation data
2106  *
2107  * Return: true if set description is compatible, false otherwise
2108  */
2109 static bool nft_pipapo_estimate(const struct nft_set_desc *desc, u32 features,
2110 				struct nft_set_estimate *est)
2111 {
2112 	if (!(features & NFT_SET_INTERVAL) ||
2113 	    desc->field_count < NFT_PIPAPO_MIN_FIELDS)
2114 		return false;
2115 
2116 	est->size = pipapo_estimate_size(desc);
2117 	if (!est->size)
2118 		return false;
2119 
2120 	est->lookup = NFT_SET_CLASS_O_LOG_N;
2121 
2122 	est->space = NFT_SET_CLASS_O_N;
2123 
2124 	return true;
2125 }
2126 
2127 /**
2128  * nft_pipapo_init() - Initialise data for a set instance
2129  * @set:	nftables API set representation
2130  * @desc:	Set description
2131  * @nla:	netlink attributes
2132  *
2133  * Validate number and size of fields passed as NFTA_SET_DESC_CONCAT netlink
2134  * attributes, initialise internal set parameters, current instance of matching
2135  * data and a copy for subsequent insertions.
2136  *
2137  * Return: 0 on success, negative error code on failure.
2138  */
2139 static int nft_pipapo_init(const struct nft_set *set,
2140 			   const struct nft_set_desc *desc,
2141 			   const struct nlattr * const nla[])
2142 {
2143 	struct nft_pipapo *priv = nft_set_priv(set);
2144 	struct nft_pipapo_match *m;
2145 	struct nft_pipapo_field *f;
2146 	int err, i, field_count;
2147 
2148 	field_count = desc->field_count ? : 1;
2149 
2150 	if (field_count > NFT_PIPAPO_MAX_FIELDS)
2151 		return -EINVAL;
2152 
2153 	m = kmalloc(struct_size(m, f, field_count), GFP_KERNEL);
2154 	if (!m)
2155 		return -ENOMEM;
2156 
2157 	m->field_count = field_count;
2158 	m->bsize_max = 0;
2159 
2160 	m->scratch = alloc_percpu(struct nft_pipapo_scratch *);
2161 	if (!m->scratch) {
2162 		err = -ENOMEM;
2163 		goto out_scratch;
2164 	}
2165 	for_each_possible_cpu(i)
2166 		*per_cpu_ptr(m->scratch, i) = NULL;
2167 
2168 	rcu_head_init(&m->rcu);
2169 
2170 	nft_pipapo_for_each_field(f, i, m) {
2171 		int len = desc->field_len[i] ? : set->klen;
2172 
2173 		f->bb = NFT_PIPAPO_GROUP_BITS_INIT;
2174 		f->groups = len * NFT_PIPAPO_GROUPS_PER_BYTE(f);
2175 
2176 		priv->width += round_up(len, sizeof(u32));
2177 
2178 		f->bsize = 0;
2179 		f->rules = 0;
2180 		NFT_PIPAPO_LT_ASSIGN(f, NULL);
2181 		f->mt = NULL;
2182 	}
2183 
2184 	/* Create an initial clone of matching data for next insertion */
2185 	priv->clone = pipapo_clone(m);
2186 	if (IS_ERR(priv->clone)) {
2187 		err = PTR_ERR(priv->clone);
2188 		goto out_free;
2189 	}
2190 
2191 	priv->dirty = false;
2192 
2193 	rcu_assign_pointer(priv->match, m);
2194 
2195 	return 0;
2196 
2197 out_free:
2198 	free_percpu(m->scratch);
2199 out_scratch:
2200 	kfree(m);
2201 
2202 	return err;
2203 }
2204 
2205 /**
2206  * nft_set_pipapo_match_destroy() - Destroy elements from key mapping array
2207  * @ctx:	context
2208  * @set:	nftables API set representation
2209  * @m:		matching data pointing to key mapping array
2210  */
2211 static void nft_set_pipapo_match_destroy(const struct nft_ctx *ctx,
2212 					 const struct nft_set *set,
2213 					 struct nft_pipapo_match *m)
2214 {
2215 	struct nft_pipapo_field *f;
2216 	int i, r;
2217 
2218 	for (i = 0, f = m->f; i < m->field_count - 1; i++, f++)
2219 		;
2220 
2221 	for (r = 0; r < f->rules; r++) {
2222 		struct nft_pipapo_elem *e;
2223 
2224 		if (r < f->rules - 1 && f->mt[r + 1].e == f->mt[r].e)
2225 			continue;
2226 
2227 		e = f->mt[r].e;
2228 
2229 		nf_tables_set_elem_destroy(ctx, set, e);
2230 	}
2231 }
2232 
2233 /**
2234  * nft_pipapo_destroy() - Free private data for set and all committed elements
2235  * @ctx:	context
2236  * @set:	nftables API set representation
2237  */
2238 static void nft_pipapo_destroy(const struct nft_ctx *ctx,
2239 			       const struct nft_set *set)
2240 {
2241 	struct nft_pipapo *priv = nft_set_priv(set);
2242 	struct nft_pipapo_match *m;
2243 	int cpu;
2244 
2245 	m = rcu_dereference_protected(priv->match, true);
2246 	if (m) {
2247 		rcu_barrier();
2248 
2249 		for_each_possible_cpu(cpu)
2250 			pipapo_free_scratch(m, cpu);
2251 		free_percpu(m->scratch);
2252 		pipapo_free_fields(m);
2253 		kfree(m);
2254 		priv->match = NULL;
2255 	}
2256 
2257 	if (priv->clone) {
2258 		m = priv->clone;
2259 
2260 		nft_set_pipapo_match_destroy(ctx, set, m);
2261 
2262 		for_each_possible_cpu(cpu)
2263 			pipapo_free_scratch(priv->clone, cpu);
2264 		free_percpu(priv->clone->scratch);
2265 
2266 		pipapo_free_fields(priv->clone);
2267 		kfree(priv->clone);
2268 		priv->clone = NULL;
2269 	}
2270 }
2271 
2272 /**
2273  * nft_pipapo_gc_init() - Initialise garbage collection
2274  * @set:	nftables API set representation
2275  *
2276  * Instead of actually setting up a periodic work for garbage collection, as
2277  * this operation requires a swap of matching data with the working copy, we'll
2278  * do that opportunistically with other commit operations if the interval is
2279  * elapsed, so we just need to set the current jiffies timestamp here.
2280  */
2281 static void nft_pipapo_gc_init(const struct nft_set *set)
2282 {
2283 	struct nft_pipapo *priv = nft_set_priv(set);
2284 
2285 	priv->last_gc = jiffies;
2286 }
2287 
2288 const struct nft_set_type nft_set_pipapo_type = {
2289 	.features	= NFT_SET_INTERVAL | NFT_SET_MAP | NFT_SET_OBJECT |
2290 			  NFT_SET_TIMEOUT,
2291 	.ops		= {
2292 		.lookup		= nft_pipapo_lookup,
2293 		.insert		= nft_pipapo_insert,
2294 		.activate	= nft_pipapo_activate,
2295 		.deactivate	= nft_pipapo_deactivate,
2296 		.flush		= nft_pipapo_flush,
2297 		.remove		= nft_pipapo_remove,
2298 		.walk		= nft_pipapo_walk,
2299 		.get		= nft_pipapo_get,
2300 		.privsize	= nft_pipapo_privsize,
2301 		.estimate	= nft_pipapo_estimate,
2302 		.init		= nft_pipapo_init,
2303 		.destroy	= nft_pipapo_destroy,
2304 		.gc_init	= nft_pipapo_gc_init,
2305 		.commit		= nft_pipapo_commit,
2306 		.abort		= nft_pipapo_abort,
2307 		.elemsize	= offsetof(struct nft_pipapo_elem, ext),
2308 	},
2309 };
2310 
2311 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
2312 const struct nft_set_type nft_set_pipapo_avx2_type = {
2313 	.features	= NFT_SET_INTERVAL | NFT_SET_MAP | NFT_SET_OBJECT |
2314 			  NFT_SET_TIMEOUT,
2315 	.ops		= {
2316 		.lookup		= nft_pipapo_avx2_lookup,
2317 		.insert		= nft_pipapo_insert,
2318 		.activate	= nft_pipapo_activate,
2319 		.deactivate	= nft_pipapo_deactivate,
2320 		.flush		= nft_pipapo_flush,
2321 		.remove		= nft_pipapo_remove,
2322 		.walk		= nft_pipapo_walk,
2323 		.get		= nft_pipapo_get,
2324 		.privsize	= nft_pipapo_privsize,
2325 		.estimate	= nft_pipapo_avx2_estimate,
2326 		.init		= nft_pipapo_init,
2327 		.destroy	= nft_pipapo_destroy,
2328 		.gc_init	= nft_pipapo_gc_init,
2329 		.commit		= nft_pipapo_commit,
2330 		.abort		= nft_pipapo_abort,
2331 		.elemsize	= offsetof(struct nft_pipapo_elem, ext),
2332 	},
2333 };
2334 #endif
2335