Linux Audio

Check our new training course

Loading...
v6.2
  1// SPDX-License-Identifier: GPL-2.0-only
  2/*
  3 * Longest prefix match list implementation
  4 *
  5 * Copyright (c) 2016,2017 Daniel Mack
  6 * Copyright (c) 2016 David Herrmann
  7 */
  8
  9#include <linux/bpf.h>
 10#include <linux/btf.h>
 11#include <linux/err.h>
 12#include <linux/slab.h>
 13#include <linux/spinlock.h>
 14#include <linux/vmalloc.h>
 15#include <net/ipv6.h>
 16#include <uapi/linux/btf.h>
 17#include <linux/btf_ids.h>
 18
 19/* Intermediate node */
 20#define LPM_TREE_NODE_FLAG_IM BIT(0)
 21
 22struct lpm_trie_node;
 23
 24struct lpm_trie_node {
 25	struct rcu_head rcu;
 26	struct lpm_trie_node __rcu	*child[2];
 27	u32				prefixlen;
 28	u32				flags;
 29	u8				data[];
 30};
 31
 32struct lpm_trie {
 33	struct bpf_map			map;
 34	struct lpm_trie_node __rcu	*root;
 35	size_t				n_entries;
 36	size_t				max_prefixlen;
 37	size_t				data_size;
 38	spinlock_t			lock;
 39};
 40
 41/* This trie implements a longest prefix match algorithm that can be used to
 42 * match IP addresses to a stored set of ranges.
 43 *
 44 * Data stored in @data of struct bpf_lpm_key and struct lpm_trie_node is
 45 * interpreted as big endian, so data[0] stores the most significant byte.
 46 *
 47 * Match ranges are internally stored in instances of struct lpm_trie_node
 48 * which each contain their prefix length as well as two pointers that may
 49 * lead to more nodes containing more specific matches. Each node also stores
 50 * a value that is defined by and returned to userspace via the update_elem
 51 * and lookup functions.
 52 *
 53 * For instance, let's start with a trie that was created with a prefix length
 54 * of 32, so it can be used for IPv4 addresses, and one single element that
 55 * matches 192.168.0.0/16. The data array would hence contain
 56 * [0xc0, 0xa8, 0x00, 0x00] in big-endian notation. This documentation will
 57 * stick to IP-address notation for readability though.
 58 *
 59 * As the trie is empty initially, the new node (1) will be places as root
 60 * node, denoted as (R) in the example below. As there are no other node, both
 61 * child pointers are %NULL.
 62 *
 63 *              +----------------+
 64 *              |       (1)  (R) |
 65 *              | 192.168.0.0/16 |
 66 *              |    value: 1    |
 67 *              |   [0]    [1]   |
 68 *              +----------------+
 69 *
 70 * Next, let's add a new node (2) matching 192.168.0.0/24. As there is already
 71 * a node with the same data and a smaller prefix (ie, a less specific one),
 72 * node (2) will become a child of (1). In child index depends on the next bit
 73 * that is outside of what (1) matches, and that bit is 0, so (2) will be
 74 * child[0] of (1):
 75 *
 76 *              +----------------+
 77 *              |       (1)  (R) |
 78 *              | 192.168.0.0/16 |
 79 *              |    value: 1    |
 80 *              |   [0]    [1]   |
 81 *              +----------------+
 82 *                   |
 83 *    +----------------+
 84 *    |       (2)      |
 85 *    | 192.168.0.0/24 |
 86 *    |    value: 2    |
 87 *    |   [0]    [1]   |
 88 *    +----------------+
 89 *
 90 * The child[1] slot of (1) could be filled with another node which has bit #17
 91 * (the next bit after the ones that (1) matches on) set to 1. For instance,
 92 * 192.168.128.0/24:
 93 *
 94 *              +----------------+
 95 *              |       (1)  (R) |
 96 *              | 192.168.0.0/16 |
 97 *              |    value: 1    |
 98 *              |   [0]    [1]   |
 99 *              +----------------+
100 *                   |      |
101 *    +----------------+  +------------------+
102 *    |       (2)      |  |        (3)       |
103 *    | 192.168.0.0/24 |  | 192.168.128.0/24 |
104 *    |    value: 2    |  |     value: 3     |
105 *    |   [0]    [1]   |  |    [0]    [1]    |
106 *    +----------------+  +------------------+
107 *
108 * Let's add another node (4) to the game for 192.168.1.0/24. In order to place
109 * it, node (1) is looked at first, and because (4) of the semantics laid out
110 * above (bit #17 is 0), it would normally be attached to (1) as child[0].
111 * However, that slot is already allocated, so a new node is needed in between.
112 * That node does not have a value attached to it and it will never be
113 * returned to users as result of a lookup. It is only there to differentiate
114 * the traversal further. It will get a prefix as wide as necessary to
115 * distinguish its two children:
116 *
117 *                      +----------------+
118 *                      |       (1)  (R) |
119 *                      | 192.168.0.0/16 |
120 *                      |    value: 1    |
121 *                      |   [0]    [1]   |
122 *                      +----------------+
123 *                           |      |
124 *            +----------------+  +------------------+
125 *            |       (4)  (I) |  |        (3)       |
126 *            | 192.168.0.0/23 |  | 192.168.128.0/24 |
127 *            |    value: ---  |  |     value: 3     |
128 *            |   [0]    [1]   |  |    [0]    [1]    |
129 *            +----------------+  +------------------+
130 *                 |      |
131 *  +----------------+  +----------------+
132 *  |       (2)      |  |       (5)      |
133 *  | 192.168.0.0/24 |  | 192.168.1.0/24 |
134 *  |    value: 2    |  |     value: 5   |
135 *  |   [0]    [1]   |  |   [0]    [1]   |
136 *  +----------------+  +----------------+
137 *
138 * 192.168.1.1/32 would be a child of (5) etc.
139 *
140 * An intermediate node will be turned into a 'real' node on demand. In the
141 * example above, (4) would be re-used if 192.168.0.0/23 is added to the trie.
142 *
143 * A fully populated trie would have a height of 32 nodes, as the trie was
144 * created with a prefix length of 32.
145 *
146 * The lookup starts at the root node. If the current node matches and if there
147 * is a child that can be used to become more specific, the trie is traversed
148 * downwards. The last node in the traversal that is a non-intermediate one is
149 * returned.
150 */
151
152static inline int extract_bit(const u8 *data, size_t index)
153{
154	return !!(data[index / 8] & (1 << (7 - (index % 8))));
155}
156
157/**
158 * longest_prefix_match() - determine the longest prefix
159 * @trie:	The trie to get internal sizes from
160 * @node:	The node to operate on
161 * @key:	The key to compare to @node
162 *
163 * Determine the longest prefix of @node that matches the bits in @key.
164 */
165static size_t longest_prefix_match(const struct lpm_trie *trie,
166				   const struct lpm_trie_node *node,
167				   const struct bpf_lpm_trie_key *key)
168{
169	u32 limit = min(node->prefixlen, key->prefixlen);
170	u32 prefixlen = 0, i = 0;
171
172	BUILD_BUG_ON(offsetof(struct lpm_trie_node, data) % sizeof(u32));
173	BUILD_BUG_ON(offsetof(struct bpf_lpm_trie_key, data) % sizeof(u32));
174
175#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) && defined(CONFIG_64BIT)
176
177	/* data_size >= 16 has very small probability.
178	 * We do not use a loop for optimal code generation.
179	 */
180	if (trie->data_size >= 8) {
181		u64 diff = be64_to_cpu(*(__be64 *)node->data ^
182				       *(__be64 *)key->data);
183
184		prefixlen = 64 - fls64(diff);
185		if (prefixlen >= limit)
186			return limit;
187		if (diff)
188			return prefixlen;
189		i = 8;
190	}
191#endif
192
193	while (trie->data_size >= i + 4) {
194		u32 diff = be32_to_cpu(*(__be32 *)&node->data[i] ^
195				       *(__be32 *)&key->data[i]);
196
197		prefixlen += 32 - fls(diff);
198		if (prefixlen >= limit)
199			return limit;
200		if (diff)
201			return prefixlen;
202		i += 4;
203	}
204
205	if (trie->data_size >= i + 2) {
206		u16 diff = be16_to_cpu(*(__be16 *)&node->data[i] ^
207				       *(__be16 *)&key->data[i]);
208
209		prefixlen += 16 - fls(diff);
210		if (prefixlen >= limit)
211			return limit;
212		if (diff)
213			return prefixlen;
214		i += 2;
215	}
216
217	if (trie->data_size >= i + 1) {
218		prefixlen += 8 - fls(node->data[i] ^ key->data[i]);
219
220		if (prefixlen >= limit)
221			return limit;
222	}
223
224	return prefixlen;
225}
226
227/* Called from syscall or from eBPF program */
228static void *trie_lookup_elem(struct bpf_map *map, void *_key)
229{
230	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
231	struct lpm_trie_node *node, *found = NULL;
232	struct bpf_lpm_trie_key *key = _key;
233
234	/* Start walking the trie from the root node ... */
235
236	for (node = rcu_dereference_check(trie->root, rcu_read_lock_bh_held());
237	     node;) {
238		unsigned int next_bit;
239		size_t matchlen;
240
241		/* Determine the longest prefix of @node that matches @key.
242		 * If it's the maximum possible prefix for this trie, we have
243		 * an exact match and can return it directly.
244		 */
245		matchlen = longest_prefix_match(trie, node, key);
246		if (matchlen == trie->max_prefixlen) {
247			found = node;
248			break;
249		}
250
251		/* If the number of bits that match is smaller than the prefix
252		 * length of @node, bail out and return the node we have seen
253		 * last in the traversal (ie, the parent).
254		 */
255		if (matchlen < node->prefixlen)
256			break;
257
258		/* Consider this node as return candidate unless it is an
259		 * artificially added intermediate one.
260		 */
261		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
262			found = node;
263
264		/* If the node match is fully satisfied, let's see if we can
265		 * become more specific. Determine the next bit in the key and
266		 * traverse down.
267		 */
268		next_bit = extract_bit(key->data, node->prefixlen);
269		node = rcu_dereference_check(node->child[next_bit],
270					     rcu_read_lock_bh_held());
271	}
272
273	if (!found)
274		return NULL;
275
276	return found->data + trie->data_size;
277}
278
279static struct lpm_trie_node *lpm_trie_node_alloc(const struct lpm_trie *trie,
280						 const void *value)
281{
282	struct lpm_trie_node *node;
283	size_t size = sizeof(struct lpm_trie_node) + trie->data_size;
284
285	if (value)
286		size += trie->map.value_size;
287
288	node = bpf_map_kmalloc_node(&trie->map, size, GFP_NOWAIT | __GFP_NOWARN,
289				    trie->map.numa_node);
290	if (!node)
291		return NULL;
292
293	node->flags = 0;
294
295	if (value)
296		memcpy(node->data + trie->data_size, value,
297		       trie->map.value_size);
298
299	return node;
300}
301
302/* Called from syscall or from eBPF program */
303static int trie_update_elem(struct bpf_map *map,
304			    void *_key, void *value, u64 flags)
305{
306	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
307	struct lpm_trie_node *node, *im_node = NULL, *new_node = NULL;
308	struct lpm_trie_node __rcu **slot;
309	struct bpf_lpm_trie_key *key = _key;
310	unsigned long irq_flags;
311	unsigned int next_bit;
312	size_t matchlen = 0;
313	int ret = 0;
314
315	if (unlikely(flags > BPF_EXIST))
316		return -EINVAL;
317
318	if (key->prefixlen > trie->max_prefixlen)
319		return -EINVAL;
320
321	spin_lock_irqsave(&trie->lock, irq_flags);
322
323	/* Allocate and fill a new node */
324
325	if (trie->n_entries == trie->map.max_entries) {
326		ret = -ENOSPC;
327		goto out;
328	}
329
330	new_node = lpm_trie_node_alloc(trie, value);
331	if (!new_node) {
332		ret = -ENOMEM;
333		goto out;
334	}
335
336	trie->n_entries++;
337
338	new_node->prefixlen = key->prefixlen;
339	RCU_INIT_POINTER(new_node->child[0], NULL);
340	RCU_INIT_POINTER(new_node->child[1], NULL);
341	memcpy(new_node->data, key->data, trie->data_size);
342
343	/* Now find a slot to attach the new node. To do that, walk the tree
344	 * from the root and match as many bits as possible for each node until
345	 * we either find an empty slot or a slot that needs to be replaced by
346	 * an intermediate node.
347	 */
348	slot = &trie->root;
349
350	while ((node = rcu_dereference_protected(*slot,
351					lockdep_is_held(&trie->lock)))) {
352		matchlen = longest_prefix_match(trie, node, key);
353
354		if (node->prefixlen != matchlen ||
355		    node->prefixlen == key->prefixlen ||
356		    node->prefixlen == trie->max_prefixlen)
357			break;
358
359		next_bit = extract_bit(key->data, node->prefixlen);
360		slot = &node->child[next_bit];
361	}
362
363	/* If the slot is empty (a free child pointer or an empty root),
364	 * simply assign the @new_node to that slot and be done.
365	 */
366	if (!node) {
367		rcu_assign_pointer(*slot, new_node);
368		goto out;
369	}
370
371	/* If the slot we picked already exists, replace it with @new_node
372	 * which already has the correct data array set.
373	 */
374	if (node->prefixlen == matchlen) {
375		new_node->child[0] = node->child[0];
376		new_node->child[1] = node->child[1];
377
378		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
379			trie->n_entries--;
380
381		rcu_assign_pointer(*slot, new_node);
382		kfree_rcu(node, rcu);
383
384		goto out;
385	}
386
387	/* If the new node matches the prefix completely, it must be inserted
388	 * as an ancestor. Simply insert it between @node and *@slot.
389	 */
390	if (matchlen == key->prefixlen) {
391		next_bit = extract_bit(node->data, matchlen);
392		rcu_assign_pointer(new_node->child[next_bit], node);
393		rcu_assign_pointer(*slot, new_node);
394		goto out;
395	}
396
397	im_node = lpm_trie_node_alloc(trie, NULL);
398	if (!im_node) {
399		ret = -ENOMEM;
400		goto out;
401	}
402
403	im_node->prefixlen = matchlen;
404	im_node->flags |= LPM_TREE_NODE_FLAG_IM;
405	memcpy(im_node->data, node->data, trie->data_size);
406
407	/* Now determine which child to install in which slot */
408	if (extract_bit(key->data, matchlen)) {
409		rcu_assign_pointer(im_node->child[0], node);
410		rcu_assign_pointer(im_node->child[1], new_node);
411	} else {
412		rcu_assign_pointer(im_node->child[0], new_node);
413		rcu_assign_pointer(im_node->child[1], node);
414	}
415
416	/* Finally, assign the intermediate node to the determined slot */
417	rcu_assign_pointer(*slot, im_node);
418
419out:
420	if (ret) {
421		if (new_node)
422			trie->n_entries--;
423
424		kfree(new_node);
425		kfree(im_node);
426	}
427
428	spin_unlock_irqrestore(&trie->lock, irq_flags);
429
430	return ret;
431}
432
433/* Called from syscall or from eBPF program */
434static int trie_delete_elem(struct bpf_map *map, void *_key)
435{
436	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
437	struct bpf_lpm_trie_key *key = _key;
438	struct lpm_trie_node __rcu **trim, **trim2;
439	struct lpm_trie_node *node, *parent;
440	unsigned long irq_flags;
441	unsigned int next_bit;
442	size_t matchlen = 0;
443	int ret = 0;
444
445	if (key->prefixlen > trie->max_prefixlen)
446		return -EINVAL;
447
448	spin_lock_irqsave(&trie->lock, irq_flags);
449
450	/* Walk the tree looking for an exact key/length match and keeping
451	 * track of the path we traverse.  We will need to know the node
452	 * we wish to delete, and the slot that points to the node we want
453	 * to delete.  We may also need to know the nodes parent and the
454	 * slot that contains it.
455	 */
456	trim = &trie->root;
457	trim2 = trim;
458	parent = NULL;
459	while ((node = rcu_dereference_protected(
460		       *trim, lockdep_is_held(&trie->lock)))) {
461		matchlen = longest_prefix_match(trie, node, key);
462
463		if (node->prefixlen != matchlen ||
464		    node->prefixlen == key->prefixlen)
465			break;
466
467		parent = node;
468		trim2 = trim;
469		next_bit = extract_bit(key->data, node->prefixlen);
470		trim = &node->child[next_bit];
471	}
472
473	if (!node || node->prefixlen != key->prefixlen ||
474	    node->prefixlen != matchlen ||
475	    (node->flags & LPM_TREE_NODE_FLAG_IM)) {
476		ret = -ENOENT;
477		goto out;
478	}
479
480	trie->n_entries--;
481
482	/* If the node we are removing has two children, simply mark it
483	 * as intermediate and we are done.
484	 */
485	if (rcu_access_pointer(node->child[0]) &&
486	    rcu_access_pointer(node->child[1])) {
487		node->flags |= LPM_TREE_NODE_FLAG_IM;
488		goto out;
489	}
490
491	/* If the parent of the node we are about to delete is an intermediate
492	 * node, and the deleted node doesn't have any children, we can delete
493	 * the intermediate parent as well and promote its other child
494	 * up the tree.  Doing this maintains the invariant that all
495	 * intermediate nodes have exactly 2 children and that there are no
496	 * unnecessary intermediate nodes in the tree.
497	 */
498	if (parent && (parent->flags & LPM_TREE_NODE_FLAG_IM) &&
499	    !node->child[0] && !node->child[1]) {
500		if (node == rcu_access_pointer(parent->child[0]))
501			rcu_assign_pointer(
502				*trim2, rcu_access_pointer(parent->child[1]));
503		else
504			rcu_assign_pointer(
505				*trim2, rcu_access_pointer(parent->child[0]));
506		kfree_rcu(parent, rcu);
507		kfree_rcu(node, rcu);
508		goto out;
509	}
510
511	/* The node we are removing has either zero or one child. If there
512	 * is a child, move it into the removed node's slot then delete
513	 * the node.  Otherwise just clear the slot and delete the node.
514	 */
515	if (node->child[0])
516		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[0]));
517	else if (node->child[1])
518		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[1]));
519	else
520		RCU_INIT_POINTER(*trim, NULL);
521	kfree_rcu(node, rcu);
522
523out:
524	spin_unlock_irqrestore(&trie->lock, irq_flags);
525
526	return ret;
527}
528
529#define LPM_DATA_SIZE_MAX	256
530#define LPM_DATA_SIZE_MIN	1
531
532#define LPM_VAL_SIZE_MAX	(KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
533				 sizeof(struct lpm_trie_node))
534#define LPM_VAL_SIZE_MIN	1
535
536#define LPM_KEY_SIZE(X)		(sizeof(struct bpf_lpm_trie_key) + (X))
537#define LPM_KEY_SIZE_MAX	LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
538#define LPM_KEY_SIZE_MIN	LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
539
540#define LPM_CREATE_FLAG_MASK	(BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE |	\
541				 BPF_F_ACCESS_MASK)
542
543static struct bpf_map *trie_alloc(union bpf_attr *attr)
544{
545	struct lpm_trie *trie;
 
 
546
547	if (!bpf_capable())
548		return ERR_PTR(-EPERM);
549
550	/* check sanity of attributes */
551	if (attr->max_entries == 0 ||
552	    !(attr->map_flags & BPF_F_NO_PREALLOC) ||
553	    attr->map_flags & ~LPM_CREATE_FLAG_MASK ||
554	    !bpf_map_flags_access_ok(attr->map_flags) ||
555	    attr->key_size < LPM_KEY_SIZE_MIN ||
556	    attr->key_size > LPM_KEY_SIZE_MAX ||
557	    attr->value_size < LPM_VAL_SIZE_MIN ||
558	    attr->value_size > LPM_VAL_SIZE_MAX)
559		return ERR_PTR(-EINVAL);
560
561	trie = bpf_map_area_alloc(sizeof(*trie), NUMA_NO_NODE);
562	if (!trie)
563		return ERR_PTR(-ENOMEM);
564
565	/* copy mandatory map attributes */
566	bpf_map_init_from_attr(&trie->map, attr);
567	trie->data_size = attr->key_size -
568			  offsetof(struct bpf_lpm_trie_key, data);
569	trie->max_prefixlen = trie->data_size * 8;
570
 
 
 
 
 
 
 
 
571	spin_lock_init(&trie->lock);
572
573	return &trie->map;
 
 
 
574}
575
576static void trie_free(struct bpf_map *map)
577{
578	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
579	struct lpm_trie_node __rcu **slot;
580	struct lpm_trie_node *node;
581
582	/* Always start at the root and walk down to a node that has no
583	 * children. Then free that node, nullify its reference in the parent
584	 * and start over.
585	 */
586
587	for (;;) {
588		slot = &trie->root;
589
590		for (;;) {
591			node = rcu_dereference_protected(*slot, 1);
592			if (!node)
593				goto out;
594
595			if (rcu_access_pointer(node->child[0])) {
596				slot = &node->child[0];
597				continue;
598			}
599
600			if (rcu_access_pointer(node->child[1])) {
601				slot = &node->child[1];
602				continue;
603			}
604
605			kfree(node);
606			RCU_INIT_POINTER(*slot, NULL);
607			break;
608		}
609	}
610
611out:
612	bpf_map_area_free(trie);
613}
614
615static int trie_get_next_key(struct bpf_map *map, void *_key, void *_next_key)
616{
617	struct lpm_trie_node *node, *next_node = NULL, *parent, *search_root;
618	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
619	struct bpf_lpm_trie_key *key = _key, *next_key = _next_key;
620	struct lpm_trie_node **node_stack = NULL;
621	int err = 0, stack_ptr = -1;
622	unsigned int next_bit;
623	size_t matchlen;
624
625	/* The get_next_key follows postorder. For the 4 node example in
626	 * the top of this file, the trie_get_next_key() returns the following
627	 * one after another:
628	 *   192.168.0.0/24
629	 *   192.168.1.0/24
630	 *   192.168.128.0/24
631	 *   192.168.0.0/16
632	 *
633	 * The idea is to return more specific keys before less specific ones.
634	 */
635
636	/* Empty trie */
637	search_root = rcu_dereference(trie->root);
638	if (!search_root)
639		return -ENOENT;
640
641	/* For invalid key, find the leftmost node in the trie */
642	if (!key || key->prefixlen > trie->max_prefixlen)
643		goto find_leftmost;
644
645	node_stack = kmalloc_array(trie->max_prefixlen,
646				   sizeof(struct lpm_trie_node *),
647				   GFP_ATOMIC | __GFP_NOWARN);
648	if (!node_stack)
649		return -ENOMEM;
650
651	/* Try to find the exact node for the given key */
652	for (node = search_root; node;) {
653		node_stack[++stack_ptr] = node;
654		matchlen = longest_prefix_match(trie, node, key);
655		if (node->prefixlen != matchlen ||
656		    node->prefixlen == key->prefixlen)
657			break;
658
659		next_bit = extract_bit(key->data, node->prefixlen);
660		node = rcu_dereference(node->child[next_bit]);
661	}
662	if (!node || node->prefixlen != key->prefixlen ||
663	    (node->flags & LPM_TREE_NODE_FLAG_IM))
664		goto find_leftmost;
665
666	/* The node with the exactly-matching key has been found,
667	 * find the first node in postorder after the matched node.
668	 */
669	node = node_stack[stack_ptr];
670	while (stack_ptr > 0) {
671		parent = node_stack[stack_ptr - 1];
672		if (rcu_dereference(parent->child[0]) == node) {
673			search_root = rcu_dereference(parent->child[1]);
674			if (search_root)
675				goto find_leftmost;
676		}
677		if (!(parent->flags & LPM_TREE_NODE_FLAG_IM)) {
678			next_node = parent;
679			goto do_copy;
680		}
681
682		node = parent;
683		stack_ptr--;
684	}
685
686	/* did not find anything */
687	err = -ENOENT;
688	goto free_stack;
689
690find_leftmost:
691	/* Find the leftmost non-intermediate node, all intermediate nodes
692	 * have exact two children, so this function will never return NULL.
693	 */
694	for (node = search_root; node;) {
695		if (node->flags & LPM_TREE_NODE_FLAG_IM) {
696			node = rcu_dereference(node->child[0]);
697		} else {
698			next_node = node;
699			node = rcu_dereference(node->child[0]);
700			if (!node)
701				node = rcu_dereference(next_node->child[1]);
702		}
703	}
704do_copy:
705	next_key->prefixlen = next_node->prefixlen;
706	memcpy((void *)next_key + offsetof(struct bpf_lpm_trie_key, data),
707	       next_node->data, trie->data_size);
708free_stack:
709	kfree(node_stack);
710	return err;
711}
712
713static int trie_check_btf(const struct bpf_map *map,
714			  const struct btf *btf,
715			  const struct btf_type *key_type,
716			  const struct btf_type *value_type)
717{
718	/* Keys must have struct bpf_lpm_trie_key embedded. */
719	return BTF_INFO_KIND(key_type->info) != BTF_KIND_STRUCT ?
720	       -EINVAL : 0;
721}
722
723BTF_ID_LIST_SINGLE(trie_map_btf_ids, struct, lpm_trie)
724const struct bpf_map_ops trie_map_ops = {
725	.map_meta_equal = bpf_map_meta_equal,
726	.map_alloc = trie_alloc,
727	.map_free = trie_free,
728	.map_get_next_key = trie_get_next_key,
729	.map_lookup_elem = trie_lookup_elem,
730	.map_update_elem = trie_update_elem,
731	.map_delete_elem = trie_delete_elem,
732	.map_lookup_batch = generic_map_lookup_batch,
733	.map_update_batch = generic_map_update_batch,
734	.map_delete_batch = generic_map_delete_batch,
735	.map_check_btf = trie_check_btf,
736	.map_btf_id = &trie_map_btf_ids[0],
 
737};
v5.9
  1// SPDX-License-Identifier: GPL-2.0-only
  2/*
  3 * Longest prefix match list implementation
  4 *
  5 * Copyright (c) 2016,2017 Daniel Mack
  6 * Copyright (c) 2016 David Herrmann
  7 */
  8
  9#include <linux/bpf.h>
 10#include <linux/btf.h>
 11#include <linux/err.h>
 12#include <linux/slab.h>
 13#include <linux/spinlock.h>
 14#include <linux/vmalloc.h>
 15#include <net/ipv6.h>
 16#include <uapi/linux/btf.h>
 
 17
 18/* Intermediate node */
 19#define LPM_TREE_NODE_FLAG_IM BIT(0)
 20
 21struct lpm_trie_node;
 22
 23struct lpm_trie_node {
 24	struct rcu_head rcu;
 25	struct lpm_trie_node __rcu	*child[2];
 26	u32				prefixlen;
 27	u32				flags;
 28	u8				data[];
 29};
 30
 31struct lpm_trie {
 32	struct bpf_map			map;
 33	struct lpm_trie_node __rcu	*root;
 34	size_t				n_entries;
 35	size_t				max_prefixlen;
 36	size_t				data_size;
 37	spinlock_t			lock;
 38};
 39
 40/* This trie implements a longest prefix match algorithm that can be used to
 41 * match IP addresses to a stored set of ranges.
 42 *
 43 * Data stored in @data of struct bpf_lpm_key and struct lpm_trie_node is
 44 * interpreted as big endian, so data[0] stores the most significant byte.
 45 *
 46 * Match ranges are internally stored in instances of struct lpm_trie_node
 47 * which each contain their prefix length as well as two pointers that may
 48 * lead to more nodes containing more specific matches. Each node also stores
 49 * a value that is defined by and returned to userspace via the update_elem
 50 * and lookup functions.
 51 *
 52 * For instance, let's start with a trie that was created with a prefix length
 53 * of 32, so it can be used for IPv4 addresses, and one single element that
 54 * matches 192.168.0.0/16. The data array would hence contain
 55 * [0xc0, 0xa8, 0x00, 0x00] in big-endian notation. This documentation will
 56 * stick to IP-address notation for readability though.
 57 *
 58 * As the trie is empty initially, the new node (1) will be places as root
 59 * node, denoted as (R) in the example below. As there are no other node, both
 60 * child pointers are %NULL.
 61 *
 62 *              +----------------+
 63 *              |       (1)  (R) |
 64 *              | 192.168.0.0/16 |
 65 *              |    value: 1    |
 66 *              |   [0]    [1]   |
 67 *              +----------------+
 68 *
 69 * Next, let's add a new node (2) matching 192.168.0.0/24. As there is already
 70 * a node with the same data and a smaller prefix (ie, a less specific one),
 71 * node (2) will become a child of (1). In child index depends on the next bit
 72 * that is outside of what (1) matches, and that bit is 0, so (2) will be
 73 * child[0] of (1):
 74 *
 75 *              +----------------+
 76 *              |       (1)  (R) |
 77 *              | 192.168.0.0/16 |
 78 *              |    value: 1    |
 79 *              |   [0]    [1]   |
 80 *              +----------------+
 81 *                   |
 82 *    +----------------+
 83 *    |       (2)      |
 84 *    | 192.168.0.0/24 |
 85 *    |    value: 2    |
 86 *    |   [0]    [1]   |
 87 *    +----------------+
 88 *
 89 * The child[1] slot of (1) could be filled with another node which has bit #17
 90 * (the next bit after the ones that (1) matches on) set to 1. For instance,
 91 * 192.168.128.0/24:
 92 *
 93 *              +----------------+
 94 *              |       (1)  (R) |
 95 *              | 192.168.0.0/16 |
 96 *              |    value: 1    |
 97 *              |   [0]    [1]   |
 98 *              +----------------+
 99 *                   |      |
100 *    +----------------+  +------------------+
101 *    |       (2)      |  |        (3)       |
102 *    | 192.168.0.0/24 |  | 192.168.128.0/24 |
103 *    |    value: 2    |  |     value: 3     |
104 *    |   [0]    [1]   |  |    [0]    [1]    |
105 *    +----------------+  +------------------+
106 *
107 * Let's add another node (4) to the game for 192.168.1.0/24. In order to place
108 * it, node (1) is looked at first, and because (4) of the semantics laid out
109 * above (bit #17 is 0), it would normally be attached to (1) as child[0].
110 * However, that slot is already allocated, so a new node is needed in between.
111 * That node does not have a value attached to it and it will never be
112 * returned to users as result of a lookup. It is only there to differentiate
113 * the traversal further. It will get a prefix as wide as necessary to
114 * distinguish its two children:
115 *
116 *                      +----------------+
117 *                      |       (1)  (R) |
118 *                      | 192.168.0.0/16 |
119 *                      |    value: 1    |
120 *                      |   [0]    [1]   |
121 *                      +----------------+
122 *                           |      |
123 *            +----------------+  +------------------+
124 *            |       (4)  (I) |  |        (3)       |
125 *            | 192.168.0.0/23 |  | 192.168.128.0/24 |
126 *            |    value: ---  |  |     value: 3     |
127 *            |   [0]    [1]   |  |    [0]    [1]    |
128 *            +----------------+  +------------------+
129 *                 |      |
130 *  +----------------+  +----------------+
131 *  |       (2)      |  |       (5)      |
132 *  | 192.168.0.0/24 |  | 192.168.1.0/24 |
133 *  |    value: 2    |  |     value: 5   |
134 *  |   [0]    [1]   |  |   [0]    [1]   |
135 *  +----------------+  +----------------+
136 *
137 * 192.168.1.1/32 would be a child of (5) etc.
138 *
139 * An intermediate node will be turned into a 'real' node on demand. In the
140 * example above, (4) would be re-used if 192.168.0.0/23 is added to the trie.
141 *
142 * A fully populated trie would have a height of 32 nodes, as the trie was
143 * created with a prefix length of 32.
144 *
145 * The lookup starts at the root node. If the current node matches and if there
146 * is a child that can be used to become more specific, the trie is traversed
147 * downwards. The last node in the traversal that is a non-intermediate one is
148 * returned.
149 */
150
151static inline int extract_bit(const u8 *data, size_t index)
152{
153	return !!(data[index / 8] & (1 << (7 - (index % 8))));
154}
155
156/**
157 * longest_prefix_match() - determine the longest prefix
158 * @trie:	The trie to get internal sizes from
159 * @node:	The node to operate on
160 * @key:	The key to compare to @node
161 *
162 * Determine the longest prefix of @node that matches the bits in @key.
163 */
164static size_t longest_prefix_match(const struct lpm_trie *trie,
165				   const struct lpm_trie_node *node,
166				   const struct bpf_lpm_trie_key *key)
167{
168	u32 limit = min(node->prefixlen, key->prefixlen);
169	u32 prefixlen = 0, i = 0;
170
171	BUILD_BUG_ON(offsetof(struct lpm_trie_node, data) % sizeof(u32));
172	BUILD_BUG_ON(offsetof(struct bpf_lpm_trie_key, data) % sizeof(u32));
173
174#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) && defined(CONFIG_64BIT)
175
176	/* data_size >= 16 has very small probability.
177	 * We do not use a loop for optimal code generation.
178	 */
179	if (trie->data_size >= 8) {
180		u64 diff = be64_to_cpu(*(__be64 *)node->data ^
181				       *(__be64 *)key->data);
182
183		prefixlen = 64 - fls64(diff);
184		if (prefixlen >= limit)
185			return limit;
186		if (diff)
187			return prefixlen;
188		i = 8;
189	}
190#endif
191
192	while (trie->data_size >= i + 4) {
193		u32 diff = be32_to_cpu(*(__be32 *)&node->data[i] ^
194				       *(__be32 *)&key->data[i]);
195
196		prefixlen += 32 - fls(diff);
197		if (prefixlen >= limit)
198			return limit;
199		if (diff)
200			return prefixlen;
201		i += 4;
202	}
203
204	if (trie->data_size >= i + 2) {
205		u16 diff = be16_to_cpu(*(__be16 *)&node->data[i] ^
206				       *(__be16 *)&key->data[i]);
207
208		prefixlen += 16 - fls(diff);
209		if (prefixlen >= limit)
210			return limit;
211		if (diff)
212			return prefixlen;
213		i += 2;
214	}
215
216	if (trie->data_size >= i + 1) {
217		prefixlen += 8 - fls(node->data[i] ^ key->data[i]);
218
219		if (prefixlen >= limit)
220			return limit;
221	}
222
223	return prefixlen;
224}
225
226/* Called from syscall or from eBPF program */
227static void *trie_lookup_elem(struct bpf_map *map, void *_key)
228{
229	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
230	struct lpm_trie_node *node, *found = NULL;
231	struct bpf_lpm_trie_key *key = _key;
232
233	/* Start walking the trie from the root node ... */
234
235	for (node = rcu_dereference(trie->root); node;) {
 
236		unsigned int next_bit;
237		size_t matchlen;
238
239		/* Determine the longest prefix of @node that matches @key.
240		 * If it's the maximum possible prefix for this trie, we have
241		 * an exact match and can return it directly.
242		 */
243		matchlen = longest_prefix_match(trie, node, key);
244		if (matchlen == trie->max_prefixlen) {
245			found = node;
246			break;
247		}
248
249		/* If the number of bits that match is smaller than the prefix
250		 * length of @node, bail out and return the node we have seen
251		 * last in the traversal (ie, the parent).
252		 */
253		if (matchlen < node->prefixlen)
254			break;
255
256		/* Consider this node as return candidate unless it is an
257		 * artificially added intermediate one.
258		 */
259		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
260			found = node;
261
262		/* If the node match is fully satisfied, let's see if we can
263		 * become more specific. Determine the next bit in the key and
264		 * traverse down.
265		 */
266		next_bit = extract_bit(key->data, node->prefixlen);
267		node = rcu_dereference(node->child[next_bit]);
 
268	}
269
270	if (!found)
271		return NULL;
272
273	return found->data + trie->data_size;
274}
275
276static struct lpm_trie_node *lpm_trie_node_alloc(const struct lpm_trie *trie,
277						 const void *value)
278{
279	struct lpm_trie_node *node;
280	size_t size = sizeof(struct lpm_trie_node) + trie->data_size;
281
282	if (value)
283		size += trie->map.value_size;
284
285	node = kmalloc_node(size, GFP_ATOMIC | __GFP_NOWARN,
286			    trie->map.numa_node);
287	if (!node)
288		return NULL;
289
290	node->flags = 0;
291
292	if (value)
293		memcpy(node->data + trie->data_size, value,
294		       trie->map.value_size);
295
296	return node;
297}
298
299/* Called from syscall or from eBPF program */
300static int trie_update_elem(struct bpf_map *map,
301			    void *_key, void *value, u64 flags)
302{
303	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
304	struct lpm_trie_node *node, *im_node = NULL, *new_node = NULL;
305	struct lpm_trie_node __rcu **slot;
306	struct bpf_lpm_trie_key *key = _key;
307	unsigned long irq_flags;
308	unsigned int next_bit;
309	size_t matchlen = 0;
310	int ret = 0;
311
312	if (unlikely(flags > BPF_EXIST))
313		return -EINVAL;
314
315	if (key->prefixlen > trie->max_prefixlen)
316		return -EINVAL;
317
318	spin_lock_irqsave(&trie->lock, irq_flags);
319
320	/* Allocate and fill a new node */
321
322	if (trie->n_entries == trie->map.max_entries) {
323		ret = -ENOSPC;
324		goto out;
325	}
326
327	new_node = lpm_trie_node_alloc(trie, value);
328	if (!new_node) {
329		ret = -ENOMEM;
330		goto out;
331	}
332
333	trie->n_entries++;
334
335	new_node->prefixlen = key->prefixlen;
336	RCU_INIT_POINTER(new_node->child[0], NULL);
337	RCU_INIT_POINTER(new_node->child[1], NULL);
338	memcpy(new_node->data, key->data, trie->data_size);
339
340	/* Now find a slot to attach the new node. To do that, walk the tree
341	 * from the root and match as many bits as possible for each node until
342	 * we either find an empty slot or a slot that needs to be replaced by
343	 * an intermediate node.
344	 */
345	slot = &trie->root;
346
347	while ((node = rcu_dereference_protected(*slot,
348					lockdep_is_held(&trie->lock)))) {
349		matchlen = longest_prefix_match(trie, node, key);
350
351		if (node->prefixlen != matchlen ||
352		    node->prefixlen == key->prefixlen ||
353		    node->prefixlen == trie->max_prefixlen)
354			break;
355
356		next_bit = extract_bit(key->data, node->prefixlen);
357		slot = &node->child[next_bit];
358	}
359
360	/* If the slot is empty (a free child pointer or an empty root),
361	 * simply assign the @new_node to that slot and be done.
362	 */
363	if (!node) {
364		rcu_assign_pointer(*slot, new_node);
365		goto out;
366	}
367
368	/* If the slot we picked already exists, replace it with @new_node
369	 * which already has the correct data array set.
370	 */
371	if (node->prefixlen == matchlen) {
372		new_node->child[0] = node->child[0];
373		new_node->child[1] = node->child[1];
374
375		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
376			trie->n_entries--;
377
378		rcu_assign_pointer(*slot, new_node);
379		kfree_rcu(node, rcu);
380
381		goto out;
382	}
383
384	/* If the new node matches the prefix completely, it must be inserted
385	 * as an ancestor. Simply insert it between @node and *@slot.
386	 */
387	if (matchlen == key->prefixlen) {
388		next_bit = extract_bit(node->data, matchlen);
389		rcu_assign_pointer(new_node->child[next_bit], node);
390		rcu_assign_pointer(*slot, new_node);
391		goto out;
392	}
393
394	im_node = lpm_trie_node_alloc(trie, NULL);
395	if (!im_node) {
396		ret = -ENOMEM;
397		goto out;
398	}
399
400	im_node->prefixlen = matchlen;
401	im_node->flags |= LPM_TREE_NODE_FLAG_IM;
402	memcpy(im_node->data, node->data, trie->data_size);
403
404	/* Now determine which child to install in which slot */
405	if (extract_bit(key->data, matchlen)) {
406		rcu_assign_pointer(im_node->child[0], node);
407		rcu_assign_pointer(im_node->child[1], new_node);
408	} else {
409		rcu_assign_pointer(im_node->child[0], new_node);
410		rcu_assign_pointer(im_node->child[1], node);
411	}
412
413	/* Finally, assign the intermediate node to the determined spot */
414	rcu_assign_pointer(*slot, im_node);
415
416out:
417	if (ret) {
418		if (new_node)
419			trie->n_entries--;
420
421		kfree(new_node);
422		kfree(im_node);
423	}
424
425	spin_unlock_irqrestore(&trie->lock, irq_flags);
426
427	return ret;
428}
429
430/* Called from syscall or from eBPF program */
431static int trie_delete_elem(struct bpf_map *map, void *_key)
432{
433	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
434	struct bpf_lpm_trie_key *key = _key;
435	struct lpm_trie_node __rcu **trim, **trim2;
436	struct lpm_trie_node *node, *parent;
437	unsigned long irq_flags;
438	unsigned int next_bit;
439	size_t matchlen = 0;
440	int ret = 0;
441
442	if (key->prefixlen > trie->max_prefixlen)
443		return -EINVAL;
444
445	spin_lock_irqsave(&trie->lock, irq_flags);
446
447	/* Walk the tree looking for an exact key/length match and keeping
448	 * track of the path we traverse.  We will need to know the node
449	 * we wish to delete, and the slot that points to the node we want
450	 * to delete.  We may also need to know the nodes parent and the
451	 * slot that contains it.
452	 */
453	trim = &trie->root;
454	trim2 = trim;
455	parent = NULL;
456	while ((node = rcu_dereference_protected(
457		       *trim, lockdep_is_held(&trie->lock)))) {
458		matchlen = longest_prefix_match(trie, node, key);
459
460		if (node->prefixlen != matchlen ||
461		    node->prefixlen == key->prefixlen)
462			break;
463
464		parent = node;
465		trim2 = trim;
466		next_bit = extract_bit(key->data, node->prefixlen);
467		trim = &node->child[next_bit];
468	}
469
470	if (!node || node->prefixlen != key->prefixlen ||
471	    node->prefixlen != matchlen ||
472	    (node->flags & LPM_TREE_NODE_FLAG_IM)) {
473		ret = -ENOENT;
474		goto out;
475	}
476
477	trie->n_entries--;
478
479	/* If the node we are removing has two children, simply mark it
480	 * as intermediate and we are done.
481	 */
482	if (rcu_access_pointer(node->child[0]) &&
483	    rcu_access_pointer(node->child[1])) {
484		node->flags |= LPM_TREE_NODE_FLAG_IM;
485		goto out;
486	}
487
488	/* If the parent of the node we are about to delete is an intermediate
489	 * node, and the deleted node doesn't have any children, we can delete
490	 * the intermediate parent as well and promote its other child
491	 * up the tree.  Doing this maintains the invariant that all
492	 * intermediate nodes have exactly 2 children and that there are no
493	 * unnecessary intermediate nodes in the tree.
494	 */
495	if (parent && (parent->flags & LPM_TREE_NODE_FLAG_IM) &&
496	    !node->child[0] && !node->child[1]) {
497		if (node == rcu_access_pointer(parent->child[0]))
498			rcu_assign_pointer(
499				*trim2, rcu_access_pointer(parent->child[1]));
500		else
501			rcu_assign_pointer(
502				*trim2, rcu_access_pointer(parent->child[0]));
503		kfree_rcu(parent, rcu);
504		kfree_rcu(node, rcu);
505		goto out;
506	}
507
508	/* The node we are removing has either zero or one child. If there
509	 * is a child, move it into the removed node's slot then delete
510	 * the node.  Otherwise just clear the slot and delete the node.
511	 */
512	if (node->child[0])
513		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[0]));
514	else if (node->child[1])
515		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[1]));
516	else
517		RCU_INIT_POINTER(*trim, NULL);
518	kfree_rcu(node, rcu);
519
520out:
521	spin_unlock_irqrestore(&trie->lock, irq_flags);
522
523	return ret;
524}
525
526#define LPM_DATA_SIZE_MAX	256
527#define LPM_DATA_SIZE_MIN	1
528
529#define LPM_VAL_SIZE_MAX	(KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
530				 sizeof(struct lpm_trie_node))
531#define LPM_VAL_SIZE_MIN	1
532
533#define LPM_KEY_SIZE(X)		(sizeof(struct bpf_lpm_trie_key) + (X))
534#define LPM_KEY_SIZE_MAX	LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
535#define LPM_KEY_SIZE_MIN	LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
536
537#define LPM_CREATE_FLAG_MASK	(BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE |	\
538				 BPF_F_ACCESS_MASK)
539
540static struct bpf_map *trie_alloc(union bpf_attr *attr)
541{
542	struct lpm_trie *trie;
543	u64 cost = sizeof(*trie), cost_per_node;
544	int ret;
545
546	if (!bpf_capable())
547		return ERR_PTR(-EPERM);
548
549	/* check sanity of attributes */
550	if (attr->max_entries == 0 ||
551	    !(attr->map_flags & BPF_F_NO_PREALLOC) ||
552	    attr->map_flags & ~LPM_CREATE_FLAG_MASK ||
553	    !bpf_map_flags_access_ok(attr->map_flags) ||
554	    attr->key_size < LPM_KEY_SIZE_MIN ||
555	    attr->key_size > LPM_KEY_SIZE_MAX ||
556	    attr->value_size < LPM_VAL_SIZE_MIN ||
557	    attr->value_size > LPM_VAL_SIZE_MAX)
558		return ERR_PTR(-EINVAL);
559
560	trie = kzalloc(sizeof(*trie), GFP_USER | __GFP_NOWARN);
561	if (!trie)
562		return ERR_PTR(-ENOMEM);
563
564	/* copy mandatory map attributes */
565	bpf_map_init_from_attr(&trie->map, attr);
566	trie->data_size = attr->key_size -
567			  offsetof(struct bpf_lpm_trie_key, data);
568	trie->max_prefixlen = trie->data_size * 8;
569
570	cost_per_node = sizeof(struct lpm_trie_node) +
571			attr->value_size + trie->data_size;
572	cost += (u64) attr->max_entries * cost_per_node;
573
574	ret = bpf_map_charge_init(&trie->map.memory, cost);
575	if (ret)
576		goto out_err;
577
578	spin_lock_init(&trie->lock);
579
580	return &trie->map;
581out_err:
582	kfree(trie);
583	return ERR_PTR(ret);
584}
585
586static void trie_free(struct bpf_map *map)
587{
588	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
589	struct lpm_trie_node __rcu **slot;
590	struct lpm_trie_node *node;
591
592	/* Always start at the root and walk down to a node that has no
593	 * children. Then free that node, nullify its reference in the parent
594	 * and start over.
595	 */
596
597	for (;;) {
598		slot = &trie->root;
599
600		for (;;) {
601			node = rcu_dereference_protected(*slot, 1);
602			if (!node)
603				goto out;
604
605			if (rcu_access_pointer(node->child[0])) {
606				slot = &node->child[0];
607				continue;
608			}
609
610			if (rcu_access_pointer(node->child[1])) {
611				slot = &node->child[1];
612				continue;
613			}
614
615			kfree(node);
616			RCU_INIT_POINTER(*slot, NULL);
617			break;
618		}
619	}
620
621out:
622	kfree(trie);
623}
624
625static int trie_get_next_key(struct bpf_map *map, void *_key, void *_next_key)
626{
627	struct lpm_trie_node *node, *next_node = NULL, *parent, *search_root;
628	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
629	struct bpf_lpm_trie_key *key = _key, *next_key = _next_key;
630	struct lpm_trie_node **node_stack = NULL;
631	int err = 0, stack_ptr = -1;
632	unsigned int next_bit;
633	size_t matchlen;
634
635	/* The get_next_key follows postorder. For the 4 node example in
636	 * the top of this file, the trie_get_next_key() returns the following
637	 * one after another:
638	 *   192.168.0.0/24
639	 *   192.168.1.0/24
640	 *   192.168.128.0/24
641	 *   192.168.0.0/16
642	 *
643	 * The idea is to return more specific keys before less specific ones.
644	 */
645
646	/* Empty trie */
647	search_root = rcu_dereference(trie->root);
648	if (!search_root)
649		return -ENOENT;
650
651	/* For invalid key, find the leftmost node in the trie */
652	if (!key || key->prefixlen > trie->max_prefixlen)
653		goto find_leftmost;
654
655	node_stack = kmalloc_array(trie->max_prefixlen,
656				   sizeof(struct lpm_trie_node *),
657				   GFP_ATOMIC | __GFP_NOWARN);
658	if (!node_stack)
659		return -ENOMEM;
660
661	/* Try to find the exact node for the given key */
662	for (node = search_root; node;) {
663		node_stack[++stack_ptr] = node;
664		matchlen = longest_prefix_match(trie, node, key);
665		if (node->prefixlen != matchlen ||
666		    node->prefixlen == key->prefixlen)
667			break;
668
669		next_bit = extract_bit(key->data, node->prefixlen);
670		node = rcu_dereference(node->child[next_bit]);
671	}
672	if (!node || node->prefixlen != key->prefixlen ||
673	    (node->flags & LPM_TREE_NODE_FLAG_IM))
674		goto find_leftmost;
675
676	/* The node with the exactly-matching key has been found,
677	 * find the first node in postorder after the matched node.
678	 */
679	node = node_stack[stack_ptr];
680	while (stack_ptr > 0) {
681		parent = node_stack[stack_ptr - 1];
682		if (rcu_dereference(parent->child[0]) == node) {
683			search_root = rcu_dereference(parent->child[1]);
684			if (search_root)
685				goto find_leftmost;
686		}
687		if (!(parent->flags & LPM_TREE_NODE_FLAG_IM)) {
688			next_node = parent;
689			goto do_copy;
690		}
691
692		node = parent;
693		stack_ptr--;
694	}
695
696	/* did not find anything */
697	err = -ENOENT;
698	goto free_stack;
699
700find_leftmost:
701	/* Find the leftmost non-intermediate node, all intermediate nodes
702	 * have exact two children, so this function will never return NULL.
703	 */
704	for (node = search_root; node;) {
705		if (node->flags & LPM_TREE_NODE_FLAG_IM) {
706			node = rcu_dereference(node->child[0]);
707		} else {
708			next_node = node;
709			node = rcu_dereference(node->child[0]);
710			if (!node)
711				node = rcu_dereference(next_node->child[1]);
712		}
713	}
714do_copy:
715	next_key->prefixlen = next_node->prefixlen;
716	memcpy((void *)next_key + offsetof(struct bpf_lpm_trie_key, data),
717	       next_node->data, trie->data_size);
718free_stack:
719	kfree(node_stack);
720	return err;
721}
722
723static int trie_check_btf(const struct bpf_map *map,
724			  const struct btf *btf,
725			  const struct btf_type *key_type,
726			  const struct btf_type *value_type)
727{
728	/* Keys must have struct bpf_lpm_trie_key embedded. */
729	return BTF_INFO_KIND(key_type->info) != BTF_KIND_STRUCT ?
730	       -EINVAL : 0;
731}
732
733static int trie_map_btf_id;
734const struct bpf_map_ops trie_map_ops = {
 
735	.map_alloc = trie_alloc,
736	.map_free = trie_free,
737	.map_get_next_key = trie_get_next_key,
738	.map_lookup_elem = trie_lookup_elem,
739	.map_update_elem = trie_update_elem,
740	.map_delete_elem = trie_delete_elem,
 
 
 
741	.map_check_btf = trie_check_btf,
742	.map_btf_name = "lpm_trie",
743	.map_btf_id = &trie_map_btf_id,
744};