xref: /linux-6.15/kernel/bpf/devmap.c (revision d839a731)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Covalent IO, Inc. http://covalent.io
3  */
4 
5 /* Devmaps primary use is as a backend map for XDP BPF helper call
6  * bpf_redirect_map(). Because XDP is mostly concerned with performance we
7  * spent some effort to ensure the datapath with redirect maps does not use
8  * any locking. This is a quick note on the details.
9  *
10  * We have three possible paths to get into the devmap control plane bpf
11  * syscalls, bpf programs, and driver side xmit/flush operations. A bpf syscall
12  * will invoke an update, delete, or lookup operation. To ensure updates and
13  * deletes appear atomic from the datapath side xchg() is used to modify the
14  * netdev_map array. Then because the datapath does a lookup into the netdev_map
15  * array (read-only) from an RCU critical section we use call_rcu() to wait for
16  * an rcu grace period before free'ing the old data structures. This ensures the
17  * datapath always has a valid copy. However, the datapath does a "flush"
18  * operation that pushes any pending packets in the driver outside the RCU
19  * critical section. Each bpf_dtab_netdev tracks these pending operations using
20  * a per-cpu flush list. The bpf_dtab_netdev object will not be destroyed  until
21  * this list is empty, indicating outstanding flush operations have completed.
22  *
23  * BPF syscalls may race with BPF program calls on any of the update, delete
24  * or lookup operations. As noted above the xchg() operation also keep the
25  * netdev_map consistent in this case. From the devmap side BPF programs
26  * calling into these operations are the same as multiple user space threads
27  * making system calls.
28  *
29  * Finally, any of the above may race with a netdev_unregister notifier. The
30  * unregister notifier must search for net devices in the map structure that
31  * contain a reference to the net device and remove them. This is a two step
32  * process (a) dereference the bpf_dtab_netdev object in netdev_map and (b)
33  * check to see if the ifindex is the same as the net_device being removed.
34  * When removing the dev a cmpxchg() is used to ensure the correct dev is
35  * removed, in the case of a concurrent update or delete operation it is
36  * possible that the initially referenced dev is no longer in the map. As the
37  * notifier hook walks the map we know that new dev references can not be
38  * added by the user because core infrastructure ensures dev_get_by_index()
39  * calls will fail at this point.
40  *
41  * The devmap_hash type is a map type which interprets keys as ifindexes and
42  * indexes these using a hashmap. This allows maps that use ifindex as key to be
43  * densely packed instead of having holes in the lookup array for unused
44  * ifindexes. The setup and packet enqueue/send code is shared between the two
45  * types of devmap; only the lookup and insertion is different.
46  */
47 #include <linux/bpf.h>
48 #include <net/xdp.h>
49 #include <linux/filter.h>
50 #include <trace/events/xdp.h>
51 #include <linux/btf_ids.h>
52 
53 #define DEV_CREATE_FLAG_MASK \
54 	(BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)
55 
56 struct xdp_dev_bulk_queue {
57 	struct xdp_frame *q[DEV_MAP_BULK_SIZE];
58 	struct list_head flush_node;
59 	struct net_device *dev;
60 	struct net_device *dev_rx;
61 	struct bpf_prog *xdp_prog;
62 	unsigned int count;
63 };
64 
65 struct bpf_dtab_netdev {
66 	struct net_device *dev; /* must be first member, due to tracepoint */
67 	struct hlist_node index_hlist;
68 	struct bpf_prog *xdp_prog;
69 	struct rcu_head rcu;
70 	unsigned int idx;
71 	struct bpf_devmap_val val;
72 };
73 
74 struct bpf_dtab {
75 	struct bpf_map map;
76 	struct bpf_dtab_netdev __rcu **netdev_map; /* DEVMAP type only */
77 	struct list_head list;
78 
79 	/* these are only used for DEVMAP_HASH type maps */
80 	struct hlist_head *dev_index_head;
81 	spinlock_t index_lock;
82 	unsigned int items;
83 	u32 n_buckets;
84 };
85 
86 static DEFINE_SPINLOCK(dev_map_lock);
87 static LIST_HEAD(dev_map_list);
88 
89 static struct hlist_head *dev_map_create_hash(unsigned int entries,
90 					      int numa_node)
91 {
92 	int i;
93 	struct hlist_head *hash;
94 
95 	hash = bpf_map_area_alloc((u64) entries * sizeof(*hash), numa_node);
96 	if (hash != NULL)
97 		for (i = 0; i < entries; i++)
98 			INIT_HLIST_HEAD(&hash[i]);
99 
100 	return hash;
101 }
102 
103 static inline struct hlist_head *dev_map_index_hash(struct bpf_dtab *dtab,
104 						    int idx)
105 {
106 	return &dtab->dev_index_head[idx & (dtab->n_buckets - 1)];
107 }
108 
109 static int dev_map_init_map(struct bpf_dtab *dtab, union bpf_attr *attr)
110 {
111 	u32 valsize = attr->value_size;
112 
113 	/* check sanity of attributes. 2 value sizes supported:
114 	 * 4 bytes: ifindex
115 	 * 8 bytes: ifindex + prog fd
116 	 */
117 	if (attr->max_entries == 0 || attr->key_size != 4 ||
118 	    (valsize != offsetofend(struct bpf_devmap_val, ifindex) &&
119 	     valsize != offsetofend(struct bpf_devmap_val, bpf_prog.fd)) ||
120 	    attr->map_flags & ~DEV_CREATE_FLAG_MASK)
121 		return -EINVAL;
122 
123 	/* Lookup returns a pointer straight to dev->ifindex, so make sure the
124 	 * verifier prevents writes from the BPF side
125 	 */
126 	attr->map_flags |= BPF_F_RDONLY_PROG;
127 
128 
129 	bpf_map_init_from_attr(&dtab->map, attr);
130 
131 	if (attr->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
132 		/* hash table size must be power of 2; roundup_pow_of_two() can
133 		 * overflow into UB on 32-bit arches, so check that first
134 		 */
135 		if (dtab->map.max_entries > 1UL << 31)
136 			return -EINVAL;
137 
138 		dtab->n_buckets = roundup_pow_of_two(dtab->map.max_entries);
139 
140 		dtab->dev_index_head = dev_map_create_hash(dtab->n_buckets,
141 							   dtab->map.numa_node);
142 		if (!dtab->dev_index_head)
143 			return -ENOMEM;
144 
145 		spin_lock_init(&dtab->index_lock);
146 	} else {
147 		dtab->netdev_map = bpf_map_area_alloc((u64) dtab->map.max_entries *
148 						      sizeof(struct bpf_dtab_netdev *),
149 						      dtab->map.numa_node);
150 		if (!dtab->netdev_map)
151 			return -ENOMEM;
152 	}
153 
154 	return 0;
155 }
156 
157 static struct bpf_map *dev_map_alloc(union bpf_attr *attr)
158 {
159 	struct bpf_dtab *dtab;
160 	int err;
161 
162 	dtab = bpf_map_area_alloc(sizeof(*dtab), NUMA_NO_NODE);
163 	if (!dtab)
164 		return ERR_PTR(-ENOMEM);
165 
166 	err = dev_map_init_map(dtab, attr);
167 	if (err) {
168 		bpf_map_area_free(dtab);
169 		return ERR_PTR(err);
170 	}
171 
172 	spin_lock(&dev_map_lock);
173 	list_add_tail_rcu(&dtab->list, &dev_map_list);
174 	spin_unlock(&dev_map_lock);
175 
176 	return &dtab->map;
177 }
178 
179 static void dev_map_free(struct bpf_map *map)
180 {
181 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
182 	int i;
183 
184 	/* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
185 	 * so the programs (can be more than one that used this map) were
186 	 * disconnected from events. The following synchronize_rcu() guarantees
187 	 * both rcu read critical sections complete and waits for
188 	 * preempt-disable regions (NAPI being the relevant context here) so we
189 	 * are certain there will be no further reads against the netdev_map and
190 	 * all flush operations are complete. Flush operations can only be done
191 	 * from NAPI context for this reason.
192 	 */
193 
194 	spin_lock(&dev_map_lock);
195 	list_del_rcu(&dtab->list);
196 	spin_unlock(&dev_map_lock);
197 
198 	/* bpf_redirect_info->map is assigned in __bpf_xdp_redirect_map()
199 	 * during NAPI callback and cleared after the XDP redirect. There is no
200 	 * explicit RCU read section which protects bpf_redirect_info->map but
201 	 * local_bh_disable() also marks the beginning an RCU section. This
202 	 * makes the complete softirq callback RCU protected. Thus after
203 	 * following synchronize_rcu() there no bpf_redirect_info->map == map
204 	 * assignment.
205 	 */
206 	synchronize_rcu();
207 
208 	/* Make sure prior __dev_map_entry_free() have completed. */
209 	rcu_barrier();
210 
211 	if (dtab->map.map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
212 		for (i = 0; i < dtab->n_buckets; i++) {
213 			struct bpf_dtab_netdev *dev;
214 			struct hlist_head *head;
215 			struct hlist_node *next;
216 
217 			head = dev_map_index_hash(dtab, i);
218 
219 			hlist_for_each_entry_safe(dev, next, head, index_hlist) {
220 				hlist_del_rcu(&dev->index_hlist);
221 				if (dev->xdp_prog)
222 					bpf_prog_put(dev->xdp_prog);
223 				dev_put(dev->dev);
224 				kfree(dev);
225 			}
226 		}
227 
228 		bpf_map_area_free(dtab->dev_index_head);
229 	} else {
230 		for (i = 0; i < dtab->map.max_entries; i++) {
231 			struct bpf_dtab_netdev *dev;
232 
233 			dev = rcu_dereference_raw(dtab->netdev_map[i]);
234 			if (!dev)
235 				continue;
236 
237 			if (dev->xdp_prog)
238 				bpf_prog_put(dev->xdp_prog);
239 			dev_put(dev->dev);
240 			kfree(dev);
241 		}
242 
243 		bpf_map_area_free(dtab->netdev_map);
244 	}
245 
246 	bpf_map_area_free(dtab);
247 }
248 
249 static int dev_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
250 {
251 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
252 	u32 index = key ? *(u32 *)key : U32_MAX;
253 	u32 *next = next_key;
254 
255 	if (index >= dtab->map.max_entries) {
256 		*next = 0;
257 		return 0;
258 	}
259 
260 	if (index == dtab->map.max_entries - 1)
261 		return -ENOENT;
262 	*next = index + 1;
263 	return 0;
264 }
265 
266 /* Elements are kept alive by RCU; either by rcu_read_lock() (from syscall) or
267  * by local_bh_disable() (from XDP calls inside NAPI). The
268  * rcu_read_lock_bh_held() below makes lockdep accept both.
269  */
270 static void *__dev_map_hash_lookup_elem(struct bpf_map *map, u32 key)
271 {
272 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
273 	struct hlist_head *head = dev_map_index_hash(dtab, key);
274 	struct bpf_dtab_netdev *dev;
275 
276 	hlist_for_each_entry_rcu(dev, head, index_hlist,
277 				 lockdep_is_held(&dtab->index_lock))
278 		if (dev->idx == key)
279 			return dev;
280 
281 	return NULL;
282 }
283 
284 static int dev_map_hash_get_next_key(struct bpf_map *map, void *key,
285 				    void *next_key)
286 {
287 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
288 	u32 idx, *next = next_key;
289 	struct bpf_dtab_netdev *dev, *next_dev;
290 	struct hlist_head *head;
291 	int i = 0;
292 
293 	if (!key)
294 		goto find_first;
295 
296 	idx = *(u32 *)key;
297 
298 	dev = __dev_map_hash_lookup_elem(map, idx);
299 	if (!dev)
300 		goto find_first;
301 
302 	next_dev = hlist_entry_safe(rcu_dereference_raw(hlist_next_rcu(&dev->index_hlist)),
303 				    struct bpf_dtab_netdev, index_hlist);
304 
305 	if (next_dev) {
306 		*next = next_dev->idx;
307 		return 0;
308 	}
309 
310 	i = idx & (dtab->n_buckets - 1);
311 	i++;
312 
313  find_first:
314 	for (; i < dtab->n_buckets; i++) {
315 		head = dev_map_index_hash(dtab, i);
316 
317 		next_dev = hlist_entry_safe(rcu_dereference_raw(hlist_first_rcu(head)),
318 					    struct bpf_dtab_netdev,
319 					    index_hlist);
320 		if (next_dev) {
321 			*next = next_dev->idx;
322 			return 0;
323 		}
324 	}
325 
326 	return -ENOENT;
327 }
328 
329 static int dev_map_bpf_prog_run(struct bpf_prog *xdp_prog,
330 				struct xdp_frame **frames, int n,
331 				struct net_device *dev)
332 {
333 	struct xdp_txq_info txq = { .dev = dev };
334 	struct xdp_buff xdp;
335 	int i, nframes = 0;
336 
337 	for (i = 0; i < n; i++) {
338 		struct xdp_frame *xdpf = frames[i];
339 		u32 act;
340 		int err;
341 
342 		xdp_convert_frame_to_buff(xdpf, &xdp);
343 		xdp.txq = &txq;
344 
345 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
346 		switch (act) {
347 		case XDP_PASS:
348 			err = xdp_update_frame_from_buff(&xdp, xdpf);
349 			if (unlikely(err < 0))
350 				xdp_return_frame_rx_napi(xdpf);
351 			else
352 				frames[nframes++] = xdpf;
353 			break;
354 		default:
355 			bpf_warn_invalid_xdp_action(NULL, xdp_prog, act);
356 			fallthrough;
357 		case XDP_ABORTED:
358 			trace_xdp_exception(dev, xdp_prog, act);
359 			fallthrough;
360 		case XDP_DROP:
361 			xdp_return_frame_rx_napi(xdpf);
362 			break;
363 		}
364 	}
365 	return nframes; /* sent frames count */
366 }
367 
368 static void bq_xmit_all(struct xdp_dev_bulk_queue *bq, u32 flags)
369 {
370 	struct net_device *dev = bq->dev;
371 	unsigned int cnt = bq->count;
372 	int sent = 0, err = 0;
373 	int to_send = cnt;
374 	int i;
375 
376 	if (unlikely(!cnt))
377 		return;
378 
379 	for (i = 0; i < cnt; i++) {
380 		struct xdp_frame *xdpf = bq->q[i];
381 
382 		prefetch(xdpf);
383 	}
384 
385 	if (bq->xdp_prog) {
386 		to_send = dev_map_bpf_prog_run(bq->xdp_prog, bq->q, cnt, dev);
387 		if (!to_send)
388 			goto out;
389 	}
390 
391 	sent = dev->netdev_ops->ndo_xdp_xmit(dev, to_send, bq->q, flags);
392 	if (sent < 0) {
393 		/* If ndo_xdp_xmit fails with an errno, no frames have
394 		 * been xmit'ed.
395 		 */
396 		err = sent;
397 		sent = 0;
398 	}
399 
400 	/* If not all frames have been transmitted, it is our
401 	 * responsibility to free them
402 	 */
403 	for (i = sent; unlikely(i < to_send); i++)
404 		xdp_return_frame_rx_napi(bq->q[i]);
405 
406 out:
407 	bq->count = 0;
408 	trace_xdp_devmap_xmit(bq->dev_rx, dev, sent, cnt - sent, err);
409 }
410 
411 /* __dev_flush is called from xdp_do_flush() which _must_ be signalled from the
412  * driver before returning from its napi->poll() routine. See the comment above
413  * xdp_do_flush() in filter.c.
414  */
415 void __dev_flush(struct list_head *flush_list)
416 {
417 	struct xdp_dev_bulk_queue *bq, *tmp;
418 
419 	list_for_each_entry_safe(bq, tmp, flush_list, flush_node) {
420 		bq_xmit_all(bq, XDP_XMIT_FLUSH);
421 		bq->dev_rx = NULL;
422 		bq->xdp_prog = NULL;
423 		__list_del_clearprev(&bq->flush_node);
424 	}
425 }
426 
427 /* Elements are kept alive by RCU; either by rcu_read_lock() (from syscall) or
428  * by local_bh_disable() (from XDP calls inside NAPI). The
429  * rcu_read_lock_bh_held() below makes lockdep accept both.
430  */
431 static void *__dev_map_lookup_elem(struct bpf_map *map, u32 key)
432 {
433 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
434 	struct bpf_dtab_netdev *obj;
435 
436 	if (key >= map->max_entries)
437 		return NULL;
438 
439 	obj = rcu_dereference_check(dtab->netdev_map[key],
440 				    rcu_read_lock_bh_held());
441 	return obj;
442 }
443 
444 /* Runs in NAPI, i.e., softirq under local_bh_disable(). Thus, safe percpu
445  * variable access, and map elements stick around. See comment above
446  * xdp_do_flush() in filter.c.
447  */
448 static void bq_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
449 		       struct net_device *dev_rx, struct bpf_prog *xdp_prog)
450 {
451 	struct list_head *flush_list = bpf_net_ctx_get_dev_flush_list();
452 	struct xdp_dev_bulk_queue *bq = this_cpu_ptr(dev->xdp_bulkq);
453 
454 	if (unlikely(bq->count == DEV_MAP_BULK_SIZE))
455 		bq_xmit_all(bq, 0);
456 
457 	/* Ingress dev_rx will be the same for all xdp_frame's in
458 	 * bulk_queue, because bq stored per-CPU and must be flushed
459 	 * from net_device drivers NAPI func end.
460 	 *
461 	 * Do the same with xdp_prog and flush_list since these fields
462 	 * are only ever modified together.
463 	 */
464 	if (!bq->dev_rx) {
465 		bq->dev_rx = dev_rx;
466 		bq->xdp_prog = xdp_prog;
467 		list_add(&bq->flush_node, flush_list);
468 	}
469 
470 	bq->q[bq->count++] = xdpf;
471 }
472 
473 static inline int __xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
474 				struct net_device *dev_rx,
475 				struct bpf_prog *xdp_prog)
476 {
477 	int err;
478 
479 	if (!(dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT))
480 		return -EOPNOTSUPP;
481 
482 	if (unlikely(!(dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT_SG) &&
483 		     xdp_frame_has_frags(xdpf)))
484 		return -EOPNOTSUPP;
485 
486 	err = xdp_ok_fwd_dev(dev, xdp_get_frame_len(xdpf));
487 	if (unlikely(err))
488 		return err;
489 
490 	bq_enqueue(dev, xdpf, dev_rx, xdp_prog);
491 	return 0;
492 }
493 
494 static u32 dev_map_bpf_prog_run_skb(struct sk_buff *skb, struct bpf_dtab_netdev *dst)
495 {
496 	struct xdp_txq_info txq = { .dev = dst->dev };
497 	struct xdp_buff xdp;
498 	u32 act;
499 
500 	if (!dst->xdp_prog)
501 		return XDP_PASS;
502 
503 	__skb_pull(skb, skb->mac_len);
504 	xdp.txq = &txq;
505 
506 	act = bpf_prog_run_generic_xdp(skb, &xdp, dst->xdp_prog);
507 	switch (act) {
508 	case XDP_PASS:
509 		__skb_push(skb, skb->mac_len);
510 		break;
511 	default:
512 		bpf_warn_invalid_xdp_action(NULL, dst->xdp_prog, act);
513 		fallthrough;
514 	case XDP_ABORTED:
515 		trace_xdp_exception(dst->dev, dst->xdp_prog, act);
516 		fallthrough;
517 	case XDP_DROP:
518 		kfree_skb(skb);
519 		break;
520 	}
521 
522 	return act;
523 }
524 
525 int dev_xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
526 		    struct net_device *dev_rx)
527 {
528 	return __xdp_enqueue(dev, xdpf, dev_rx, NULL);
529 }
530 
531 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_frame *xdpf,
532 		    struct net_device *dev_rx)
533 {
534 	struct net_device *dev = dst->dev;
535 
536 	return __xdp_enqueue(dev, xdpf, dev_rx, dst->xdp_prog);
537 }
538 
539 static bool is_valid_dst(struct bpf_dtab_netdev *obj, struct xdp_frame *xdpf)
540 {
541 	if (!obj)
542 		return false;
543 
544 	if (!(obj->dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT))
545 		return false;
546 
547 	if (unlikely(!(obj->dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT_SG) &&
548 		     xdp_frame_has_frags(xdpf)))
549 		return false;
550 
551 	if (xdp_ok_fwd_dev(obj->dev, xdp_get_frame_len(xdpf)))
552 		return false;
553 
554 	return true;
555 }
556 
557 static int dev_map_enqueue_clone(struct bpf_dtab_netdev *obj,
558 				 struct net_device *dev_rx,
559 				 struct xdp_frame *xdpf)
560 {
561 	struct xdp_frame *nxdpf;
562 
563 	nxdpf = xdpf_clone(xdpf);
564 	if (!nxdpf)
565 		return -ENOMEM;
566 
567 	bq_enqueue(obj->dev, nxdpf, dev_rx, obj->xdp_prog);
568 
569 	return 0;
570 }
571 
572 static inline bool is_ifindex_excluded(int *excluded, int num_excluded, int ifindex)
573 {
574 	while (num_excluded--) {
575 		if (ifindex == excluded[num_excluded])
576 			return true;
577 	}
578 	return false;
579 }
580 
581 /* Get ifindex of each upper device. 'indexes' must be able to hold at
582  * least MAX_NEST_DEV elements.
583  * Returns the number of ifindexes added.
584  */
585 static int get_upper_ifindexes(struct net_device *dev, int *indexes)
586 {
587 	struct net_device *upper;
588 	struct list_head *iter;
589 	int n = 0;
590 
591 	netdev_for_each_upper_dev_rcu(dev, upper, iter) {
592 		indexes[n++] = upper->ifindex;
593 	}
594 	return n;
595 }
596 
597 int dev_map_enqueue_multi(struct xdp_frame *xdpf, struct net_device *dev_rx,
598 			  struct bpf_map *map, bool exclude_ingress)
599 {
600 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
601 	struct bpf_dtab_netdev *dst, *last_dst = NULL;
602 	int excluded_devices[1+MAX_NEST_DEV];
603 	struct hlist_head *head;
604 	int num_excluded = 0;
605 	unsigned int i;
606 	int err;
607 
608 	if (exclude_ingress) {
609 		num_excluded = get_upper_ifindexes(dev_rx, excluded_devices);
610 		excluded_devices[num_excluded++] = dev_rx->ifindex;
611 	}
612 
613 	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
614 		for (i = 0; i < map->max_entries; i++) {
615 			dst = rcu_dereference_check(dtab->netdev_map[i],
616 						    rcu_read_lock_bh_held());
617 			if (!is_valid_dst(dst, xdpf))
618 				continue;
619 
620 			if (is_ifindex_excluded(excluded_devices, num_excluded, dst->dev->ifindex))
621 				continue;
622 
623 			/* we only need n-1 clones; last_dst enqueued below */
624 			if (!last_dst) {
625 				last_dst = dst;
626 				continue;
627 			}
628 
629 			err = dev_map_enqueue_clone(last_dst, dev_rx, xdpf);
630 			if (err)
631 				return err;
632 
633 			last_dst = dst;
634 		}
635 	} else { /* BPF_MAP_TYPE_DEVMAP_HASH */
636 		for (i = 0; i < dtab->n_buckets; i++) {
637 			head = dev_map_index_hash(dtab, i);
638 			hlist_for_each_entry_rcu(dst, head, index_hlist,
639 						 lockdep_is_held(&dtab->index_lock)) {
640 				if (!is_valid_dst(dst, xdpf))
641 					continue;
642 
643 				if (is_ifindex_excluded(excluded_devices, num_excluded,
644 							dst->dev->ifindex))
645 					continue;
646 
647 				/* we only need n-1 clones; last_dst enqueued below */
648 				if (!last_dst) {
649 					last_dst = dst;
650 					continue;
651 				}
652 
653 				err = dev_map_enqueue_clone(last_dst, dev_rx, xdpf);
654 				if (err)
655 					return err;
656 
657 				last_dst = dst;
658 			}
659 		}
660 	}
661 
662 	/* consume the last copy of the frame */
663 	if (last_dst)
664 		bq_enqueue(last_dst->dev, xdpf, dev_rx, last_dst->xdp_prog);
665 	else
666 		xdp_return_frame_rx_napi(xdpf); /* dtab is empty */
667 
668 	return 0;
669 }
670 
671 int dev_map_generic_redirect(struct bpf_dtab_netdev *dst, struct sk_buff *skb,
672 			     struct bpf_prog *xdp_prog)
673 {
674 	int err;
675 
676 	err = xdp_ok_fwd_dev(dst->dev, skb->len);
677 	if (unlikely(err))
678 		return err;
679 
680 	/* Redirect has already succeeded semantically at this point, so we just
681 	 * return 0 even if packet is dropped. Helper below takes care of
682 	 * freeing skb.
683 	 */
684 	if (dev_map_bpf_prog_run_skb(skb, dst) != XDP_PASS)
685 		return 0;
686 
687 	skb->dev = dst->dev;
688 	generic_xdp_tx(skb, xdp_prog);
689 
690 	return 0;
691 }
692 
693 static int dev_map_redirect_clone(struct bpf_dtab_netdev *dst,
694 				  struct sk_buff *skb,
695 				  struct bpf_prog *xdp_prog)
696 {
697 	struct sk_buff *nskb;
698 	int err;
699 
700 	nskb = skb_clone(skb, GFP_ATOMIC);
701 	if (!nskb)
702 		return -ENOMEM;
703 
704 	err = dev_map_generic_redirect(dst, nskb, xdp_prog);
705 	if (unlikely(err)) {
706 		consume_skb(nskb);
707 		return err;
708 	}
709 
710 	return 0;
711 }
712 
713 int dev_map_redirect_multi(struct net_device *dev, struct sk_buff *skb,
714 			   struct bpf_prog *xdp_prog, struct bpf_map *map,
715 			   bool exclude_ingress)
716 {
717 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
718 	struct bpf_dtab_netdev *dst, *last_dst = NULL;
719 	int excluded_devices[1+MAX_NEST_DEV];
720 	struct hlist_head *head;
721 	struct hlist_node *next;
722 	int num_excluded = 0;
723 	unsigned int i;
724 	int err;
725 
726 	if (exclude_ingress) {
727 		num_excluded = get_upper_ifindexes(dev, excluded_devices);
728 		excluded_devices[num_excluded++] = dev->ifindex;
729 	}
730 
731 	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
732 		for (i = 0; i < map->max_entries; i++) {
733 			dst = rcu_dereference_check(dtab->netdev_map[i],
734 						    rcu_read_lock_bh_held());
735 			if (!dst)
736 				continue;
737 
738 			if (is_ifindex_excluded(excluded_devices, num_excluded, dst->dev->ifindex))
739 				continue;
740 
741 			/* we only need n-1 clones; last_dst enqueued below */
742 			if (!last_dst) {
743 				last_dst = dst;
744 				continue;
745 			}
746 
747 			err = dev_map_redirect_clone(last_dst, skb, xdp_prog);
748 			if (err)
749 				return err;
750 
751 			last_dst = dst;
752 
753 		}
754 	} else { /* BPF_MAP_TYPE_DEVMAP_HASH */
755 		for (i = 0; i < dtab->n_buckets; i++) {
756 			head = dev_map_index_hash(dtab, i);
757 			hlist_for_each_entry_safe(dst, next, head, index_hlist) {
758 				if (is_ifindex_excluded(excluded_devices, num_excluded,
759 							dst->dev->ifindex))
760 					continue;
761 
762 				/* we only need n-1 clones; last_dst enqueued below */
763 				if (!last_dst) {
764 					last_dst = dst;
765 					continue;
766 				}
767 
768 				err = dev_map_redirect_clone(last_dst, skb, xdp_prog);
769 				if (err)
770 					return err;
771 
772 				last_dst = dst;
773 			}
774 		}
775 	}
776 
777 	/* consume the first skb and return */
778 	if (last_dst)
779 		return dev_map_generic_redirect(last_dst, skb, xdp_prog);
780 
781 	/* dtab is empty */
782 	consume_skb(skb);
783 	return 0;
784 }
785 
786 static void *dev_map_lookup_elem(struct bpf_map *map, void *key)
787 {
788 	struct bpf_dtab_netdev *obj = __dev_map_lookup_elem(map, *(u32 *)key);
789 
790 	return obj ? &obj->val : NULL;
791 }
792 
793 static void *dev_map_hash_lookup_elem(struct bpf_map *map, void *key)
794 {
795 	struct bpf_dtab_netdev *obj = __dev_map_hash_lookup_elem(map,
796 								*(u32 *)key);
797 	return obj ? &obj->val : NULL;
798 }
799 
800 static void __dev_map_entry_free(struct rcu_head *rcu)
801 {
802 	struct bpf_dtab_netdev *dev;
803 
804 	dev = container_of(rcu, struct bpf_dtab_netdev, rcu);
805 	if (dev->xdp_prog)
806 		bpf_prog_put(dev->xdp_prog);
807 	dev_put(dev->dev);
808 	kfree(dev);
809 }
810 
811 static long dev_map_delete_elem(struct bpf_map *map, void *key)
812 {
813 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
814 	struct bpf_dtab_netdev *old_dev;
815 	int k = *(u32 *)key;
816 
817 	if (k >= map->max_entries)
818 		return -EINVAL;
819 
820 	old_dev = unrcu_pointer(xchg(&dtab->netdev_map[k], NULL));
821 	if (old_dev) {
822 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
823 		atomic_dec((atomic_t *)&dtab->items);
824 	}
825 	return 0;
826 }
827 
828 static long dev_map_hash_delete_elem(struct bpf_map *map, void *key)
829 {
830 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
831 	struct bpf_dtab_netdev *old_dev;
832 	int k = *(u32 *)key;
833 	unsigned long flags;
834 	int ret = -ENOENT;
835 
836 	spin_lock_irqsave(&dtab->index_lock, flags);
837 
838 	old_dev = __dev_map_hash_lookup_elem(map, k);
839 	if (old_dev) {
840 		dtab->items--;
841 		hlist_del_init_rcu(&old_dev->index_hlist);
842 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
843 		ret = 0;
844 	}
845 	spin_unlock_irqrestore(&dtab->index_lock, flags);
846 
847 	return ret;
848 }
849 
850 static struct bpf_dtab_netdev *__dev_map_alloc_node(struct net *net,
851 						    struct bpf_dtab *dtab,
852 						    struct bpf_devmap_val *val,
853 						    unsigned int idx)
854 {
855 	struct bpf_prog *prog = NULL;
856 	struct bpf_dtab_netdev *dev;
857 
858 	dev = bpf_map_kmalloc_node(&dtab->map, sizeof(*dev),
859 				   GFP_NOWAIT | __GFP_NOWARN,
860 				   dtab->map.numa_node);
861 	if (!dev)
862 		return ERR_PTR(-ENOMEM);
863 
864 	dev->dev = dev_get_by_index(net, val->ifindex);
865 	if (!dev->dev)
866 		goto err_out;
867 
868 	if (val->bpf_prog.fd > 0) {
869 		prog = bpf_prog_get_type_dev(val->bpf_prog.fd,
870 					     BPF_PROG_TYPE_XDP, false);
871 		if (IS_ERR(prog))
872 			goto err_put_dev;
873 		if (prog->expected_attach_type != BPF_XDP_DEVMAP ||
874 		    !bpf_prog_map_compatible(&dtab->map, prog))
875 			goto err_put_prog;
876 	}
877 
878 	dev->idx = idx;
879 	if (prog) {
880 		dev->xdp_prog = prog;
881 		dev->val.bpf_prog.id = prog->aux->id;
882 	} else {
883 		dev->xdp_prog = NULL;
884 		dev->val.bpf_prog.id = 0;
885 	}
886 	dev->val.ifindex = val->ifindex;
887 
888 	return dev;
889 err_put_prog:
890 	bpf_prog_put(prog);
891 err_put_dev:
892 	dev_put(dev->dev);
893 err_out:
894 	kfree(dev);
895 	return ERR_PTR(-EINVAL);
896 }
897 
898 static long __dev_map_update_elem(struct net *net, struct bpf_map *map,
899 				  void *key, void *value, u64 map_flags)
900 {
901 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
902 	struct bpf_dtab_netdev *dev, *old_dev;
903 	struct bpf_devmap_val val = {};
904 	u32 i = *(u32 *)key;
905 
906 	if (unlikely(map_flags > BPF_EXIST))
907 		return -EINVAL;
908 	if (unlikely(i >= dtab->map.max_entries))
909 		return -E2BIG;
910 	if (unlikely(map_flags == BPF_NOEXIST))
911 		return -EEXIST;
912 
913 	/* already verified value_size <= sizeof val */
914 	memcpy(&val, value, map->value_size);
915 
916 	if (!val.ifindex) {
917 		dev = NULL;
918 		/* can not specify fd if ifindex is 0 */
919 		if (val.bpf_prog.fd > 0)
920 			return -EINVAL;
921 	} else {
922 		dev = __dev_map_alloc_node(net, dtab, &val, i);
923 		if (IS_ERR(dev))
924 			return PTR_ERR(dev);
925 	}
926 
927 	/* Use call_rcu() here to ensure rcu critical sections have completed
928 	 * Remembering the driver side flush operation will happen before the
929 	 * net device is removed.
930 	 */
931 	old_dev = unrcu_pointer(xchg(&dtab->netdev_map[i], RCU_INITIALIZER(dev)));
932 	if (old_dev)
933 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
934 	else
935 		atomic_inc((atomic_t *)&dtab->items);
936 
937 	return 0;
938 }
939 
940 static long dev_map_update_elem(struct bpf_map *map, void *key, void *value,
941 				u64 map_flags)
942 {
943 	return __dev_map_update_elem(current->nsproxy->net_ns,
944 				     map, key, value, map_flags);
945 }
946 
947 static long __dev_map_hash_update_elem(struct net *net, struct bpf_map *map,
948 				       void *key, void *value, u64 map_flags)
949 {
950 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
951 	struct bpf_dtab_netdev *dev, *old_dev;
952 	struct bpf_devmap_val val = {};
953 	u32 idx = *(u32 *)key;
954 	unsigned long flags;
955 	int err = -EEXIST;
956 
957 	/* already verified value_size <= sizeof val */
958 	memcpy(&val, value, map->value_size);
959 
960 	if (unlikely(map_flags > BPF_EXIST || !val.ifindex))
961 		return -EINVAL;
962 
963 	spin_lock_irqsave(&dtab->index_lock, flags);
964 
965 	old_dev = __dev_map_hash_lookup_elem(map, idx);
966 	if (old_dev && (map_flags & BPF_NOEXIST))
967 		goto out_err;
968 
969 	dev = __dev_map_alloc_node(net, dtab, &val, idx);
970 	if (IS_ERR(dev)) {
971 		err = PTR_ERR(dev);
972 		goto out_err;
973 	}
974 
975 	if (old_dev) {
976 		hlist_del_rcu(&old_dev->index_hlist);
977 	} else {
978 		if (dtab->items >= dtab->map.max_entries) {
979 			spin_unlock_irqrestore(&dtab->index_lock, flags);
980 			call_rcu(&dev->rcu, __dev_map_entry_free);
981 			return -E2BIG;
982 		}
983 		dtab->items++;
984 	}
985 
986 	hlist_add_head_rcu(&dev->index_hlist,
987 			   dev_map_index_hash(dtab, idx));
988 	spin_unlock_irqrestore(&dtab->index_lock, flags);
989 
990 	if (old_dev)
991 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
992 
993 	return 0;
994 
995 out_err:
996 	spin_unlock_irqrestore(&dtab->index_lock, flags);
997 	return err;
998 }
999 
1000 static long dev_map_hash_update_elem(struct bpf_map *map, void *key, void *value,
1001 				     u64 map_flags)
1002 {
1003 	return __dev_map_hash_update_elem(current->nsproxy->net_ns,
1004 					 map, key, value, map_flags);
1005 }
1006 
1007 static long dev_map_redirect(struct bpf_map *map, u64 ifindex, u64 flags)
1008 {
1009 	return __bpf_xdp_redirect_map(map, ifindex, flags,
1010 				      BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS,
1011 				      __dev_map_lookup_elem);
1012 }
1013 
1014 static long dev_hash_map_redirect(struct bpf_map *map, u64 ifindex, u64 flags)
1015 {
1016 	return __bpf_xdp_redirect_map(map, ifindex, flags,
1017 				      BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS,
1018 				      __dev_map_hash_lookup_elem);
1019 }
1020 
1021 static u64 dev_map_mem_usage(const struct bpf_map *map)
1022 {
1023 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
1024 	u64 usage = sizeof(struct bpf_dtab);
1025 
1026 	if (map->map_type == BPF_MAP_TYPE_DEVMAP_HASH)
1027 		usage += (u64)dtab->n_buckets * sizeof(struct hlist_head);
1028 	else
1029 		usage += (u64)map->max_entries * sizeof(struct bpf_dtab_netdev *);
1030 	usage += atomic_read((atomic_t *)&dtab->items) *
1031 			 (u64)sizeof(struct bpf_dtab_netdev);
1032 	return usage;
1033 }
1034 
1035 BTF_ID_LIST_SINGLE(dev_map_btf_ids, struct, bpf_dtab)
1036 const struct bpf_map_ops dev_map_ops = {
1037 	.map_meta_equal = bpf_map_meta_equal,
1038 	.map_alloc = dev_map_alloc,
1039 	.map_free = dev_map_free,
1040 	.map_get_next_key = dev_map_get_next_key,
1041 	.map_lookup_elem = dev_map_lookup_elem,
1042 	.map_update_elem = dev_map_update_elem,
1043 	.map_delete_elem = dev_map_delete_elem,
1044 	.map_check_btf = map_check_no_btf,
1045 	.map_mem_usage = dev_map_mem_usage,
1046 	.map_btf_id = &dev_map_btf_ids[0],
1047 	.map_redirect = dev_map_redirect,
1048 };
1049 
1050 const struct bpf_map_ops dev_map_hash_ops = {
1051 	.map_meta_equal = bpf_map_meta_equal,
1052 	.map_alloc = dev_map_alloc,
1053 	.map_free = dev_map_free,
1054 	.map_get_next_key = dev_map_hash_get_next_key,
1055 	.map_lookup_elem = dev_map_hash_lookup_elem,
1056 	.map_update_elem = dev_map_hash_update_elem,
1057 	.map_delete_elem = dev_map_hash_delete_elem,
1058 	.map_check_btf = map_check_no_btf,
1059 	.map_mem_usage = dev_map_mem_usage,
1060 	.map_btf_id = &dev_map_btf_ids[0],
1061 	.map_redirect = dev_hash_map_redirect,
1062 };
1063 
1064 static void dev_map_hash_remove_netdev(struct bpf_dtab *dtab,
1065 				       struct net_device *netdev)
1066 {
1067 	unsigned long flags;
1068 	u32 i;
1069 
1070 	spin_lock_irqsave(&dtab->index_lock, flags);
1071 	for (i = 0; i < dtab->n_buckets; i++) {
1072 		struct bpf_dtab_netdev *dev;
1073 		struct hlist_head *head;
1074 		struct hlist_node *next;
1075 
1076 		head = dev_map_index_hash(dtab, i);
1077 
1078 		hlist_for_each_entry_safe(dev, next, head, index_hlist) {
1079 			if (netdev != dev->dev)
1080 				continue;
1081 
1082 			dtab->items--;
1083 			hlist_del_rcu(&dev->index_hlist);
1084 			call_rcu(&dev->rcu, __dev_map_entry_free);
1085 		}
1086 	}
1087 	spin_unlock_irqrestore(&dtab->index_lock, flags);
1088 }
1089 
1090 static int dev_map_notification(struct notifier_block *notifier,
1091 				ulong event, void *ptr)
1092 {
1093 	struct net_device *netdev = netdev_notifier_info_to_dev(ptr);
1094 	struct bpf_dtab *dtab;
1095 	int i, cpu;
1096 
1097 	switch (event) {
1098 	case NETDEV_REGISTER:
1099 		if (!netdev->netdev_ops->ndo_xdp_xmit || netdev->xdp_bulkq)
1100 			break;
1101 
1102 		/* will be freed in free_netdev() */
1103 		netdev->xdp_bulkq = alloc_percpu(struct xdp_dev_bulk_queue);
1104 		if (!netdev->xdp_bulkq)
1105 			return NOTIFY_BAD;
1106 
1107 		for_each_possible_cpu(cpu)
1108 			per_cpu_ptr(netdev->xdp_bulkq, cpu)->dev = netdev;
1109 		break;
1110 	case NETDEV_UNREGISTER:
1111 		/* This rcu_read_lock/unlock pair is needed because
1112 		 * dev_map_list is an RCU list AND to ensure a delete
1113 		 * operation does not free a netdev_map entry while we
1114 		 * are comparing it against the netdev being unregistered.
1115 		 */
1116 		rcu_read_lock();
1117 		list_for_each_entry_rcu(dtab, &dev_map_list, list) {
1118 			if (dtab->map.map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
1119 				dev_map_hash_remove_netdev(dtab, netdev);
1120 				continue;
1121 			}
1122 
1123 			for (i = 0; i < dtab->map.max_entries; i++) {
1124 				struct bpf_dtab_netdev *dev, *odev;
1125 
1126 				dev = rcu_dereference(dtab->netdev_map[i]);
1127 				if (!dev || netdev != dev->dev)
1128 					continue;
1129 				odev = unrcu_pointer(cmpxchg(&dtab->netdev_map[i], RCU_INITIALIZER(dev), NULL));
1130 				if (dev == odev) {
1131 					call_rcu(&dev->rcu,
1132 						 __dev_map_entry_free);
1133 					atomic_dec((atomic_t *)&dtab->items);
1134 				}
1135 			}
1136 		}
1137 		rcu_read_unlock();
1138 		break;
1139 	default:
1140 		break;
1141 	}
1142 	return NOTIFY_OK;
1143 }
1144 
1145 static struct notifier_block dev_map_notifier = {
1146 	.notifier_call = dev_map_notification,
1147 };
1148 
1149 static int __init dev_map_init(void)
1150 {
1151 	/* Assure tracepoint shadow struct _bpf_dtab_netdev is in sync */
1152 	BUILD_BUG_ON(offsetof(struct bpf_dtab_netdev, dev) !=
1153 		     offsetof(struct _bpf_dtab_netdev, dev));
1154 	register_netdevice_notifier(&dev_map_notifier);
1155 
1156 	return 0;
1157 }
1158 
1159 subsys_initcall(dev_map_init);
1160