1 // SPDX-License-Identifier: GPL-2.0-only
3 /* PIPAPO: PIle PAcket POlicies: set for arbitrary concatenations of ranges
5 * Copyright (c) 2019-2020 Red Hat GmbH
7 * Author: Stefano Brivio <sbrivio@redhat.com>
11 * DOC: Theory of Operation
17 * Match packet bytes against entries composed of ranged or non-ranged packet
18 * field specifiers, mapping them to arbitrary references. For example:
23 * | [net],[port],[net]... => [reference]
24 * entries [net],[port],[net]... => [reference]
25 * | [net],[port],[net]... => [reference]
28 * where [net] fields can be IP ranges or netmasks, and [port] fields are port
29 * ranges. Arbitrary packet fields can be matched.
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].
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.
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:
48 * and a packet with source port:
50 * first and second groups match, but the third doesn't. We conclude that the
51 * packet doesn't match the given entry.
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.
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.
67 * The mapping array for the last field maps to the desired references.
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
73 * A stand-alone, reference implementation, also including notes about possible
74 * future optimisations, is available at:
75 * https://pipapo.lameexcu.se/
80 * - For each packet field:
82 * - divide the b packet bits we want to classify into groups of size t,
83 * obtaining ceil(b / t) groups
85 * Example: match on destination IP address, with t = 4: 32 bits, 8 groups
88 * - allocate a lookup table with one column ("bucket") for each possible
89 * value of a group, and with one row for each group
91 * Example: 8 groups, 2^4 buckets:
96 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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().
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
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
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 > >
128 * these bits are set in the lookup table:
133 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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
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().
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.
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):
157 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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
167 * and lookup table #1 for field 1 with:
168 * - rule #0: 1024 mapping to buckets
170 * - rule #1: 2048 mapping to buckets
176 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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):
188 * rule indices in current field: 0 1 2
189 * map to rules in next field: 0 1 1
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
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.
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:
205 * rule indices in last field: 0 1
206 * map to elements: 0x66 0x42
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().
216 * - For each packet field:
218 * - start with an all-ones result bitmap (res_map in pipapo_lookup())
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
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:
233 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
235 * result bitmap is now: 0xff & 0x6 [bucket 12] = 0x6
238 * result bitmap is now: 0x6 & 0x6 [bucket 0] = 0x6
241 * result bitmap is now: 0x6 & 0x6 [bucket 10] = 0x6
244 * result bitmap is now: 0x6 & 0x6 [bucket 8] = 0x6
247 * result bitmap is now: 0x6 & 0x7 [bucket 0] = 0x6
250 * result bitmap is now: 0x6 & 0x2 [bucket 1] = 0x2
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
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
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
264 * Example: with mapping table from insertion examples, with the current
265 * result bitmap from the previous example, 0x02:
269 * rule indices in current field: 0 1 2
270 * map to rules in next field: 0 1 1
272 * the new result bitmap will be 0x02: rule 1 was set, and rule 1 will be
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:
283 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
289 * operations are: 0x2 & 0x3 [bucket 0] & 0x3 [bucket 0] & 0x2 [bucket 5]
290 * & 0x3 [bucket 0], resulting bitmap is 0x2.
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
295 * Example: 0x2 resulting bitmap from 192.168.1.5:2048, mapping array for
296 * last field from insertion example:
300 * rule indices in last field: 0 1
301 * map to elements: 0x66 0x42
303 * the matching element is at 0x42.
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
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
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
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>
342 #include "nft_set_pipapo_avx2.h"
343 #include "nft_set_pipapo.h"
345 /* Current working bitmap index, toggled between field matches */
346 static DEFINE_PER_CPU(bool, nft_pipapo_scratch_index);
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
357 * Iteration over set bits with __builtin_ctzl(): Daniel Lemire, public domain.
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.
363 * Return: -1 on no match, bit position on 'match_only', 0 otherwise.
365 int pipapo_refill(unsigned long *map, int len, int rules, unsigned long *dst,
366 union nft_pipapo_map_bucket *mt, bool match_only)
368 unsigned long bitset;
371 for (k = 0; k < len; k++) {
374 unsigned long t = bitset & -bitset;
375 int r = __builtin_ctzl(bitset);
376 int i = k * BITS_PER_LONG + r;
378 if (unlikely(i >= rules)) {
384 bitmap_clear(map, i, 1);
390 bitmap_set(dst, mt[i].to, mt[i].n);
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
407 * For more details, see DOC: Theory of Operation.
409 * Return: true on match, false otherwise.
411 bool nft_pipapo_lookup(const struct net *net, const struct nft_set *set,
412 const u32 *key, const struct nft_set_ext **ext)
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;
425 map_index = raw_cpu_read(nft_pipapo_scratch_index);
427 m = rcu_dereference(priv->match);
429 if (unlikely(!m || !*raw_cpu_ptr(m->scratch)))
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);
435 memset(res_map, 0xff, m->bsize_max * sizeof(*res_map));
437 nft_pipapo_for_each_field(f, i, m) {
438 bool last = i == m->field_count - 1;
441 /* For each bit group: select lookup table bucket depending on
442 * packet bytes value, then AND bucket value
444 if (likely(f->bb == 8))
445 pipapo_and_field_buckets_8bit(f, res_map, rp);
447 pipapo_and_field_buckets_4bit(f, res_map, rp);
448 NFT_PIPAPO_GROUP_BITS_ARE_8_OR_4;
450 rp += f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f);
452 /* Now populate the bitmap for the next field, unless this is
453 * the last field, in which case return the matched 'ext'
456 * Now res_map contains the matching bitmap, and fill_map is the
457 * bitmap for the next field.
460 b = pipapo_refill(res_map, f->bsize, f->rules, fill_map, f->mt,
463 raw_cpu_write(nft_pipapo_scratch_index, map_index);
470 *ext = &f->mt[b].e->ext;
471 if (unlikely(nft_set_elem_expired(*ext) ||
472 !nft_set_elem_active(*ext, genmask)))
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.
480 raw_cpu_write(nft_pipapo_scratch_index, map_index);
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
490 map_index = !map_index;
491 swap(res_map, fill_map);
493 rp += NFT_PIPAPO_GROUPS_PADDING(f);
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
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
512 * Return: pointer to &struct nft_pipapo_elem on match, error pointer otherwise.
514 static struct nft_pipapo_elem *pipapo_get(const struct net *net,
515 const struct nft_set *set,
516 const u8 *data, u8 genmask)
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;
525 res_map = kmalloc_array(m->bsize_max, sizeof(*res_map), GFP_ATOMIC);
527 ret = ERR_PTR(-ENOMEM);
531 fill_map = kcalloc(m->bsize_max, sizeof(*res_map), GFP_ATOMIC);
533 ret = ERR_PTR(-ENOMEM);
537 memset(res_map, 0xff, m->bsize_max * sizeof(*res_map));
539 nft_pipapo_for_each_field(f, i, m) {
540 bool last = i == m->field_count - 1;
543 /* For each bit group: select lookup table bucket depending on
544 * packet bytes value, then AND bucket value
547 pipapo_and_field_buckets_8bit(f, res_map, data);
549 pipapo_and_field_buckets_4bit(f, res_map, data);
553 data += f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f);
555 /* Now populate the bitmap for the next field, unless this is
556 * the last field, in which case return the matched 'ext'
559 * Now res_map contains the matching bitmap, and fill_map is the
560 * bitmap for the next field.
563 b = pipapo_refill(res_map, f->bsize, f->rules, fill_map, f->mt,
570 !nft_set_elem_active(&f->mt[b].e->ext, genmask)))
577 data += NFT_PIPAPO_GROUPS_PADDING(f);
579 /* Swap bitmap indices: fill_map will be the initial bitmap for
580 * the next field (i.e. the new res_map), and res_map is
581 * guaranteed to be all-zeroes at this point, ready to be filled
582 * according to the next mapping table.
584 swap(res_map, fill_map);
594 * nft_pipapo_get() - Get matching element reference given key data
595 * @net: Network namespace
596 * @set: nftables API set representation
597 * @elem: nftables API element representation containing key data
600 static void *nft_pipapo_get(const struct net *net, const struct nft_set *set,
601 const struct nft_set_elem *elem, unsigned int flags)
603 struct nft_pipapo_elem *ret;
605 ret = pipapo_get(net, set, (const u8 *)elem->key.val.data,
606 nft_genmask_cur(net));
610 if (nft_set_elem_expired(&ret->ext))
611 return ERR_PTR(-ENOENT);
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
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.
626 * Return: 0 on success, -ENOMEM on allocation failure.
628 static int pipapo_resize(struct nft_pipapo_field *f, int old_rules, int rules)
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;
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));
641 if (new_bucket_size == f->bsize)
644 if (new_bucket_size > f->bsize)
647 copy = new_bucket_size;
649 new_lt = kvzalloc(f->groups * NFT_PIPAPO_BUCKETS(f->bb) *
650 new_bucket_size * sizeof(*new_lt) +
651 NFT_PIPAPO_ALIGN_HEADROOM,
656 new_p = NFT_PIPAPO_LT_ALIGN(new_lt);
657 old_p = NFT_PIPAPO_LT_ALIGN(old_lt);
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));
665 if (new_bucket_size > f->bsize)
666 new_p += new_bucket_size - f->bsize;
668 old_p += f->bsize - new_bucket_size;
673 new_mt = kvmalloc(rules * sizeof(*new_mt), GFP_KERNEL);
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));
686 f->bsize = new_bucket_size;
687 NFT_PIPAPO_LT_ASSIGN(f, new_lt);
698 * pipapo_bucket_set() - Set rule bit in bucket given group and group value
699 * @f: Field containing lookup table
701 * @group: Group index
702 * @v: Value of bit group
704 static void pipapo_bucket_set(struct nft_pipapo_field *f, int rule, int group,
709 pos = NFT_PIPAPO_LT_ALIGN(f->lt);
710 pos += f->bsize * NFT_PIPAPO_BUCKETS(f->bb) * group;
713 __set_bit(rule, pos);
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
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
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:
731 * N(b, g) := O(b / 16, g) & O(b % 16, g + 1)
733 * This ensures equivalence of the matching results on lookup. Two examples in
737 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ... 254 255
744 * group 0 / 1 2 3 \ 4 5 6 7 8 9 10 11 12 13 |14 15 |
751 static void pipapo_lt_4b_to_8b(int old_groups, int bsize,
752 unsigned long *old_lt, unsigned long *new_lt)
756 for (g = 0; g < old_groups / 2; g++) {
757 int src_g0 = g * 2, src_g1 = g * 2 + 1;
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;
765 for (i = 0; i < bsize; i++) {
766 *new_lt = old_lt[src_i0 * bsize + i] &
767 old_lt[src_i1 * bsize + i];
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
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
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:
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)
794 * where U() denotes the arbitrary union operation (binary OR of n terms). This
795 * ensures equivalence of the matching results on lookup.
797 static void pipapo_lt_8b_to_4b(int old_groups, int bsize,
798 unsigned long *old_lt, unsigned long *new_lt)
802 memset(new_lt, 0, old_groups * 2 * NFT_PIPAPO_BUCKETS(4) * bsize *
803 sizeof(unsigned long));
805 for (g = 0; g < old_groups * 2; g += 2) {
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);
812 if (((bsrc & 0xf0) >> 4) != b)
815 for (i = 0; i < bsize; i++)
816 new_lt[i] |= old_lt[bsrc * bsize + i];
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);
826 if ((bsrc & 0x0f) != b)
829 for (i = 0; i < bsize; i++)
830 new_lt[i] |= old_lt[bsrc * bsize + i];
839 * pipapo_lt_bits_adjust() - Adjust group size for lookup table if needed
840 * @f: Field containing lookup table
842 static void pipapo_lt_bits_adjust(struct nft_pipapo_field *f)
844 unsigned long *new_lt;
848 lt_size = f->groups * NFT_PIPAPO_BUCKETS(f->bb) * f->bsize *
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;
856 lt_size = groups * NFT_PIPAPO_BUCKETS(bb) * f->bsize *
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;
863 lt_size = groups * NFT_PIPAPO_BUCKETS(bb) * f->bsize *
866 /* Don't increase group width if the resulting lookup table size
867 * would exceed the upper size threshold for a "small" set.
869 if (lt_size > NFT_PIPAPO_LT_SIZE_HIGH)
875 new_lt = kvzalloc(lt_size + NFT_PIPAPO_ALIGN_HEADROOM, GFP_KERNEL);
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));
895 NFT_PIPAPO_LT_ASSIGN(f, new_lt);
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
904 * Insert a new rule reference in lookup buckets corresponding to k and
907 * Return: 1 on success (one rule inserted), negative error code on failure.
909 static int pipapo_insert(struct nft_pipapo_field *f, const uint8_t *k,
912 int rule = f->rules++, group, ret, bit_offset = 0;
914 ret = pipapo_resize(f, f->rules - 1, f->rules);
918 for (group = 0; group < f->groups; group++) {
922 v = k[group / (BITS_PER_BYTE / f->bb)];
923 v &= GENMASK(BITS_PER_BYTE - bit_offset - 1, 0);
924 v >>= (BITS_PER_BYTE - bit_offset) - f->bb;
927 bit_offset %= BITS_PER_BYTE;
929 if (mask_bits >= (group + 1) * f->bb) {
931 pipapo_bucket_set(f, rule, group, v);
932 } else if (mask_bits <= group * f->bb) {
933 /* Completely masked */
934 for (i = 0; i < NFT_PIPAPO_BUCKETS(f->bb); i++)
935 pipapo_bucket_set(f, rule, group, i);
937 /* The mask limit falls on this group */
938 mask = GENMASK(f->bb - 1, 0);
939 mask >>= mask_bits - group * f->bb;
940 for (i = 0; i < NFT_PIPAPO_BUCKETS(f->bb); i++) {
941 if ((i & ~mask) == (v & ~mask))
942 pipapo_bucket_set(f, rule, group, i);
947 pipapo_lt_bits_adjust(f);
953 * pipapo_step_diff() - Check if setting @step bit in netmask would change it
954 * @base: Mask we are expanding
955 * @step: Step bit for given expansion step
956 * @len: Total length of mask space (set and unset bits), bytes
958 * Convenience function for mask expansion.
960 * Return: true if step bit changes mask (i.e. isn't set), false otherwise.
962 static bool pipapo_step_diff(u8 *base, int step, int len)
964 /* Network order, byte-addressed */
965 #ifdef __BIG_ENDIAN__
966 return !(BIT(step % BITS_PER_BYTE) & base[step / BITS_PER_BYTE]);
968 return !(BIT(step % BITS_PER_BYTE) &
969 base[len - 1 - step / BITS_PER_BYTE]);
974 * pipapo_step_after_end() - Check if mask exceeds range end with given step
975 * @base: Mask we are expanding
977 * @step: Step bit for given expansion step, highest bit to be set
978 * @len: Total length of mask space (set and unset bits), bytes
980 * Convenience function for mask expansion.
982 * Return: true if mask exceeds range setting step bits, false otherwise.
984 static bool pipapo_step_after_end(const u8 *base, const u8 *end, int step,
987 u8 tmp[NFT_PIPAPO_MAX_BYTES];
990 memcpy(tmp, base, len);
992 /* Network order, byte-addressed */
993 for (i = 0; i <= step; i++)
994 #ifdef __BIG_ENDIAN__
995 tmp[i / BITS_PER_BYTE] |= BIT(i % BITS_PER_BYTE);
997 tmp[len - 1 - i / BITS_PER_BYTE] |= BIT(i % BITS_PER_BYTE);
1000 return memcmp(tmp, end, len) > 0;
1004 * pipapo_base_sum() - Sum step bit to given len-sized netmask base with carry
1005 * @base: Netmask base
1006 * @step: Step bit to sum
1007 * @len: Netmask length, bytes
1009 static void pipapo_base_sum(u8 *base, int step, int len)
1014 /* Network order, byte-addressed */
1015 #ifdef __BIG_ENDIAN__
1016 for (i = step / BITS_PER_BYTE; i < len; i++) {
1018 for (i = len - 1 - step / BITS_PER_BYTE; i >= 0; i--) {
1023 base[i] += 1 << (step % BITS_PER_BYTE);
1033 * pipapo_expand() - Expand to composing netmasks, insert into lookup table
1034 * @f: Field containing lookup table
1035 * @start: Start of range
1036 * @end: End of range
1037 * @len: Length of value in bits
1039 * Expand range to composing netmasks and insert corresponding rule references
1040 * in lookup buckets.
1042 * Return: number of inserted rules on success, negative error code on failure.
1044 static int pipapo_expand(struct nft_pipapo_field *f,
1045 const u8 *start, const u8 *end, int len)
1047 int step, masks = 0, bytes = DIV_ROUND_UP(len, BITS_PER_BYTE);
1048 u8 base[NFT_PIPAPO_MAX_BYTES];
1050 memcpy(base, start, bytes);
1051 while (memcmp(base, end, bytes) <= 0) {
1055 while (pipapo_step_diff(base, step, bytes)) {
1056 if (pipapo_step_after_end(base, end, step, bytes))
1062 pipapo_insert(f, base, 0);
1069 err = pipapo_insert(f, base, len - step);
1075 pipapo_base_sum(base, step, bytes);
1082 * pipapo_map() - Insert rules in mapping tables, mapping them between fields
1083 * @m: Matching data, including mapping table
1084 * @map: Table of rule maps: array of first rule and amount of rules
1085 * in next field a given rule maps to, for each field
1086 * @e: For last field, nft_set_ext pointer matching rules map to
1088 static void pipapo_map(struct nft_pipapo_match *m,
1089 union nft_pipapo_map_bucket map[NFT_PIPAPO_MAX_FIELDS],
1090 struct nft_pipapo_elem *e)
1092 struct nft_pipapo_field *f;
1095 for (i = 0, f = m->f; i < m->field_count - 1; i++, f++) {
1096 for (j = 0; j < map[i].n; j++) {
1097 f->mt[map[i].to + j].to = map[i + 1].to;
1098 f->mt[map[i].to + j].n = map[i + 1].n;
1102 /* Last field: map to ext instead of mapping to next field */
1103 for (j = 0; j < map[i].n; j++)
1104 f->mt[map[i].to + j].e = e;
1108 * pipapo_realloc_scratch() - Reallocate scratch maps for partial match results
1109 * @clone: Copy of matching data with pending insertions and deletions
1110 * @bsize_max: Maximum bucket size, scratch maps cover two buckets
1112 * Return: 0 on success, -ENOMEM on failure.
1114 static int pipapo_realloc_scratch(struct nft_pipapo_match *clone,
1115 unsigned long bsize_max)
1119 for_each_possible_cpu(i) {
1120 unsigned long *scratch;
1121 #ifdef NFT_PIPAPO_ALIGN
1122 unsigned long *scratch_aligned;
1125 scratch = kzalloc_node(bsize_max * sizeof(*scratch) * 2 +
1126 NFT_PIPAPO_ALIGN_HEADROOM,
1127 GFP_KERNEL, cpu_to_node(i));
1129 /* On failure, there's no need to undo previous
1130 * allocations: this means that some scratch maps have
1131 * a bigger allocated size now (this is only called on
1132 * insertion), but the extra space won't be used by any
1133 * CPU as new elements are not inserted and m->bsize_max
1139 kfree(*per_cpu_ptr(clone->scratch, i));
1141 *per_cpu_ptr(clone->scratch, i) = scratch;
1143 #ifdef NFT_PIPAPO_ALIGN
1144 scratch_aligned = NFT_PIPAPO_LT_ALIGN(scratch);
1145 *per_cpu_ptr(clone->scratch_aligned, i) = scratch_aligned;
1153 * nft_pipapo_insert() - Validate and insert ranged elements
1154 * @net: Network namespace
1155 * @set: nftables API set representation
1156 * @elem: nftables API element representation containing key data
1157 * @ext2: Filled with pointer to &struct nft_set_ext in inserted element
1159 * Return: 0 on success, error pointer on failure.
1161 static int nft_pipapo_insert(const struct net *net, const struct nft_set *set,
1162 const struct nft_set_elem *elem,
1163 struct nft_set_ext **ext2)
1165 const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
1166 union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1167 const u8 *start = (const u8 *)elem->key.val.data, *end;
1168 struct nft_pipapo_elem *e = elem->priv, *dup;
1169 struct nft_pipapo *priv = nft_set_priv(set);
1170 struct nft_pipapo_match *m = priv->clone;
1171 u8 genmask = nft_genmask_next(net);
1172 struct nft_pipapo_field *f;
1173 const u8 *start_p, *end_p;
1174 int i, bsize_max, err = 0;
1176 if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END))
1177 end = (const u8 *)nft_set_ext_key_end(ext)->data;
1181 dup = pipapo_get(net, set, start, genmask);
1183 /* Check if we already have the same exact entry */
1184 const struct nft_data *dup_key, *dup_end;
1186 dup_key = nft_set_ext_key(&dup->ext);
1187 if (nft_set_ext_exists(&dup->ext, NFT_SET_EXT_KEY_END))
1188 dup_end = nft_set_ext_key_end(&dup->ext);
1192 if (!memcmp(start, dup_key->data, sizeof(*dup_key->data)) &&
1193 !memcmp(end, dup_end->data, sizeof(*dup_end->data))) {
1201 if (PTR_ERR(dup) == -ENOENT) {
1202 /* Look for partially overlapping entries */
1203 dup = pipapo_get(net, set, end, nft_genmask_next(net));
1206 if (PTR_ERR(dup) != -ENOENT) {
1208 return PTR_ERR(dup);
1216 nft_pipapo_for_each_field(f, i, m) {
1217 if (f->rules >= (unsigned long)NFT_PIPAPO_RULE0_MAX)
1220 if (memcmp(start_p, end_p,
1221 f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f)) > 0)
1224 start_p += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1225 end_p += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1231 bsize_max = m->bsize_max;
1233 nft_pipapo_for_each_field(f, i, m) {
1236 rulemap[i].to = f->rules;
1238 ret = memcmp(start, end,
1239 f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f));
1241 ret = pipapo_insert(f, start, f->groups * f->bb);
1243 ret = pipapo_expand(f, start, end, f->groups * f->bb);
1245 if (f->bsize > bsize_max)
1246 bsize_max = f->bsize;
1250 start += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1251 end += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1254 if (!*get_cpu_ptr(m->scratch) || bsize_max > m->bsize_max) {
1255 put_cpu_ptr(m->scratch);
1257 err = pipapo_realloc_scratch(m, bsize_max);
1261 m->bsize_max = bsize_max;
1263 put_cpu_ptr(m->scratch);
1268 pipapo_map(m, rulemap, e);
1274 * pipapo_clone() - Clone matching data to create new working copy
1275 * @old: Existing matching data
1277 * Return: copy of matching data passed as 'old', error pointer on failure
1279 static struct nft_pipapo_match *pipapo_clone(struct nft_pipapo_match *old)
1281 struct nft_pipapo_field *dst, *src;
1282 struct nft_pipapo_match *new;
1285 new = kmalloc(struct_size(new, f, old->field_count), GFP_KERNEL);
1287 return ERR_PTR(-ENOMEM);
1289 new->field_count = old->field_count;
1290 new->bsize_max = old->bsize_max;
1292 new->scratch = alloc_percpu(*new->scratch);
1296 #ifdef NFT_PIPAPO_ALIGN
1297 new->scratch_aligned = alloc_percpu(*new->scratch_aligned);
1298 if (!new->scratch_aligned)
1301 for_each_possible_cpu(i)
1302 *per_cpu_ptr(new->scratch, i) = NULL;
1304 if (pipapo_realloc_scratch(new, old->bsize_max))
1305 goto out_scratch_realloc;
1307 rcu_head_init(&new->rcu);
1312 for (i = 0; i < old->field_count; i++) {
1313 unsigned long *new_lt;
1315 memcpy(dst, src, offsetof(struct nft_pipapo_field, lt));
1317 new_lt = kvzalloc(src->groups * NFT_PIPAPO_BUCKETS(src->bb) *
1318 src->bsize * sizeof(*dst->lt) +
1319 NFT_PIPAPO_ALIGN_HEADROOM,
1324 NFT_PIPAPO_LT_ASSIGN(dst, new_lt);
1326 memcpy(NFT_PIPAPO_LT_ALIGN(new_lt),
1327 NFT_PIPAPO_LT_ALIGN(src->lt),
1328 src->bsize * sizeof(*dst->lt) *
1329 src->groups * NFT_PIPAPO_BUCKETS(src->bb));
1331 dst->mt = kvmalloc(src->rules * sizeof(*src->mt), GFP_KERNEL);
1335 memcpy(dst->mt, src->mt, src->rules * sizeof(*src->mt));
1345 for (dst--; i > 0; i--) {
1350 out_scratch_realloc:
1351 for_each_possible_cpu(i)
1352 kfree(*per_cpu_ptr(new->scratch, i));
1353 #ifdef NFT_PIPAPO_ALIGN
1354 free_percpu(new->scratch_aligned);
1357 free_percpu(new->scratch);
1360 return ERR_PTR(-ENOMEM);
1364 * pipapo_rules_same_key() - Get number of rules originated from the same entry
1365 * @f: Field containing mapping table
1366 * @first: Index of first rule in set of rules mapping to same entry
1368 * Using the fact that all rules in a field that originated from the same entry
1369 * will map to the same set of rules in the next field, or to the same element
1370 * reference, return the cardinality of the set of rules that originated from
1371 * the same entry as the rule with index @first, @first rule included.
1375 * field #0 0 1 2 3 4
1376 * map to: 0 1 2-4 2-4 5-9
1382 * in field #1 0 1 2 3 4 5 ...
1384 * if this is called for rule 2 on field #0, it will return 3, as also rules 2
1385 * and 3 in field 0 map to the same set of rules (2, 3, 4) in the next field.
1387 * For the last field in a set, we can rely on associated entries to map to the
1388 * same element references.
1390 * Return: Number of rules that originated from the same entry as @first.
1392 static int pipapo_rules_same_key(struct nft_pipapo_field *f, int first)
1394 struct nft_pipapo_elem *e = NULL; /* Keep gcc happy */
1397 for (r = first; r < f->rules; r++) {
1398 if (r != first && e != f->mt[r].e)
1411 * pipapo_unmap() - Remove rules from mapping tables, renumber remaining ones
1412 * @mt: Mapping array
1413 * @rules: Original amount of rules in mapping table
1414 * @start: First rule index to be removed
1415 * @n: Amount of rules to be removed
1416 * @to_offset: First rule index, in next field, this group of rules maps to
1417 * @is_last: If this is the last field, delete reference from mapping array
1419 * This is used to unmap rules from the mapping table for a single field,
1420 * maintaining consistency and compactness for the existing ones.
1422 * In pictures: let's assume that we want to delete rules 2 and 3 from the
1423 * following mapping array:
1427 * map to: 4-10 4-10 11-15 11-15 16-18
1429 * the result will be:
1433 * map to: 4-10 4-10 11-13
1435 * for fields before the last one. In case this is the mapping table for the
1436 * last field in a set, and rules map to pointers to &struct nft_pipapo_elem:
1440 * element pointers: 0x42 0x42 0x33 0x33 0x44
1442 * the result will be:
1446 * element pointers: 0x42 0x42 0x44
1448 static void pipapo_unmap(union nft_pipapo_map_bucket *mt, int rules,
1449 int start, int n, int to_offset, bool is_last)
1453 memmove(mt + start, mt + start + n, (rules - start - n) * sizeof(*mt));
1454 memset(mt + rules - n, 0, n * sizeof(*mt));
1459 for (i = start; i < rules - n; i++)
1460 mt[i].to -= to_offset;
1464 * pipapo_drop() - Delete entry from lookup and mapping tables, given rule map
1466 * @rulemap: Table of rule maps, arrays of first rule and amount of rules
1467 * in next field a given entry maps to, for each field
1469 * For each rule in lookup table buckets mapping to this set of rules, drop
1470 * all bits set in lookup table mapping. In pictures, assuming we want to drop
1471 * rules 0 and 1 from this lookup table:
1474 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1481 * 6 0,1,2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1482 * 7 1,2 1,2 1 1 1 0,1 1 1 1 1 1 1 1 1 1 1
1484 * rule 2 becomes rule 0, and the result will be:
1487 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1497 * once this is done, call unmap() to drop all the corresponding rule references
1498 * from mapping tables.
1500 static void pipapo_drop(struct nft_pipapo_match *m,
1501 union nft_pipapo_map_bucket rulemap[])
1503 struct nft_pipapo_field *f;
1506 nft_pipapo_for_each_field(f, i, m) {
1509 for (g = 0; g < f->groups; g++) {
1513 pos = NFT_PIPAPO_LT_ALIGN(f->lt) + g *
1514 NFT_PIPAPO_BUCKETS(f->bb) * f->bsize;
1516 for (b = 0; b < NFT_PIPAPO_BUCKETS(f->bb); b++) {
1517 bitmap_cut(pos, pos, rulemap[i].to,
1519 f->bsize * BITS_PER_LONG);
1525 pipapo_unmap(f->mt, f->rules, rulemap[i].to, rulemap[i].n,
1526 rulemap[i + 1].n, i == m->field_count - 1);
1527 if (pipapo_resize(f, f->rules, f->rules - rulemap[i].n)) {
1528 /* We can ignore this, a failure to shrink tables down
1529 * doesn't make tables invalid.
1533 f->rules -= rulemap[i].n;
1535 pipapo_lt_bits_adjust(f);
1539 static void nft_pipapo_gc_deactivate(struct net *net, struct nft_set *set,
1540 struct nft_pipapo_elem *e)
1543 struct nft_set_elem elem = {
1547 nft_setelem_data_deactivate(net, set, &elem);
1551 * pipapo_gc() - Drop expired entries from set, destroy start and end elements
1552 * @_set: nftables API set representation
1555 static void pipapo_gc(const struct nft_set *_set, struct nft_pipapo_match *m)
1557 struct nft_set *set = (struct nft_set *) _set;
1558 struct nft_pipapo *priv = nft_set_priv(set);
1559 struct net *net = read_pnet(&set->net);
1560 int rules_f0, first_rule = 0;
1561 struct nft_pipapo_elem *e;
1562 struct nft_trans_gc *gc;
1564 gc = nft_trans_gc_alloc(set, 0, GFP_KERNEL);
1568 while ((rules_f0 = pipapo_rules_same_key(m->f, first_rule))) {
1569 union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1570 struct nft_pipapo_field *f;
1571 int i, start, rules_fx;
1574 rules_fx = rules_f0;
1576 nft_pipapo_for_each_field(f, i, m) {
1577 rulemap[i].to = start;
1578 rulemap[i].n = rules_fx;
1580 if (i < m->field_count - 1) {
1581 rules_fx = f->mt[start].n;
1582 start = f->mt[start].to;
1586 /* Pick the last field, and its last index */
1589 e = f->mt[rulemap[i].to].e;
1591 /* synchronous gc never fails, there is no need to set on
1592 * NFT_SET_ELEM_DEAD_BIT.
1594 if (nft_set_elem_expired(&e->ext)) {
1597 gc = nft_trans_gc_queue_sync(gc, GFP_ATOMIC);
1601 nft_pipapo_gc_deactivate(net, set, e);
1602 pipapo_drop(m, rulemap);
1603 nft_trans_gc_elem_add(gc, e);
1605 /* And check again current first rule, which is now the
1606 * first we haven't checked.
1609 first_rule += rules_f0;
1613 gc = nft_trans_gc_catchall(gc, 0);
1615 nft_trans_gc_queue_sync_done(gc);
1616 priv->last_gc = jiffies;
1621 * pipapo_free_fields() - Free per-field tables contained in matching data
1624 static void pipapo_free_fields(struct nft_pipapo_match *m)
1626 struct nft_pipapo_field *f;
1629 nft_pipapo_for_each_field(f, i, m) {
1635 static void pipapo_free_match(struct nft_pipapo_match *m)
1639 for_each_possible_cpu(i)
1640 kfree(*per_cpu_ptr(m->scratch, i));
1642 #ifdef NFT_PIPAPO_ALIGN
1643 free_percpu(m->scratch_aligned);
1645 free_percpu(m->scratch);
1647 pipapo_free_fields(m);
1653 * pipapo_reclaim_match - RCU callback to free fields from old matching data
1656 static void pipapo_reclaim_match(struct rcu_head *rcu)
1658 struct nft_pipapo_match *m;
1660 m = container_of(rcu, struct nft_pipapo_match, rcu);
1661 pipapo_free_match(m);
1665 * nft_pipapo_commit() - Replace lookup data with current working copy
1666 * @set: nftables API set representation
1668 * While at it, check if we should perform garbage collection on the working
1669 * copy before committing it for lookup, and don't replace the table if the
1670 * working copy doesn't have pending changes.
1672 * We also need to create a new working copy for subsequent insertions and
1675 static void nft_pipapo_commit(const struct nft_set *set)
1677 struct nft_pipapo *priv = nft_set_priv(set);
1678 struct nft_pipapo_match *new_clone, *old;
1680 if (time_after_eq(jiffies, priv->last_gc + nft_set_gc_interval(set)))
1681 pipapo_gc(set, priv->clone);
1686 new_clone = pipapo_clone(priv->clone);
1687 if (IS_ERR(new_clone))
1690 priv->dirty = false;
1692 old = rcu_access_pointer(priv->match);
1693 rcu_assign_pointer(priv->match, priv->clone);
1695 call_rcu(&old->rcu, pipapo_reclaim_match);
1697 priv->clone = new_clone;
1700 static bool nft_pipapo_transaction_mutex_held(const struct nft_set *set)
1702 #ifdef CONFIG_PROVE_LOCKING
1703 const struct net *net = read_pnet(&set->net);
1705 return lockdep_is_held(&nft_pernet(net)->commit_mutex);
1711 static void nft_pipapo_abort(const struct nft_set *set)
1713 struct nft_pipapo *priv = nft_set_priv(set);
1714 struct nft_pipapo_match *new_clone, *m;
1719 m = rcu_dereference_protected(priv->match, nft_pipapo_transaction_mutex_held(set));
1721 new_clone = pipapo_clone(m);
1722 if (IS_ERR(new_clone))
1725 priv->dirty = false;
1727 pipapo_free_match(priv->clone);
1728 priv->clone = new_clone;
1732 * nft_pipapo_activate() - Mark element reference as active given key, commit
1733 * @net: Network namespace
1734 * @set: nftables API set representation
1735 * @elem: nftables API element representation containing key data
1737 * On insertion, elements are added to a copy of the matching data currently
1738 * in use for lookups, and not directly inserted into current lookup data. Both
1739 * nft_pipapo_insert() and nft_pipapo_activate() are called once for each
1740 * element, hence we can't purpose either one as a real commit operation.
1742 static void nft_pipapo_activate(const struct net *net,
1743 const struct nft_set *set,
1744 const struct nft_set_elem *elem)
1746 struct nft_pipapo_elem *e;
1748 e = pipapo_get(net, set, (const u8 *)elem->key.val.data, 0);
1752 nft_set_elem_change_active(net, set, &e->ext);
1756 * pipapo_deactivate() - Check that element is in set, mark as inactive
1757 * @net: Network namespace
1758 * @set: nftables API set representation
1759 * @data: Input key data
1760 * @ext: nftables API extension pointer, used to check for end element
1762 * This is a convenience function that can be called from both
1763 * nft_pipapo_deactivate() and nft_pipapo_flush(), as they are in fact the same
1766 * Return: deactivated element if found, NULL otherwise.
1768 static void *pipapo_deactivate(const struct net *net, const struct nft_set *set,
1769 const u8 *data, const struct nft_set_ext *ext)
1771 struct nft_pipapo_elem *e;
1773 e = pipapo_get(net, set, data, nft_genmask_next(net));
1777 nft_set_elem_change_active(net, set, &e->ext);
1783 * nft_pipapo_deactivate() - Call pipapo_deactivate() to make element inactive
1784 * @net: Network namespace
1785 * @set: nftables API set representation
1786 * @elem: nftables API element representation containing key data
1788 * Return: deactivated element if found, NULL otherwise.
1790 static void *nft_pipapo_deactivate(const struct net *net,
1791 const struct nft_set *set,
1792 const struct nft_set_elem *elem)
1794 const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
1796 return pipapo_deactivate(net, set, (const u8 *)elem->key.val.data, ext);
1800 * nft_pipapo_flush() - Call pipapo_deactivate() to make element inactive
1801 * @net: Network namespace
1802 * @set: nftables API set representation
1803 * @elem: nftables API element representation containing key data
1805 * This is functionally the same as nft_pipapo_deactivate(), with a slightly
1806 * different interface, and it's also called once for each element in a set
1807 * being flushed, so we can't implement, strictly speaking, a flush operation,
1808 * which would otherwise be as simple as allocating an empty copy of the
1811 * Note that we could in theory do that, mark the set as flushed, and ignore
1812 * subsequent calls, but we would leak all the elements after the first one,
1813 * because they wouldn't then be freed as result of API calls.
1815 * Return: true if element was found and deactivated.
1817 static bool nft_pipapo_flush(const struct net *net, const struct nft_set *set,
1820 struct nft_pipapo_elem *e = elem;
1822 return pipapo_deactivate(net, set, (const u8 *)nft_set_ext_key(&e->ext),
1827 * pipapo_get_boundaries() - Get byte interval for associated rules
1828 * @f: Field including lookup table
1829 * @first_rule: First rule (lowest index)
1830 * @rule_count: Number of associated rules
1831 * @left: Byte expression for left boundary (start of range)
1832 * @right: Byte expression for right boundary (end of range)
1834 * Given the first rule and amount of rules that originated from the same entry,
1835 * build the original range associated with the entry, and calculate the length
1836 * of the originating netmask.
1841 * group 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1848 * 6 1,2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1849 * 7 1,2 1,2 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1851 * this is the lookup table corresponding to the IPv4 range
1852 * 192.168.1.0-192.168.2.1, which was expanded to the two composing netmasks,
1853 * rule #1: 192.168.1.0/24, and rule #2: 192.168.2.0/31.
1855 * This function fills @left and @right with the byte values of the leftmost
1856 * and rightmost bucket indices for the lowest and highest rule indices,
1857 * respectively. If @first_rule is 1 and @rule_count is 2, we obtain, in
1859 * left: < 12, 0, 10, 8, 0, 1, 0, 0 >
1860 * right: < 12, 0, 10, 8, 0, 2, 2, 1 >
1861 * corresponding to bytes:
1862 * left: < 192, 168, 1, 0 >
1863 * right: < 192, 168, 2, 1 >
1864 * with mask length irrelevant here, unused on return, as the range is already
1865 * defined by its start and end points. The mask length is relevant for a single
1866 * ranged entry instead: if @first_rule is 1 and @rule_count is 1, we ignore
1867 * rule 2 above: @left becomes < 192, 168, 1, 0 >, @right becomes
1868 * < 192, 168, 1, 255 >, and the mask length, calculated from the distances
1869 * between leftmost and rightmost bucket indices for each group, would be 24.
1871 * Return: mask length, in bits.
1873 static int pipapo_get_boundaries(struct nft_pipapo_field *f, int first_rule,
1874 int rule_count, u8 *left, u8 *right)
1876 int g, mask_len = 0, bit_offset = 0;
1877 u8 *l = left, *r = right;
1879 for (g = 0; g < f->groups; g++) {
1884 for (b = 0; b < NFT_PIPAPO_BUCKETS(f->bb); b++) {
1887 pos = NFT_PIPAPO_LT_ALIGN(f->lt) +
1888 (g * NFT_PIPAPO_BUCKETS(f->bb) + b) * f->bsize;
1889 if (test_bit(first_rule, pos) && x0 == -1)
1891 if (test_bit(first_rule + rule_count - 1, pos))
1895 *l |= x0 << (BITS_PER_BYTE - f->bb - bit_offset);
1896 *r |= x1 << (BITS_PER_BYTE - f->bb - bit_offset);
1898 bit_offset += f->bb;
1899 if (bit_offset >= BITS_PER_BYTE) {
1900 bit_offset %= BITS_PER_BYTE;
1907 else if (x1 - x0 == 1)
1909 else if (x1 - x0 == 3)
1911 else if (x1 - x0 == 7)
1919 * pipapo_match_field() - Match rules against byte ranges
1920 * @f: Field including the lookup table
1921 * @first_rule: First of associated rules originating from same entry
1922 * @rule_count: Amount of associated rules
1923 * @start: Start of range to be matched
1924 * @end: End of range to be matched
1926 * Return: true on match, false otherwise.
1928 static bool pipapo_match_field(struct nft_pipapo_field *f,
1929 int first_rule, int rule_count,
1930 const u8 *start, const u8 *end)
1932 u8 right[NFT_PIPAPO_MAX_BYTES] = { 0 };
1933 u8 left[NFT_PIPAPO_MAX_BYTES] = { 0 };
1935 pipapo_get_boundaries(f, first_rule, rule_count, left, right);
1937 return !memcmp(start, left,
1938 f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f)) &&
1939 !memcmp(end, right, f->groups / NFT_PIPAPO_GROUPS_PER_BYTE(f));
1943 * nft_pipapo_remove() - Remove element given key, commit
1944 * @net: Network namespace
1945 * @set: nftables API set representation
1946 * @elem: nftables API element representation containing key data
1948 * Similarly to nft_pipapo_activate(), this is used as commit operation by the
1949 * API, but it's called once per element in the pending transaction, so we can't
1950 * implement this as a single commit operation. Closest we can get is to remove
1951 * the matched element here, if any, and commit the updated matching data.
1953 static void nft_pipapo_remove(const struct net *net, const struct nft_set *set,
1954 const struct nft_set_elem *elem)
1956 struct nft_pipapo *priv = nft_set_priv(set);
1957 struct nft_pipapo_match *m = priv->clone;
1958 struct nft_pipapo_elem *e = elem->priv;
1959 int rules_f0, first_rule = 0;
1962 data = (const u8 *)nft_set_ext_key(&e->ext);
1964 e = pipapo_get(net, set, data, 0);
1968 while ((rules_f0 = pipapo_rules_same_key(m->f, first_rule))) {
1969 union nft_pipapo_map_bucket rulemap[NFT_PIPAPO_MAX_FIELDS];
1970 const u8 *match_start, *match_end;
1971 struct nft_pipapo_field *f;
1972 int i, start, rules_fx;
1976 if (nft_set_ext_exists(&e->ext, NFT_SET_EXT_KEY_END))
1977 match_end = (const u8 *)nft_set_ext_key_end(&e->ext)->data;
1982 rules_fx = rules_f0;
1984 nft_pipapo_for_each_field(f, i, m) {
1985 if (!pipapo_match_field(f, start, rules_fx,
1986 match_start, match_end))
1989 rulemap[i].to = start;
1990 rulemap[i].n = rules_fx;
1992 rules_fx = f->mt[start].n;
1993 start = f->mt[start].to;
1995 match_start += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1996 match_end += NFT_PIPAPO_GROUPS_PADDED_SIZE(f);
1999 if (i == m->field_count) {
2001 pipapo_drop(m, rulemap);
2005 first_rule += rules_f0;
2010 * nft_pipapo_walk() - Walk over elements
2011 * @ctx: nftables API context
2012 * @set: nftables API set representation
2015 * As elements are referenced in the mapping array for the last field, directly
2016 * scan that array: there's no need to follow rule mappings from the first
2019 static void nft_pipapo_walk(const struct nft_ctx *ctx, struct nft_set *set,
2020 struct nft_set_iter *iter)
2022 struct nft_pipapo *priv = nft_set_priv(set);
2023 struct net *net = read_pnet(&set->net);
2024 struct nft_pipapo_match *m;
2025 struct nft_pipapo_field *f;
2029 if (iter->genmask == nft_genmask_cur(net))
2030 m = rcu_dereference(priv->match);
2037 for (i = 0, f = m->f; i < m->field_count - 1; i++, f++)
2040 for (r = 0; r < f->rules; r++) {
2041 struct nft_pipapo_elem *e;
2042 struct nft_set_elem elem;
2044 if (r < f->rules - 1 && f->mt[r + 1].e == f->mt[r].e)
2047 if (iter->count < iter->skip)
2054 iter->err = iter->fn(ctx, set, iter, &elem);
2067 * nft_pipapo_privsize() - Return the size of private data for the set
2068 * @nla: netlink attributes, ignored as size doesn't depend on them
2069 * @desc: Set description, ignored as size doesn't depend on it
2071 * Return: size of private data for this set implementation, in bytes
2073 static u64 nft_pipapo_privsize(const struct nlattr * const nla[],
2074 const struct nft_set_desc *desc)
2076 return sizeof(struct nft_pipapo);
2080 * nft_pipapo_estimate() - Set size, space and lookup complexity
2081 * @desc: Set description, element count and field description used
2082 * @features: Flags: NFT_SET_INTERVAL needs to be there
2083 * @est: Storage for estimation data
2085 * Return: true if set description is compatible, false otherwise
2087 static bool nft_pipapo_estimate(const struct nft_set_desc *desc, u32 features,
2088 struct nft_set_estimate *est)
2090 if (!(features & NFT_SET_INTERVAL) ||
2091 desc->field_count < NFT_PIPAPO_MIN_FIELDS)
2094 est->size = pipapo_estimate_size(desc);
2098 est->lookup = NFT_SET_CLASS_O_LOG_N;
2100 est->space = NFT_SET_CLASS_O_N;
2106 * nft_pipapo_init() - Initialise data for a set instance
2107 * @set: nftables API set representation
2108 * @desc: Set description
2109 * @nla: netlink attributes
2111 * Validate number and size of fields passed as NFTA_SET_DESC_CONCAT netlink
2112 * attributes, initialise internal set parameters, current instance of matching
2113 * data and a copy for subsequent insertions.
2115 * Return: 0 on success, negative error code on failure.
2117 static int nft_pipapo_init(const struct nft_set *set,
2118 const struct nft_set_desc *desc,
2119 const struct nlattr * const nla[])
2121 struct nft_pipapo *priv = nft_set_priv(set);
2122 struct nft_pipapo_match *m;
2123 struct nft_pipapo_field *f;
2124 int err, i, field_count;
2126 field_count = desc->field_count ? : 1;
2128 if (field_count > NFT_PIPAPO_MAX_FIELDS)
2131 m = kmalloc(struct_size(m, f, field_count), GFP_KERNEL);
2135 m->field_count = field_count;
2138 m->scratch = alloc_percpu(unsigned long *);
2143 for_each_possible_cpu(i)
2144 *per_cpu_ptr(m->scratch, i) = NULL;
2146 #ifdef NFT_PIPAPO_ALIGN
2147 m->scratch_aligned = alloc_percpu(unsigned long *);
2148 if (!m->scratch_aligned) {
2152 for_each_possible_cpu(i)
2153 *per_cpu_ptr(m->scratch_aligned, i) = NULL;
2156 rcu_head_init(&m->rcu);
2158 nft_pipapo_for_each_field(f, i, m) {
2159 int len = desc->field_len[i] ? : set->klen;
2161 f->bb = NFT_PIPAPO_GROUP_BITS_INIT;
2162 f->groups = len * NFT_PIPAPO_GROUPS_PER_BYTE(f);
2164 priv->width += round_up(len, sizeof(u32));
2168 NFT_PIPAPO_LT_ASSIGN(f, NULL);
2172 /* Create an initial clone of matching data for next insertion */
2173 priv->clone = pipapo_clone(m);
2174 if (IS_ERR(priv->clone)) {
2175 err = PTR_ERR(priv->clone);
2179 priv->dirty = false;
2181 rcu_assign_pointer(priv->match, m);
2186 #ifdef NFT_PIPAPO_ALIGN
2187 free_percpu(m->scratch_aligned);
2189 free_percpu(m->scratch);
2197 * nft_set_pipapo_match_destroy() - Destroy elements from key mapping array
2199 * @set: nftables API set representation
2200 * @m: matching data pointing to key mapping array
2202 static void nft_set_pipapo_match_destroy(const struct nft_ctx *ctx,
2203 const struct nft_set *set,
2204 struct nft_pipapo_match *m)
2206 struct nft_pipapo_field *f;
2209 for (i = 0, f = m->f; i < m->field_count - 1; i++, f++)
2212 for (r = 0; r < f->rules; r++) {
2213 struct nft_pipapo_elem *e;
2215 if (r < f->rules - 1 && f->mt[r + 1].e == f->mt[r].e)
2220 nf_tables_set_elem_destroy(ctx, set, e);
2225 * nft_pipapo_destroy() - Free private data for set and all committed elements
2227 * @set: nftables API set representation
2229 static void nft_pipapo_destroy(const struct nft_ctx *ctx,
2230 const struct nft_set *set)
2232 struct nft_pipapo *priv = nft_set_priv(set);
2233 struct nft_pipapo_match *m;
2236 m = rcu_dereference_protected(priv->match, true);
2240 nft_set_pipapo_match_destroy(ctx, set, m);
2242 #ifdef NFT_PIPAPO_ALIGN
2243 free_percpu(m->scratch_aligned);
2245 for_each_possible_cpu(cpu)
2246 kfree(*per_cpu_ptr(m->scratch, cpu));
2247 free_percpu(m->scratch);
2248 pipapo_free_fields(m);
2257 nft_set_pipapo_match_destroy(ctx, set, m);
2259 #ifdef NFT_PIPAPO_ALIGN
2260 free_percpu(priv->clone->scratch_aligned);
2262 for_each_possible_cpu(cpu)
2263 kfree(*per_cpu_ptr(priv->clone->scratch, cpu));
2264 free_percpu(priv->clone->scratch);
2266 pipapo_free_fields(priv->clone);
2273 * nft_pipapo_gc_init() - Initialise garbage collection
2274 * @set: nftables API set representation
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.
2281 static void nft_pipapo_gc_init(const struct nft_set *set)
2283 struct nft_pipapo *priv = nft_set_priv(set);
2285 priv->last_gc = jiffies;
2288 const struct nft_set_type nft_set_pipapo_type = {
2289 .features = NFT_SET_INTERVAL | NFT_SET_MAP | NFT_SET_OBJECT |
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),
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 |
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),