xref: /openbmc/linux/kernel/bpf/lpm_trie.c (revision 63f13eb5)
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 
22 struct lpm_trie_node;
23 
24 struct 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 
32 struct 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 
extract_bit(const u8 * data,size_t index)152 static 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  */
longest_prefix_match(const struct lpm_trie * trie,const struct lpm_trie_node * node,const struct bpf_lpm_trie_key_u8 * key)165 static size_t longest_prefix_match(const struct lpm_trie *trie,
166 				   const struct lpm_trie_node *node,
167 				   const struct bpf_lpm_trie_key_u8 *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_u8, 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 */
trie_lookup_elem(struct bpf_map * map,void * _key)228 static 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_u8 *key = _key;
233 
234 	if (key->prefixlen > trie->max_prefixlen)
235 		return NULL;
236 
237 	/* Start walking the trie from the root node ... */
238 
239 	for (node = rcu_dereference_check(trie->root, rcu_read_lock_bh_held());
240 	     node;) {
241 		unsigned int next_bit;
242 		size_t matchlen;
243 
244 		/* Determine the longest prefix of @node that matches @key.
245 		 * If it's the maximum possible prefix for this trie, we have
246 		 * an exact match and can return it directly.
247 		 */
248 		matchlen = longest_prefix_match(trie, node, key);
249 		if (matchlen == trie->max_prefixlen) {
250 			found = node;
251 			break;
252 		}
253 
254 		/* If the number of bits that match is smaller than the prefix
255 		 * length of @node, bail out and return the node we have seen
256 		 * last in the traversal (ie, the parent).
257 		 */
258 		if (matchlen < node->prefixlen)
259 			break;
260 
261 		/* Consider this node as return candidate unless it is an
262 		 * artificially added intermediate one.
263 		 */
264 		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
265 			found = node;
266 
267 		/* If the node match is fully satisfied, let's see if we can
268 		 * become more specific. Determine the next bit in the key and
269 		 * traverse down.
270 		 */
271 		next_bit = extract_bit(key->data, node->prefixlen);
272 		node = rcu_dereference_check(node->child[next_bit],
273 					     rcu_read_lock_bh_held());
274 	}
275 
276 	if (!found)
277 		return NULL;
278 
279 	return found->data + trie->data_size;
280 }
281 
lpm_trie_node_alloc(const struct lpm_trie * trie,const void * value)282 static struct lpm_trie_node *lpm_trie_node_alloc(const struct lpm_trie *trie,
283 						 const void *value)
284 {
285 	struct lpm_trie_node *node;
286 	size_t size = sizeof(struct lpm_trie_node) + trie->data_size;
287 
288 	if (value)
289 		size += trie->map.value_size;
290 
291 	node = bpf_map_kmalloc_node(&trie->map, size, GFP_NOWAIT | __GFP_NOWARN,
292 				    trie->map.numa_node);
293 	if (!node)
294 		return NULL;
295 
296 	node->flags = 0;
297 
298 	if (value)
299 		memcpy(node->data + trie->data_size, value,
300 		       trie->map.value_size);
301 
302 	return node;
303 }
304 
305 /* Called from syscall or from eBPF program */
trie_update_elem(struct bpf_map * map,void * _key,void * value,u64 flags)306 static long trie_update_elem(struct bpf_map *map,
307 			     void *_key, void *value, u64 flags)
308 {
309 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
310 	struct lpm_trie_node *node, *im_node = NULL, *new_node = NULL;
311 	struct lpm_trie_node *free_node = NULL;
312 	struct lpm_trie_node __rcu **slot;
313 	struct bpf_lpm_trie_key_u8 *key = _key;
314 	unsigned long irq_flags;
315 	unsigned int next_bit;
316 	size_t matchlen = 0;
317 	int ret = 0;
318 
319 	if (unlikely(flags > BPF_EXIST))
320 		return -EINVAL;
321 
322 	if (key->prefixlen > trie->max_prefixlen)
323 		return -EINVAL;
324 
325 	spin_lock_irqsave(&trie->lock, irq_flags);
326 
327 	/* Allocate and fill a new node */
328 
329 	if (trie->n_entries == trie->map.max_entries) {
330 		ret = -ENOSPC;
331 		goto out;
332 	}
333 
334 	new_node = lpm_trie_node_alloc(trie, value);
335 	if (!new_node) {
336 		ret = -ENOMEM;
337 		goto out;
338 	}
339 
340 	trie->n_entries++;
341 
342 	new_node->prefixlen = key->prefixlen;
343 	RCU_INIT_POINTER(new_node->child[0], NULL);
344 	RCU_INIT_POINTER(new_node->child[1], NULL);
345 	memcpy(new_node->data, key->data, trie->data_size);
346 
347 	/* Now find a slot to attach the new node. To do that, walk the tree
348 	 * from the root and match as many bits as possible for each node until
349 	 * we either find an empty slot or a slot that needs to be replaced by
350 	 * an intermediate node.
351 	 */
352 	slot = &trie->root;
353 
354 	while ((node = rcu_dereference_protected(*slot,
355 					lockdep_is_held(&trie->lock)))) {
356 		matchlen = longest_prefix_match(trie, node, key);
357 
358 		if (node->prefixlen != matchlen ||
359 		    node->prefixlen == key->prefixlen ||
360 		    node->prefixlen == trie->max_prefixlen)
361 			break;
362 
363 		next_bit = extract_bit(key->data, node->prefixlen);
364 		slot = &node->child[next_bit];
365 	}
366 
367 	/* If the slot is empty (a free child pointer or an empty root),
368 	 * simply assign the @new_node to that slot and be done.
369 	 */
370 	if (!node) {
371 		rcu_assign_pointer(*slot, new_node);
372 		goto out;
373 	}
374 
375 	/* If the slot we picked already exists, replace it with @new_node
376 	 * which already has the correct data array set.
377 	 */
378 	if (node->prefixlen == matchlen) {
379 		new_node->child[0] = node->child[0];
380 		new_node->child[1] = node->child[1];
381 
382 		if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
383 			trie->n_entries--;
384 
385 		rcu_assign_pointer(*slot, new_node);
386 		free_node = node;
387 
388 		goto out;
389 	}
390 
391 	/* If the new node matches the prefix completely, it must be inserted
392 	 * as an ancestor. Simply insert it between @node and *@slot.
393 	 */
394 	if (matchlen == key->prefixlen) {
395 		next_bit = extract_bit(node->data, matchlen);
396 		rcu_assign_pointer(new_node->child[next_bit], node);
397 		rcu_assign_pointer(*slot, new_node);
398 		goto out;
399 	}
400 
401 	im_node = lpm_trie_node_alloc(trie, NULL);
402 	if (!im_node) {
403 		ret = -ENOMEM;
404 		goto out;
405 	}
406 
407 	im_node->prefixlen = matchlen;
408 	im_node->flags |= LPM_TREE_NODE_FLAG_IM;
409 	memcpy(im_node->data, node->data, trie->data_size);
410 
411 	/* Now determine which child to install in which slot */
412 	if (extract_bit(key->data, matchlen)) {
413 		rcu_assign_pointer(im_node->child[0], node);
414 		rcu_assign_pointer(im_node->child[1], new_node);
415 	} else {
416 		rcu_assign_pointer(im_node->child[0], new_node);
417 		rcu_assign_pointer(im_node->child[1], node);
418 	}
419 
420 	/* Finally, assign the intermediate node to the determined slot */
421 	rcu_assign_pointer(*slot, im_node);
422 
423 out:
424 	if (ret) {
425 		if (new_node)
426 			trie->n_entries--;
427 
428 		kfree(new_node);
429 		kfree(im_node);
430 	}
431 
432 	spin_unlock_irqrestore(&trie->lock, irq_flags);
433 	kfree_rcu(free_node, rcu);
434 
435 	return ret;
436 }
437 
438 /* Called from syscall or from eBPF program */
trie_delete_elem(struct bpf_map * map,void * _key)439 static long trie_delete_elem(struct bpf_map *map, void *_key)
440 {
441 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
442 	struct lpm_trie_node *free_node = NULL, *free_parent = NULL;
443 	struct bpf_lpm_trie_key_u8 *key = _key;
444 	struct lpm_trie_node __rcu **trim, **trim2;
445 	struct lpm_trie_node *node, *parent;
446 	unsigned long irq_flags;
447 	unsigned int next_bit;
448 	size_t matchlen = 0;
449 	int ret = 0;
450 
451 	if (key->prefixlen > trie->max_prefixlen)
452 		return -EINVAL;
453 
454 	spin_lock_irqsave(&trie->lock, irq_flags);
455 
456 	/* Walk the tree looking for an exact key/length match and keeping
457 	 * track of the path we traverse.  We will need to know the node
458 	 * we wish to delete, and the slot that points to the node we want
459 	 * to delete.  We may also need to know the nodes parent and the
460 	 * slot that contains it.
461 	 */
462 	trim = &trie->root;
463 	trim2 = trim;
464 	parent = NULL;
465 	while ((node = rcu_dereference_protected(
466 		       *trim, lockdep_is_held(&trie->lock)))) {
467 		matchlen = longest_prefix_match(trie, node, key);
468 
469 		if (node->prefixlen != matchlen ||
470 		    node->prefixlen == key->prefixlen)
471 			break;
472 
473 		parent = node;
474 		trim2 = trim;
475 		next_bit = extract_bit(key->data, node->prefixlen);
476 		trim = &node->child[next_bit];
477 	}
478 
479 	if (!node || node->prefixlen != key->prefixlen ||
480 	    node->prefixlen != matchlen ||
481 	    (node->flags & LPM_TREE_NODE_FLAG_IM)) {
482 		ret = -ENOENT;
483 		goto out;
484 	}
485 
486 	trie->n_entries--;
487 
488 	/* If the node we are removing has two children, simply mark it
489 	 * as intermediate and we are done.
490 	 */
491 	if (rcu_access_pointer(node->child[0]) &&
492 	    rcu_access_pointer(node->child[1])) {
493 		node->flags |= LPM_TREE_NODE_FLAG_IM;
494 		goto out;
495 	}
496 
497 	/* If the parent of the node we are about to delete is an intermediate
498 	 * node, and the deleted node doesn't have any children, we can delete
499 	 * the intermediate parent as well and promote its other child
500 	 * up the tree.  Doing this maintains the invariant that all
501 	 * intermediate nodes have exactly 2 children and that there are no
502 	 * unnecessary intermediate nodes in the tree.
503 	 */
504 	if (parent && (parent->flags & LPM_TREE_NODE_FLAG_IM) &&
505 	    !node->child[0] && !node->child[1]) {
506 		if (node == rcu_access_pointer(parent->child[0]))
507 			rcu_assign_pointer(
508 				*trim2, rcu_access_pointer(parent->child[1]));
509 		else
510 			rcu_assign_pointer(
511 				*trim2, rcu_access_pointer(parent->child[0]));
512 		free_parent = parent;
513 		free_node = node;
514 		goto out;
515 	}
516 
517 	/* The node we are removing has either zero or one child. If there
518 	 * is a child, move it into the removed node's slot then delete
519 	 * the node.  Otherwise just clear the slot and delete the node.
520 	 */
521 	if (node->child[0])
522 		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[0]));
523 	else if (node->child[1])
524 		rcu_assign_pointer(*trim, rcu_access_pointer(node->child[1]));
525 	else
526 		RCU_INIT_POINTER(*trim, NULL);
527 	free_node = node;
528 
529 out:
530 	spin_unlock_irqrestore(&trie->lock, irq_flags);
531 	kfree_rcu(free_parent, rcu);
532 	kfree_rcu(free_node, rcu);
533 
534 	return ret;
535 }
536 
537 #define LPM_DATA_SIZE_MAX	256
538 #define LPM_DATA_SIZE_MIN	1
539 
540 #define LPM_VAL_SIZE_MAX	(KMALLOC_MAX_SIZE - LPM_DATA_SIZE_MAX - \
541 				 sizeof(struct lpm_trie_node))
542 #define LPM_VAL_SIZE_MIN	1
543 
544 #define LPM_KEY_SIZE(X)		(sizeof(struct bpf_lpm_trie_key_u8) + (X))
545 #define LPM_KEY_SIZE_MAX	LPM_KEY_SIZE(LPM_DATA_SIZE_MAX)
546 #define LPM_KEY_SIZE_MIN	LPM_KEY_SIZE(LPM_DATA_SIZE_MIN)
547 
548 #define LPM_CREATE_FLAG_MASK	(BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE |	\
549 				 BPF_F_ACCESS_MASK)
550 
trie_alloc(union bpf_attr * attr)551 static struct bpf_map *trie_alloc(union bpf_attr *attr)
552 {
553 	struct lpm_trie *trie;
554 
555 	/* check sanity of attributes */
556 	if (attr->max_entries == 0 ||
557 	    !(attr->map_flags & BPF_F_NO_PREALLOC) ||
558 	    attr->map_flags & ~LPM_CREATE_FLAG_MASK ||
559 	    !bpf_map_flags_access_ok(attr->map_flags) ||
560 	    attr->key_size < LPM_KEY_SIZE_MIN ||
561 	    attr->key_size > LPM_KEY_SIZE_MAX ||
562 	    attr->value_size < LPM_VAL_SIZE_MIN ||
563 	    attr->value_size > LPM_VAL_SIZE_MAX)
564 		return ERR_PTR(-EINVAL);
565 
566 	trie = bpf_map_area_alloc(sizeof(*trie), NUMA_NO_NODE);
567 	if (!trie)
568 		return ERR_PTR(-ENOMEM);
569 
570 	/* copy mandatory map attributes */
571 	bpf_map_init_from_attr(&trie->map, attr);
572 	trie->data_size = attr->key_size -
573 			  offsetof(struct bpf_lpm_trie_key_u8, data);
574 	trie->max_prefixlen = trie->data_size * 8;
575 
576 	spin_lock_init(&trie->lock);
577 
578 	return &trie->map;
579 }
580 
trie_free(struct bpf_map * map)581 static void trie_free(struct bpf_map *map)
582 {
583 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
584 	struct lpm_trie_node __rcu **slot;
585 	struct lpm_trie_node *node;
586 
587 	/* Always start at the root and walk down to a node that has no
588 	 * children. Then free that node, nullify its reference in the parent
589 	 * and start over.
590 	 */
591 
592 	for (;;) {
593 		slot = &trie->root;
594 
595 		for (;;) {
596 			node = rcu_dereference_protected(*slot, 1);
597 			if (!node)
598 				goto out;
599 
600 			if (rcu_access_pointer(node->child[0])) {
601 				slot = &node->child[0];
602 				continue;
603 			}
604 
605 			if (rcu_access_pointer(node->child[1])) {
606 				slot = &node->child[1];
607 				continue;
608 			}
609 
610 			kfree(node);
611 			RCU_INIT_POINTER(*slot, NULL);
612 			break;
613 		}
614 	}
615 
616 out:
617 	bpf_map_area_free(trie);
618 }
619 
trie_get_next_key(struct bpf_map * map,void * _key,void * _next_key)620 static int trie_get_next_key(struct bpf_map *map, void *_key, void *_next_key)
621 {
622 	struct lpm_trie_node *node, *next_node = NULL, *parent, *search_root;
623 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
624 	struct bpf_lpm_trie_key_u8 *key = _key, *next_key = _next_key;
625 	struct lpm_trie_node **node_stack = NULL;
626 	int err = 0, stack_ptr = -1;
627 	unsigned int next_bit;
628 	size_t matchlen;
629 
630 	/* The get_next_key follows postorder. For the 4 node example in
631 	 * the top of this file, the trie_get_next_key() returns the following
632 	 * one after another:
633 	 *   192.168.0.0/24
634 	 *   192.168.1.0/24
635 	 *   192.168.128.0/24
636 	 *   192.168.0.0/16
637 	 *
638 	 * The idea is to return more specific keys before less specific ones.
639 	 */
640 
641 	/* Empty trie */
642 	search_root = rcu_dereference(trie->root);
643 	if (!search_root)
644 		return -ENOENT;
645 
646 	/* For invalid key, find the leftmost node in the trie */
647 	if (!key || key->prefixlen > trie->max_prefixlen)
648 		goto find_leftmost;
649 
650 	node_stack = kmalloc_array(trie->max_prefixlen,
651 				   sizeof(struct lpm_trie_node *),
652 				   GFP_ATOMIC | __GFP_NOWARN);
653 	if (!node_stack)
654 		return -ENOMEM;
655 
656 	/* Try to find the exact node for the given key */
657 	for (node = search_root; node;) {
658 		node_stack[++stack_ptr] = node;
659 		matchlen = longest_prefix_match(trie, node, key);
660 		if (node->prefixlen != matchlen ||
661 		    node->prefixlen == key->prefixlen)
662 			break;
663 
664 		next_bit = extract_bit(key->data, node->prefixlen);
665 		node = rcu_dereference(node->child[next_bit]);
666 	}
667 	if (!node || node->prefixlen != key->prefixlen ||
668 	    (node->flags & LPM_TREE_NODE_FLAG_IM))
669 		goto find_leftmost;
670 
671 	/* The node with the exactly-matching key has been found,
672 	 * find the first node in postorder after the matched node.
673 	 */
674 	node = node_stack[stack_ptr];
675 	while (stack_ptr > 0) {
676 		parent = node_stack[stack_ptr - 1];
677 		if (rcu_dereference(parent->child[0]) == node) {
678 			search_root = rcu_dereference(parent->child[1]);
679 			if (search_root)
680 				goto find_leftmost;
681 		}
682 		if (!(parent->flags & LPM_TREE_NODE_FLAG_IM)) {
683 			next_node = parent;
684 			goto do_copy;
685 		}
686 
687 		node = parent;
688 		stack_ptr--;
689 	}
690 
691 	/* did not find anything */
692 	err = -ENOENT;
693 	goto free_stack;
694 
695 find_leftmost:
696 	/* Find the leftmost non-intermediate node, all intermediate nodes
697 	 * have exact two children, so this function will never return NULL.
698 	 */
699 	for (node = search_root; node;) {
700 		if (node->flags & LPM_TREE_NODE_FLAG_IM) {
701 			node = rcu_dereference(node->child[0]);
702 		} else {
703 			next_node = node;
704 			node = rcu_dereference(node->child[0]);
705 			if (!node)
706 				node = rcu_dereference(next_node->child[1]);
707 		}
708 	}
709 do_copy:
710 	next_key->prefixlen = next_node->prefixlen;
711 	memcpy((void *)next_key + offsetof(struct bpf_lpm_trie_key_u8, data),
712 	       next_node->data, trie->data_size);
713 free_stack:
714 	kfree(node_stack);
715 	return err;
716 }
717 
trie_check_btf(const struct bpf_map * map,const struct btf * btf,const struct btf_type * key_type,const struct btf_type * value_type)718 static int trie_check_btf(const struct bpf_map *map,
719 			  const struct btf *btf,
720 			  const struct btf_type *key_type,
721 			  const struct btf_type *value_type)
722 {
723 	/* Keys must have struct bpf_lpm_trie_key_u8 embedded. */
724 	return BTF_INFO_KIND(key_type->info) != BTF_KIND_STRUCT ?
725 	       -EINVAL : 0;
726 }
727 
trie_mem_usage(const struct bpf_map * map)728 static u64 trie_mem_usage(const struct bpf_map *map)
729 {
730 	struct lpm_trie *trie = container_of(map, struct lpm_trie, map);
731 	u64 elem_size;
732 
733 	elem_size = sizeof(struct lpm_trie_node) + trie->data_size +
734 			    trie->map.value_size;
735 	return elem_size * READ_ONCE(trie->n_entries);
736 }
737 
738 BTF_ID_LIST_SINGLE(trie_map_btf_ids, struct, lpm_trie)
739 const struct bpf_map_ops trie_map_ops = {
740 	.map_meta_equal = bpf_map_meta_equal,
741 	.map_alloc = trie_alloc,
742 	.map_free = trie_free,
743 	.map_get_next_key = trie_get_next_key,
744 	.map_lookup_elem = trie_lookup_elem,
745 	.map_update_elem = trie_update_elem,
746 	.map_delete_elem = trie_delete_elem,
747 	.map_lookup_batch = generic_map_lookup_batch,
748 	.map_update_batch = generic_map_update_batch,
749 	.map_delete_batch = generic_map_delete_batch,
750 	.map_check_btf = trie_check_btf,
751 	.map_mem_usage = trie_mem_usage,
752 	.map_btf_id = &trie_map_btf_ids[0],
753 };
754