xref: /linux-6.15/kernel/bpf/devmap.c (revision d6a6a555)
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 
52 #define DEV_CREATE_FLAG_MASK \
53 	(BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)
54 
55 struct xdp_dev_bulk_queue {
56 	struct xdp_frame *q[DEV_MAP_BULK_SIZE];
57 	struct list_head flush_node;
58 	struct net_device *dev;
59 	struct net_device *dev_rx;
60 	struct bpf_prog *xdp_prog;
61 	unsigned int count;
62 };
63 
64 struct bpf_dtab_netdev {
65 	struct net_device *dev; /* must be first member, due to tracepoint */
66 	struct hlist_node index_hlist;
67 	struct bpf_dtab *dtab;
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 **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_PER_CPU(struct list_head, dev_flush_list);
87 static DEFINE_SPINLOCK(dev_map_lock);
88 static LIST_HEAD(dev_map_list);
89 
90 static struct hlist_head *dev_map_create_hash(unsigned int entries,
91 					      int numa_node)
92 {
93 	int i;
94 	struct hlist_head *hash;
95 
96 	hash = bpf_map_area_alloc(entries * sizeof(*hash), numa_node);
97 	if (hash != NULL)
98 		for (i = 0; i < entries; i++)
99 			INIT_HLIST_HEAD(&hash[i]);
100 
101 	return hash;
102 }
103 
104 static inline struct hlist_head *dev_map_index_hash(struct bpf_dtab *dtab,
105 						    int idx)
106 {
107 	return &dtab->dev_index_head[idx & (dtab->n_buckets - 1)];
108 }
109 
110 static int dev_map_init_map(struct bpf_dtab *dtab, union bpf_attr *attr)
111 {
112 	u32 valsize = attr->value_size;
113 
114 	/* check sanity of attributes. 2 value sizes supported:
115 	 * 4 bytes: ifindex
116 	 * 8 bytes: ifindex + prog fd
117 	 */
118 	if (attr->max_entries == 0 || attr->key_size != 4 ||
119 	    (valsize != offsetofend(struct bpf_devmap_val, ifindex) &&
120 	     valsize != offsetofend(struct bpf_devmap_val, bpf_prog.fd)) ||
121 	    attr->map_flags & ~DEV_CREATE_FLAG_MASK)
122 		return -EINVAL;
123 
124 	/* Lookup returns a pointer straight to dev->ifindex, so make sure the
125 	 * verifier prevents writes from the BPF side
126 	 */
127 	attr->map_flags |= BPF_F_RDONLY_PROG;
128 
129 
130 	bpf_map_init_from_attr(&dtab->map, attr);
131 
132 	if (attr->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
133 		dtab->n_buckets = roundup_pow_of_two(dtab->map.max_entries);
134 
135 		if (!dtab->n_buckets) /* Overflow check */
136 			return -EINVAL;
137 	}
138 
139 	if (attr->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
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(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 	if (!capable(CAP_NET_ADMIN))
163 		return ERR_PTR(-EPERM);
164 
165 	dtab = kzalloc(sizeof(*dtab), GFP_USER | __GFP_ACCOUNT);
166 	if (!dtab)
167 		return ERR_PTR(-ENOMEM);
168 
169 	err = dev_map_init_map(dtab, attr);
170 	if (err) {
171 		kfree(dtab);
172 		return ERR_PTR(err);
173 	}
174 
175 	spin_lock(&dev_map_lock);
176 	list_add_tail_rcu(&dtab->list, &dev_map_list);
177 	spin_unlock(&dev_map_lock);
178 
179 	return &dtab->map;
180 }
181 
182 static void dev_map_free(struct bpf_map *map)
183 {
184 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
185 	int i;
186 
187 	/* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
188 	 * so the programs (can be more than one that used this map) were
189 	 * disconnected from events. The following synchronize_rcu() guarantees
190 	 * both rcu read critical sections complete and waits for
191 	 * preempt-disable regions (NAPI being the relevant context here) so we
192 	 * are certain there will be no further reads against the netdev_map and
193 	 * all flush operations are complete. Flush operations can only be done
194 	 * from NAPI context for this reason.
195 	 */
196 
197 	spin_lock(&dev_map_lock);
198 	list_del_rcu(&dtab->list);
199 	spin_unlock(&dev_map_lock);
200 
201 	bpf_clear_redirect_map(map);
202 	synchronize_rcu();
203 
204 	/* Make sure prior __dev_map_entry_free() have completed. */
205 	rcu_barrier();
206 
207 	if (dtab->map.map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
208 		for (i = 0; i < dtab->n_buckets; i++) {
209 			struct bpf_dtab_netdev *dev;
210 			struct hlist_head *head;
211 			struct hlist_node *next;
212 
213 			head = dev_map_index_hash(dtab, i);
214 
215 			hlist_for_each_entry_safe(dev, next, head, index_hlist) {
216 				hlist_del_rcu(&dev->index_hlist);
217 				if (dev->xdp_prog)
218 					bpf_prog_put(dev->xdp_prog);
219 				dev_put(dev->dev);
220 				kfree(dev);
221 			}
222 		}
223 
224 		bpf_map_area_free(dtab->dev_index_head);
225 	} else {
226 		for (i = 0; i < dtab->map.max_entries; i++) {
227 			struct bpf_dtab_netdev *dev;
228 
229 			dev = dtab->netdev_map[i];
230 			if (!dev)
231 				continue;
232 
233 			if (dev->xdp_prog)
234 				bpf_prog_put(dev->xdp_prog);
235 			dev_put(dev->dev);
236 			kfree(dev);
237 		}
238 
239 		bpf_map_area_free(dtab->netdev_map);
240 	}
241 
242 	kfree(dtab);
243 }
244 
245 static int dev_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
246 {
247 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
248 	u32 index = key ? *(u32 *)key : U32_MAX;
249 	u32 *next = next_key;
250 
251 	if (index >= dtab->map.max_entries) {
252 		*next = 0;
253 		return 0;
254 	}
255 
256 	if (index == dtab->map.max_entries - 1)
257 		return -ENOENT;
258 	*next = index + 1;
259 	return 0;
260 }
261 
262 static void *__dev_map_hash_lookup_elem(struct bpf_map *map, u32 key)
263 {
264 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
265 	struct hlist_head *head = dev_map_index_hash(dtab, key);
266 	struct bpf_dtab_netdev *dev;
267 
268 	hlist_for_each_entry_rcu(dev, head, index_hlist,
269 				 lockdep_is_held(&dtab->index_lock))
270 		if (dev->idx == key)
271 			return dev;
272 
273 	return NULL;
274 }
275 
276 static int dev_map_hash_get_next_key(struct bpf_map *map, void *key,
277 				    void *next_key)
278 {
279 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
280 	u32 idx, *next = next_key;
281 	struct bpf_dtab_netdev *dev, *next_dev;
282 	struct hlist_head *head;
283 	int i = 0;
284 
285 	if (!key)
286 		goto find_first;
287 
288 	idx = *(u32 *)key;
289 
290 	dev = __dev_map_hash_lookup_elem(map, idx);
291 	if (!dev)
292 		goto find_first;
293 
294 	next_dev = hlist_entry_safe(rcu_dereference_raw(hlist_next_rcu(&dev->index_hlist)),
295 				    struct bpf_dtab_netdev, index_hlist);
296 
297 	if (next_dev) {
298 		*next = next_dev->idx;
299 		return 0;
300 	}
301 
302 	i = idx & (dtab->n_buckets - 1);
303 	i++;
304 
305  find_first:
306 	for (; i < dtab->n_buckets; i++) {
307 		head = dev_map_index_hash(dtab, i);
308 
309 		next_dev = hlist_entry_safe(rcu_dereference_raw(hlist_first_rcu(head)),
310 					    struct bpf_dtab_netdev,
311 					    index_hlist);
312 		if (next_dev) {
313 			*next = next_dev->idx;
314 			return 0;
315 		}
316 	}
317 
318 	return -ENOENT;
319 }
320 
321 bool dev_map_can_have_prog(struct bpf_map *map)
322 {
323 	if ((map->map_type == BPF_MAP_TYPE_DEVMAP ||
324 	     map->map_type == BPF_MAP_TYPE_DEVMAP_HASH) &&
325 	    map->value_size != offsetofend(struct bpf_devmap_val, ifindex))
326 		return true;
327 
328 	return false;
329 }
330 
331 static int dev_map_bpf_prog_run(struct bpf_prog *xdp_prog,
332 				struct xdp_frame **frames, int n,
333 				struct net_device *dev)
334 {
335 	struct xdp_txq_info txq = { .dev = dev };
336 	struct xdp_buff xdp;
337 	int i, nframes = 0;
338 
339 	for (i = 0; i < n; i++) {
340 		struct xdp_frame *xdpf = frames[i];
341 		u32 act;
342 		int err;
343 
344 		xdp_convert_frame_to_buff(xdpf, &xdp);
345 		xdp.txq = &txq;
346 
347 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
348 		switch (act) {
349 		case XDP_PASS:
350 			err = xdp_update_frame_from_buff(&xdp, xdpf);
351 			if (unlikely(err < 0))
352 				xdp_return_frame_rx_napi(xdpf);
353 			else
354 				frames[nframes++] = xdpf;
355 			break;
356 		default:
357 			bpf_warn_invalid_xdp_action(act);
358 			fallthrough;
359 		case XDP_ABORTED:
360 			trace_xdp_exception(dev, xdp_prog, act);
361 			fallthrough;
362 		case XDP_DROP:
363 			xdp_return_frame_rx_napi(xdpf);
364 			break;
365 		}
366 	}
367 	return nframes; /* sent frames count */
368 }
369 
370 static void bq_xmit_all(struct xdp_dev_bulk_queue *bq, u32 flags)
371 {
372 	struct net_device *dev = bq->dev;
373 	int sent = 0, drops = 0, err = 0;
374 	unsigned int cnt = bq->count;
375 	int to_send = cnt;
376 	int i;
377 
378 	if (unlikely(!cnt))
379 		return;
380 
381 	for (i = 0; i < cnt; i++) {
382 		struct xdp_frame *xdpf = bq->q[i];
383 
384 		prefetch(xdpf);
385 	}
386 
387 	if (bq->xdp_prog) {
388 		to_send = dev_map_bpf_prog_run(bq->xdp_prog, bq->q, cnt, dev);
389 		if (!to_send)
390 			goto out;
391 
392 		drops = cnt - to_send;
393 	}
394 
395 	sent = dev->netdev_ops->ndo_xdp_xmit(dev, to_send, bq->q, flags);
396 	if (sent < 0) {
397 		/* If ndo_xdp_xmit fails with an errno, no frames have
398 		 * been xmit'ed.
399 		 */
400 		err = sent;
401 		sent = 0;
402 	}
403 
404 	/* If not all frames have been transmitted, it is our
405 	 * responsibility to free them
406 	 */
407 	for (i = sent; unlikely(i < to_send); i++)
408 		xdp_return_frame_rx_napi(bq->q[i]);
409 
410 out:
411 	drops = cnt - sent;
412 	bq->count = 0;
413 	trace_xdp_devmap_xmit(bq->dev_rx, dev, sent, drops, err);
414 }
415 
416 /* __dev_flush is called from xdp_do_flush() which _must_ be signaled
417  * from the driver before returning from its napi->poll() routine. The poll()
418  * routine is called either from busy_poll context or net_rx_action signaled
419  * from NET_RX_SOFTIRQ. Either way the poll routine must complete before the
420  * net device can be torn down. On devmap tear down we ensure the flush list
421  * is empty before completing to ensure all flush operations have completed.
422  * When drivers update the bpf program they may need to ensure any flush ops
423  * are also complete. Using synchronize_rcu or call_rcu will suffice for this
424  * because both wait for napi context to exit.
425  */
426 void __dev_flush(void)
427 {
428 	struct list_head *flush_list = this_cpu_ptr(&dev_flush_list);
429 	struct xdp_dev_bulk_queue *bq, *tmp;
430 
431 	list_for_each_entry_safe(bq, tmp, flush_list, flush_node) {
432 		bq_xmit_all(bq, XDP_XMIT_FLUSH);
433 		bq->dev_rx = NULL;
434 		bq->xdp_prog = NULL;
435 		__list_del_clearprev(&bq->flush_node);
436 	}
437 }
438 
439 /* rcu_read_lock (from syscall and BPF contexts) ensures that if a delete and/or
440  * update happens in parallel here a dev_put won't happen until after reading
441  * the ifindex.
442  */
443 static void *__dev_map_lookup_elem(struct bpf_map *map, u32 key)
444 {
445 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
446 	struct bpf_dtab_netdev *obj;
447 
448 	if (key >= map->max_entries)
449 		return NULL;
450 
451 	obj = READ_ONCE(dtab->netdev_map[key]);
452 	return obj;
453 }
454 
455 /* Runs under RCU-read-side, plus in softirq under NAPI protection.
456  * Thus, safe percpu variable access.
457  */
458 static void bq_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
459 		       struct net_device *dev_rx, struct bpf_prog *xdp_prog)
460 {
461 	struct list_head *flush_list = this_cpu_ptr(&dev_flush_list);
462 	struct xdp_dev_bulk_queue *bq = this_cpu_ptr(dev->xdp_bulkq);
463 
464 	if (unlikely(bq->count == DEV_MAP_BULK_SIZE))
465 		bq_xmit_all(bq, 0);
466 
467 	/* Ingress dev_rx will be the same for all xdp_frame's in
468 	 * bulk_queue, because bq stored per-CPU and must be flushed
469 	 * from net_device drivers NAPI func end.
470 	 *
471 	 * Do the same with xdp_prog and flush_list since these fields
472 	 * are only ever modified together.
473 	 */
474 	if (!bq->dev_rx) {
475 		bq->dev_rx = dev_rx;
476 		bq->xdp_prog = xdp_prog;
477 		list_add(&bq->flush_node, flush_list);
478 	}
479 
480 	bq->q[bq->count++] = xdpf;
481 }
482 
483 static inline int __xdp_enqueue(struct net_device *dev, struct xdp_buff *xdp,
484 				struct net_device *dev_rx,
485 				struct bpf_prog *xdp_prog)
486 {
487 	struct xdp_frame *xdpf;
488 	int err;
489 
490 	if (!dev->netdev_ops->ndo_xdp_xmit)
491 		return -EOPNOTSUPP;
492 
493 	err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
494 	if (unlikely(err))
495 		return err;
496 
497 	xdpf = xdp_convert_buff_to_frame(xdp);
498 	if (unlikely(!xdpf))
499 		return -EOVERFLOW;
500 
501 	bq_enqueue(dev, xdpf, dev_rx, xdp_prog);
502 	return 0;
503 }
504 
505 int dev_xdp_enqueue(struct net_device *dev, struct xdp_buff *xdp,
506 		    struct net_device *dev_rx)
507 {
508 	return __xdp_enqueue(dev, xdp, dev_rx, NULL);
509 }
510 
511 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_buff *xdp,
512 		    struct net_device *dev_rx)
513 {
514 	struct net_device *dev = dst->dev;
515 
516 	return __xdp_enqueue(dev, xdp, dev_rx, dst->xdp_prog);
517 }
518 
519 static bool is_valid_dst(struct bpf_dtab_netdev *obj, struct xdp_buff *xdp,
520 			 int exclude_ifindex)
521 {
522 	if (!obj || obj->dev->ifindex == exclude_ifindex ||
523 	    !obj->dev->netdev_ops->ndo_xdp_xmit)
524 		return false;
525 
526 	if (xdp_ok_fwd_dev(obj->dev, xdp->data_end - xdp->data))
527 		return false;
528 
529 	return true;
530 }
531 
532 static int dev_map_enqueue_clone(struct bpf_dtab_netdev *obj,
533 				 struct net_device *dev_rx,
534 				 struct xdp_frame *xdpf)
535 {
536 	struct xdp_frame *nxdpf;
537 
538 	nxdpf = xdpf_clone(xdpf);
539 	if (!nxdpf)
540 		return -ENOMEM;
541 
542 	bq_enqueue(obj->dev, nxdpf, dev_rx, obj->xdp_prog);
543 
544 	return 0;
545 }
546 
547 int dev_map_enqueue_multi(struct xdp_buff *xdp, struct net_device *dev_rx,
548 			  struct bpf_map *map, bool exclude_ingress)
549 {
550 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
551 	int exclude_ifindex = exclude_ingress ? dev_rx->ifindex : 0;
552 	struct bpf_dtab_netdev *dst, *last_dst = NULL;
553 	struct hlist_head *head;
554 	struct xdp_frame *xdpf;
555 	unsigned int i;
556 	int err;
557 
558 	xdpf = xdp_convert_buff_to_frame(xdp);
559 	if (unlikely(!xdpf))
560 		return -EOVERFLOW;
561 
562 	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
563 		for (i = 0; i < map->max_entries; i++) {
564 			dst = READ_ONCE(dtab->netdev_map[i]);
565 			if (!is_valid_dst(dst, xdp, exclude_ifindex))
566 				continue;
567 
568 			/* we only need n-1 clones; last_dst enqueued below */
569 			if (!last_dst) {
570 				last_dst = dst;
571 				continue;
572 			}
573 
574 			err = dev_map_enqueue_clone(last_dst, dev_rx, xdpf);
575 			if (err)
576 				return err;
577 
578 			last_dst = dst;
579 		}
580 	} else { /* BPF_MAP_TYPE_DEVMAP_HASH */
581 		for (i = 0; i < dtab->n_buckets; i++) {
582 			head = dev_map_index_hash(dtab, i);
583 			hlist_for_each_entry_rcu(dst, head, index_hlist,
584 						 lockdep_is_held(&dtab->index_lock)) {
585 				if (!is_valid_dst(dst, xdp, exclude_ifindex))
586 					continue;
587 
588 				/* we only need n-1 clones; last_dst enqueued below */
589 				if (!last_dst) {
590 					last_dst = dst;
591 					continue;
592 				}
593 
594 				err = dev_map_enqueue_clone(last_dst, dev_rx, xdpf);
595 				if (err)
596 					return err;
597 
598 				last_dst = dst;
599 			}
600 		}
601 	}
602 
603 	/* consume the last copy of the frame */
604 	if (last_dst)
605 		bq_enqueue(last_dst->dev, xdpf, dev_rx, last_dst->xdp_prog);
606 	else
607 		xdp_return_frame_rx_napi(xdpf); /* dtab is empty */
608 
609 	return 0;
610 }
611 
612 int dev_map_generic_redirect(struct bpf_dtab_netdev *dst, struct sk_buff *skb,
613 			     struct bpf_prog *xdp_prog)
614 {
615 	int err;
616 
617 	err = xdp_ok_fwd_dev(dst->dev, skb->len);
618 	if (unlikely(err))
619 		return err;
620 	skb->dev = dst->dev;
621 	generic_xdp_tx(skb, xdp_prog);
622 
623 	return 0;
624 }
625 
626 static int dev_map_redirect_clone(struct bpf_dtab_netdev *dst,
627 				  struct sk_buff *skb,
628 				  struct bpf_prog *xdp_prog)
629 {
630 	struct sk_buff *nskb;
631 	int err;
632 
633 	nskb = skb_clone(skb, GFP_ATOMIC);
634 	if (!nskb)
635 		return -ENOMEM;
636 
637 	err = dev_map_generic_redirect(dst, nskb, xdp_prog);
638 	if (unlikely(err)) {
639 		consume_skb(nskb);
640 		return err;
641 	}
642 
643 	return 0;
644 }
645 
646 int dev_map_redirect_multi(struct net_device *dev, struct sk_buff *skb,
647 			   struct bpf_prog *xdp_prog, struct bpf_map *map,
648 			   bool exclude_ingress)
649 {
650 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
651 	int exclude_ifindex = exclude_ingress ? dev->ifindex : 0;
652 	struct bpf_dtab_netdev *dst, *last_dst = NULL;
653 	struct hlist_head *head;
654 	struct hlist_node *next;
655 	unsigned int i;
656 	int err;
657 
658 	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
659 		for (i = 0; i < map->max_entries; i++) {
660 			dst = READ_ONCE(dtab->netdev_map[i]);
661 			if (!dst || dst->dev->ifindex == exclude_ifindex)
662 				continue;
663 
664 			/* we only need n-1 clones; last_dst enqueued below */
665 			if (!last_dst) {
666 				last_dst = dst;
667 				continue;
668 			}
669 
670 			err = dev_map_redirect_clone(last_dst, skb, xdp_prog);
671 			if (err)
672 				return err;
673 
674 			last_dst = dst;
675 		}
676 	} else { /* BPF_MAP_TYPE_DEVMAP_HASH */
677 		for (i = 0; i < dtab->n_buckets; i++) {
678 			head = dev_map_index_hash(dtab, i);
679 			hlist_for_each_entry_safe(dst, next, head, index_hlist) {
680 				if (!dst || dst->dev->ifindex == exclude_ifindex)
681 					continue;
682 
683 				/* we only need n-1 clones; last_dst enqueued below */
684 				if (!last_dst) {
685 					last_dst = dst;
686 					continue;
687 				}
688 
689 				err = dev_map_redirect_clone(last_dst, skb, xdp_prog);
690 				if (err)
691 					return err;
692 
693 				last_dst = dst;
694 			}
695 		}
696 	}
697 
698 	/* consume the first skb and return */
699 	if (last_dst)
700 		return dev_map_generic_redirect(last_dst, skb, xdp_prog);
701 
702 	/* dtab is empty */
703 	consume_skb(skb);
704 	return 0;
705 }
706 
707 static void *dev_map_lookup_elem(struct bpf_map *map, void *key)
708 {
709 	struct bpf_dtab_netdev *obj = __dev_map_lookup_elem(map, *(u32 *)key);
710 
711 	return obj ? &obj->val : NULL;
712 }
713 
714 static void *dev_map_hash_lookup_elem(struct bpf_map *map, void *key)
715 {
716 	struct bpf_dtab_netdev *obj = __dev_map_hash_lookup_elem(map,
717 								*(u32 *)key);
718 	return obj ? &obj->val : NULL;
719 }
720 
721 static void __dev_map_entry_free(struct rcu_head *rcu)
722 {
723 	struct bpf_dtab_netdev *dev;
724 
725 	dev = container_of(rcu, struct bpf_dtab_netdev, rcu);
726 	if (dev->xdp_prog)
727 		bpf_prog_put(dev->xdp_prog);
728 	dev_put(dev->dev);
729 	kfree(dev);
730 }
731 
732 static int dev_map_delete_elem(struct bpf_map *map, void *key)
733 {
734 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
735 	struct bpf_dtab_netdev *old_dev;
736 	int k = *(u32 *)key;
737 
738 	if (k >= map->max_entries)
739 		return -EINVAL;
740 
741 	/* Use call_rcu() here to ensure any rcu critical sections have
742 	 * completed as well as any flush operations because call_rcu
743 	 * will wait for preempt-disable region to complete, NAPI in this
744 	 * context.  And additionally, the driver tear down ensures all
745 	 * soft irqs are complete before removing the net device in the
746 	 * case of dev_put equals zero.
747 	 */
748 	old_dev = xchg(&dtab->netdev_map[k], NULL);
749 	if (old_dev)
750 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
751 	return 0;
752 }
753 
754 static int dev_map_hash_delete_elem(struct bpf_map *map, void *key)
755 {
756 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
757 	struct bpf_dtab_netdev *old_dev;
758 	int k = *(u32 *)key;
759 	unsigned long flags;
760 	int ret = -ENOENT;
761 
762 	spin_lock_irqsave(&dtab->index_lock, flags);
763 
764 	old_dev = __dev_map_hash_lookup_elem(map, k);
765 	if (old_dev) {
766 		dtab->items--;
767 		hlist_del_init_rcu(&old_dev->index_hlist);
768 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
769 		ret = 0;
770 	}
771 	spin_unlock_irqrestore(&dtab->index_lock, flags);
772 
773 	return ret;
774 }
775 
776 static struct bpf_dtab_netdev *__dev_map_alloc_node(struct net *net,
777 						    struct bpf_dtab *dtab,
778 						    struct bpf_devmap_val *val,
779 						    unsigned int idx)
780 {
781 	struct bpf_prog *prog = NULL;
782 	struct bpf_dtab_netdev *dev;
783 
784 	dev = bpf_map_kmalloc_node(&dtab->map, sizeof(*dev),
785 				   GFP_ATOMIC | __GFP_NOWARN,
786 				   dtab->map.numa_node);
787 	if (!dev)
788 		return ERR_PTR(-ENOMEM);
789 
790 	dev->dev = dev_get_by_index(net, val->ifindex);
791 	if (!dev->dev)
792 		goto err_out;
793 
794 	if (val->bpf_prog.fd > 0) {
795 		prog = bpf_prog_get_type_dev(val->bpf_prog.fd,
796 					     BPF_PROG_TYPE_XDP, false);
797 		if (IS_ERR(prog))
798 			goto err_put_dev;
799 		if (prog->expected_attach_type != BPF_XDP_DEVMAP)
800 			goto err_put_prog;
801 	}
802 
803 	dev->idx = idx;
804 	dev->dtab = dtab;
805 	if (prog) {
806 		dev->xdp_prog = prog;
807 		dev->val.bpf_prog.id = prog->aux->id;
808 	} else {
809 		dev->xdp_prog = NULL;
810 		dev->val.bpf_prog.id = 0;
811 	}
812 	dev->val.ifindex = val->ifindex;
813 
814 	return dev;
815 err_put_prog:
816 	bpf_prog_put(prog);
817 err_put_dev:
818 	dev_put(dev->dev);
819 err_out:
820 	kfree(dev);
821 	return ERR_PTR(-EINVAL);
822 }
823 
824 static int __dev_map_update_elem(struct net *net, struct bpf_map *map,
825 				 void *key, void *value, u64 map_flags)
826 {
827 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
828 	struct bpf_dtab_netdev *dev, *old_dev;
829 	struct bpf_devmap_val val = {};
830 	u32 i = *(u32 *)key;
831 
832 	if (unlikely(map_flags > BPF_EXIST))
833 		return -EINVAL;
834 	if (unlikely(i >= dtab->map.max_entries))
835 		return -E2BIG;
836 	if (unlikely(map_flags == BPF_NOEXIST))
837 		return -EEXIST;
838 
839 	/* already verified value_size <= sizeof val */
840 	memcpy(&val, value, map->value_size);
841 
842 	if (!val.ifindex) {
843 		dev = NULL;
844 		/* can not specify fd if ifindex is 0 */
845 		if (val.bpf_prog.fd > 0)
846 			return -EINVAL;
847 	} else {
848 		dev = __dev_map_alloc_node(net, dtab, &val, i);
849 		if (IS_ERR(dev))
850 			return PTR_ERR(dev);
851 	}
852 
853 	/* Use call_rcu() here to ensure rcu critical sections have completed
854 	 * Remembering the driver side flush operation will happen before the
855 	 * net device is removed.
856 	 */
857 	old_dev = xchg(&dtab->netdev_map[i], dev);
858 	if (old_dev)
859 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
860 
861 	return 0;
862 }
863 
864 static int dev_map_update_elem(struct bpf_map *map, void *key, void *value,
865 			       u64 map_flags)
866 {
867 	return __dev_map_update_elem(current->nsproxy->net_ns,
868 				     map, key, value, map_flags);
869 }
870 
871 static int __dev_map_hash_update_elem(struct net *net, struct bpf_map *map,
872 				     void *key, void *value, u64 map_flags)
873 {
874 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
875 	struct bpf_dtab_netdev *dev, *old_dev;
876 	struct bpf_devmap_val val = {};
877 	u32 idx = *(u32 *)key;
878 	unsigned long flags;
879 	int err = -EEXIST;
880 
881 	/* already verified value_size <= sizeof val */
882 	memcpy(&val, value, map->value_size);
883 
884 	if (unlikely(map_flags > BPF_EXIST || !val.ifindex))
885 		return -EINVAL;
886 
887 	spin_lock_irqsave(&dtab->index_lock, flags);
888 
889 	old_dev = __dev_map_hash_lookup_elem(map, idx);
890 	if (old_dev && (map_flags & BPF_NOEXIST))
891 		goto out_err;
892 
893 	dev = __dev_map_alloc_node(net, dtab, &val, idx);
894 	if (IS_ERR(dev)) {
895 		err = PTR_ERR(dev);
896 		goto out_err;
897 	}
898 
899 	if (old_dev) {
900 		hlist_del_rcu(&old_dev->index_hlist);
901 	} else {
902 		if (dtab->items >= dtab->map.max_entries) {
903 			spin_unlock_irqrestore(&dtab->index_lock, flags);
904 			call_rcu(&dev->rcu, __dev_map_entry_free);
905 			return -E2BIG;
906 		}
907 		dtab->items++;
908 	}
909 
910 	hlist_add_head_rcu(&dev->index_hlist,
911 			   dev_map_index_hash(dtab, idx));
912 	spin_unlock_irqrestore(&dtab->index_lock, flags);
913 
914 	if (old_dev)
915 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
916 
917 	return 0;
918 
919 out_err:
920 	spin_unlock_irqrestore(&dtab->index_lock, flags);
921 	return err;
922 }
923 
924 static int dev_map_hash_update_elem(struct bpf_map *map, void *key, void *value,
925 				   u64 map_flags)
926 {
927 	return __dev_map_hash_update_elem(current->nsproxy->net_ns,
928 					 map, key, value, map_flags);
929 }
930 
931 static int dev_map_redirect(struct bpf_map *map, u32 ifindex, u64 flags)
932 {
933 	return __bpf_xdp_redirect_map(map, ifindex, flags,
934 				      BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS,
935 				      __dev_map_lookup_elem);
936 }
937 
938 static int dev_hash_map_redirect(struct bpf_map *map, u32 ifindex, u64 flags)
939 {
940 	return __bpf_xdp_redirect_map(map, ifindex, flags,
941 				      BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS,
942 				      __dev_map_hash_lookup_elem);
943 }
944 
945 static int dev_map_btf_id;
946 const struct bpf_map_ops dev_map_ops = {
947 	.map_meta_equal = bpf_map_meta_equal,
948 	.map_alloc = dev_map_alloc,
949 	.map_free = dev_map_free,
950 	.map_get_next_key = dev_map_get_next_key,
951 	.map_lookup_elem = dev_map_lookup_elem,
952 	.map_update_elem = dev_map_update_elem,
953 	.map_delete_elem = dev_map_delete_elem,
954 	.map_check_btf = map_check_no_btf,
955 	.map_btf_name = "bpf_dtab",
956 	.map_btf_id = &dev_map_btf_id,
957 	.map_redirect = dev_map_redirect,
958 };
959 
960 static int dev_map_hash_map_btf_id;
961 const struct bpf_map_ops dev_map_hash_ops = {
962 	.map_meta_equal = bpf_map_meta_equal,
963 	.map_alloc = dev_map_alloc,
964 	.map_free = dev_map_free,
965 	.map_get_next_key = dev_map_hash_get_next_key,
966 	.map_lookup_elem = dev_map_hash_lookup_elem,
967 	.map_update_elem = dev_map_hash_update_elem,
968 	.map_delete_elem = dev_map_hash_delete_elem,
969 	.map_check_btf = map_check_no_btf,
970 	.map_btf_name = "bpf_dtab",
971 	.map_btf_id = &dev_map_hash_map_btf_id,
972 	.map_redirect = dev_hash_map_redirect,
973 };
974 
975 static void dev_map_hash_remove_netdev(struct bpf_dtab *dtab,
976 				       struct net_device *netdev)
977 {
978 	unsigned long flags;
979 	u32 i;
980 
981 	spin_lock_irqsave(&dtab->index_lock, flags);
982 	for (i = 0; i < dtab->n_buckets; i++) {
983 		struct bpf_dtab_netdev *dev;
984 		struct hlist_head *head;
985 		struct hlist_node *next;
986 
987 		head = dev_map_index_hash(dtab, i);
988 
989 		hlist_for_each_entry_safe(dev, next, head, index_hlist) {
990 			if (netdev != dev->dev)
991 				continue;
992 
993 			dtab->items--;
994 			hlist_del_rcu(&dev->index_hlist);
995 			call_rcu(&dev->rcu, __dev_map_entry_free);
996 		}
997 	}
998 	spin_unlock_irqrestore(&dtab->index_lock, flags);
999 }
1000 
1001 static int dev_map_notification(struct notifier_block *notifier,
1002 				ulong event, void *ptr)
1003 {
1004 	struct net_device *netdev = netdev_notifier_info_to_dev(ptr);
1005 	struct bpf_dtab *dtab;
1006 	int i, cpu;
1007 
1008 	switch (event) {
1009 	case NETDEV_REGISTER:
1010 		if (!netdev->netdev_ops->ndo_xdp_xmit || netdev->xdp_bulkq)
1011 			break;
1012 
1013 		/* will be freed in free_netdev() */
1014 		netdev->xdp_bulkq = alloc_percpu(struct xdp_dev_bulk_queue);
1015 		if (!netdev->xdp_bulkq)
1016 			return NOTIFY_BAD;
1017 
1018 		for_each_possible_cpu(cpu)
1019 			per_cpu_ptr(netdev->xdp_bulkq, cpu)->dev = netdev;
1020 		break;
1021 	case NETDEV_UNREGISTER:
1022 		/* This rcu_read_lock/unlock pair is needed because
1023 		 * dev_map_list is an RCU list AND to ensure a delete
1024 		 * operation does not free a netdev_map entry while we
1025 		 * are comparing it against the netdev being unregistered.
1026 		 */
1027 		rcu_read_lock();
1028 		list_for_each_entry_rcu(dtab, &dev_map_list, list) {
1029 			if (dtab->map.map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
1030 				dev_map_hash_remove_netdev(dtab, netdev);
1031 				continue;
1032 			}
1033 
1034 			for (i = 0; i < dtab->map.max_entries; i++) {
1035 				struct bpf_dtab_netdev *dev, *odev;
1036 
1037 				dev = READ_ONCE(dtab->netdev_map[i]);
1038 				if (!dev || netdev != dev->dev)
1039 					continue;
1040 				odev = cmpxchg(&dtab->netdev_map[i], dev, NULL);
1041 				if (dev == odev)
1042 					call_rcu(&dev->rcu,
1043 						 __dev_map_entry_free);
1044 			}
1045 		}
1046 		rcu_read_unlock();
1047 		break;
1048 	default:
1049 		break;
1050 	}
1051 	return NOTIFY_OK;
1052 }
1053 
1054 static struct notifier_block dev_map_notifier = {
1055 	.notifier_call = dev_map_notification,
1056 };
1057 
1058 static int __init dev_map_init(void)
1059 {
1060 	int cpu;
1061 
1062 	/* Assure tracepoint shadow struct _bpf_dtab_netdev is in sync */
1063 	BUILD_BUG_ON(offsetof(struct bpf_dtab_netdev, dev) !=
1064 		     offsetof(struct _bpf_dtab_netdev, dev));
1065 	register_netdevice_notifier(&dev_map_notifier);
1066 
1067 	for_each_possible_cpu(cpu)
1068 		INIT_LIST_HEAD(&per_cpu(dev_flush_list, cpu));
1069 	return 0;
1070 }
1071 
1072 subsys_initcall(dev_map_init);
1073