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