xref: /linux/kernel/bpf/devmap.c (revision 4dec64c52e24c2c9a15f81c115f1be5ea35121cb)
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 xdp_dev_bulk_queue *bq = this_cpu_ptr(dev->xdp_bulkq);
452 
453 	if (unlikely(bq->count == DEV_MAP_BULK_SIZE))
454 		bq_xmit_all(bq, 0);
455 
456 	/* Ingress dev_rx will be the same for all xdp_frame's in
457 	 * bulk_queue, because bq stored per-CPU and must be flushed
458 	 * from net_device drivers NAPI func end.
459 	 *
460 	 * Do the same with xdp_prog and flush_list since these fields
461 	 * are only ever modified together.
462 	 */
463 	if (!bq->dev_rx) {
464 		struct list_head *flush_list = bpf_net_ctx_get_dev_flush_list();
465 
466 		bq->dev_rx = dev_rx;
467 		bq->xdp_prog = xdp_prog;
468 		list_add(&bq->flush_node, flush_list);
469 	}
470 
471 	bq->q[bq->count++] = xdpf;
472 }
473 
474 static inline int __xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
475 				struct net_device *dev_rx,
476 				struct bpf_prog *xdp_prog)
477 {
478 	int err;
479 
480 	if (!(dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT))
481 		return -EOPNOTSUPP;
482 
483 	if (unlikely(!(dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT_SG) &&
484 		     xdp_frame_has_frags(xdpf)))
485 		return -EOPNOTSUPP;
486 
487 	err = xdp_ok_fwd_dev(dev, xdp_get_frame_len(xdpf));
488 	if (unlikely(err))
489 		return err;
490 
491 	bq_enqueue(dev, xdpf, dev_rx, xdp_prog);
492 	return 0;
493 }
494 
495 static u32 dev_map_bpf_prog_run_skb(struct sk_buff *skb, struct bpf_dtab_netdev *dst)
496 {
497 	struct xdp_txq_info txq = { .dev = dst->dev };
498 	struct xdp_buff xdp;
499 	u32 act;
500 
501 	if (!dst->xdp_prog)
502 		return XDP_PASS;
503 
504 	__skb_pull(skb, skb->mac_len);
505 	xdp.txq = &txq;
506 
507 	act = bpf_prog_run_generic_xdp(skb, &xdp, dst->xdp_prog);
508 	switch (act) {
509 	case XDP_PASS:
510 		__skb_push(skb, skb->mac_len);
511 		break;
512 	default:
513 		bpf_warn_invalid_xdp_action(NULL, dst->xdp_prog, act);
514 		fallthrough;
515 	case XDP_ABORTED:
516 		trace_xdp_exception(dst->dev, dst->xdp_prog, act);
517 		fallthrough;
518 	case XDP_DROP:
519 		kfree_skb(skb);
520 		break;
521 	}
522 
523 	return act;
524 }
525 
526 int dev_xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
527 		    struct net_device *dev_rx)
528 {
529 	return __xdp_enqueue(dev, xdpf, dev_rx, NULL);
530 }
531 
532 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_frame *xdpf,
533 		    struct net_device *dev_rx)
534 {
535 	struct net_device *dev = dst->dev;
536 
537 	return __xdp_enqueue(dev, xdpf, dev_rx, dst->xdp_prog);
538 }
539 
540 static bool is_valid_dst(struct bpf_dtab_netdev *obj, struct xdp_frame *xdpf)
541 {
542 	if (!obj)
543 		return false;
544 
545 	if (!(obj->dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT))
546 		return false;
547 
548 	if (unlikely(!(obj->dev->xdp_features & NETDEV_XDP_ACT_NDO_XMIT_SG) &&
549 		     xdp_frame_has_frags(xdpf)))
550 		return false;
551 
552 	if (xdp_ok_fwd_dev(obj->dev, xdp_get_frame_len(xdpf)))
553 		return false;
554 
555 	return true;
556 }
557 
558 static int dev_map_enqueue_clone(struct bpf_dtab_netdev *obj,
559 				 struct net_device *dev_rx,
560 				 struct xdp_frame *xdpf)
561 {
562 	struct xdp_frame *nxdpf;
563 
564 	nxdpf = xdpf_clone(xdpf);
565 	if (!nxdpf)
566 		return -ENOMEM;
567 
568 	bq_enqueue(obj->dev, nxdpf, dev_rx, obj->xdp_prog);
569 
570 	return 0;
571 }
572 
573 static inline bool is_ifindex_excluded(int *excluded, int num_excluded, int ifindex)
574 {
575 	while (num_excluded--) {
576 		if (ifindex == excluded[num_excluded])
577 			return true;
578 	}
579 	return false;
580 }
581 
582 /* Get ifindex of each upper device. 'indexes' must be able to hold at
583  * least MAX_NEST_DEV elements.
584  * Returns the number of ifindexes added.
585  */
586 static int get_upper_ifindexes(struct net_device *dev, int *indexes)
587 {
588 	struct net_device *upper;
589 	struct list_head *iter;
590 	int n = 0;
591 
592 	netdev_for_each_upper_dev_rcu(dev, upper, iter) {
593 		indexes[n++] = upper->ifindex;
594 	}
595 	return n;
596 }
597 
598 int dev_map_enqueue_multi(struct xdp_frame *xdpf, struct net_device *dev_rx,
599 			  struct bpf_map *map, bool exclude_ingress)
600 {
601 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
602 	struct bpf_dtab_netdev *dst, *last_dst = NULL;
603 	int excluded_devices[1+MAX_NEST_DEV];
604 	struct hlist_head *head;
605 	int num_excluded = 0;
606 	unsigned int i;
607 	int err;
608 
609 	if (exclude_ingress) {
610 		num_excluded = get_upper_ifindexes(dev_rx, excluded_devices);
611 		excluded_devices[num_excluded++] = dev_rx->ifindex;
612 	}
613 
614 	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
615 		for (i = 0; i < map->max_entries; i++) {
616 			dst = rcu_dereference_check(dtab->netdev_map[i],
617 						    rcu_read_lock_bh_held());
618 			if (!is_valid_dst(dst, xdpf))
619 				continue;
620 
621 			if (is_ifindex_excluded(excluded_devices, num_excluded, dst->dev->ifindex))
622 				continue;
623 
624 			/* we only need n-1 clones; last_dst enqueued below */
625 			if (!last_dst) {
626 				last_dst = dst;
627 				continue;
628 			}
629 
630 			err = dev_map_enqueue_clone(last_dst, dev_rx, xdpf);
631 			if (err)
632 				return err;
633 
634 			last_dst = dst;
635 		}
636 	} else { /* BPF_MAP_TYPE_DEVMAP_HASH */
637 		for (i = 0; i < dtab->n_buckets; i++) {
638 			head = dev_map_index_hash(dtab, i);
639 			hlist_for_each_entry_rcu(dst, head, index_hlist,
640 						 lockdep_is_held(&dtab->index_lock)) {
641 				if (!is_valid_dst(dst, xdpf))
642 					continue;
643 
644 				if (is_ifindex_excluded(excluded_devices, num_excluded,
645 							dst->dev->ifindex))
646 					continue;
647 
648 				/* we only need n-1 clones; last_dst enqueued below */
649 				if (!last_dst) {
650 					last_dst = dst;
651 					continue;
652 				}
653 
654 				err = dev_map_enqueue_clone(last_dst, dev_rx, xdpf);
655 				if (err)
656 					return err;
657 
658 				last_dst = dst;
659 			}
660 		}
661 	}
662 
663 	/* consume the last copy of the frame */
664 	if (last_dst)
665 		bq_enqueue(last_dst->dev, xdpf, dev_rx, last_dst->xdp_prog);
666 	else
667 		xdp_return_frame_rx_napi(xdpf); /* dtab is empty */
668 
669 	return 0;
670 }
671 
672 int dev_map_generic_redirect(struct bpf_dtab_netdev *dst, struct sk_buff *skb,
673 			     struct bpf_prog *xdp_prog)
674 {
675 	int err;
676 
677 	err = xdp_ok_fwd_dev(dst->dev, skb->len);
678 	if (unlikely(err))
679 		return err;
680 
681 	/* Redirect has already succeeded semantically at this point, so we just
682 	 * return 0 even if packet is dropped. Helper below takes care of
683 	 * freeing skb.
684 	 */
685 	if (dev_map_bpf_prog_run_skb(skb, dst) != XDP_PASS)
686 		return 0;
687 
688 	skb->dev = dst->dev;
689 	generic_xdp_tx(skb, xdp_prog);
690 
691 	return 0;
692 }
693 
694 static int dev_map_redirect_clone(struct bpf_dtab_netdev *dst,
695 				  struct sk_buff *skb,
696 				  struct bpf_prog *xdp_prog)
697 {
698 	struct sk_buff *nskb;
699 	int err;
700 
701 	nskb = skb_clone(skb, GFP_ATOMIC);
702 	if (!nskb)
703 		return -ENOMEM;
704 
705 	err = dev_map_generic_redirect(dst, nskb, xdp_prog);
706 	if (unlikely(err)) {
707 		consume_skb(nskb);
708 		return err;
709 	}
710 
711 	return 0;
712 }
713 
714 int dev_map_redirect_multi(struct net_device *dev, struct sk_buff *skb,
715 			   struct bpf_prog *xdp_prog, struct bpf_map *map,
716 			   bool exclude_ingress)
717 {
718 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
719 	struct bpf_dtab_netdev *dst, *last_dst = NULL;
720 	int excluded_devices[1+MAX_NEST_DEV];
721 	struct hlist_head *head;
722 	struct hlist_node *next;
723 	int num_excluded = 0;
724 	unsigned int i;
725 	int err;
726 
727 	if (exclude_ingress) {
728 		num_excluded = get_upper_ifindexes(dev, excluded_devices);
729 		excluded_devices[num_excluded++] = dev->ifindex;
730 	}
731 
732 	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
733 		for (i = 0; i < map->max_entries; i++) {
734 			dst = rcu_dereference_check(dtab->netdev_map[i],
735 						    rcu_read_lock_bh_held());
736 			if (!dst)
737 				continue;
738 
739 			if (is_ifindex_excluded(excluded_devices, num_excluded, dst->dev->ifindex))
740 				continue;
741 
742 			/* we only need n-1 clones; last_dst enqueued below */
743 			if (!last_dst) {
744 				last_dst = dst;
745 				continue;
746 			}
747 
748 			err = dev_map_redirect_clone(last_dst, skb, xdp_prog);
749 			if (err)
750 				return err;
751 
752 			last_dst = dst;
753 
754 		}
755 	} else { /* BPF_MAP_TYPE_DEVMAP_HASH */
756 		for (i = 0; i < dtab->n_buckets; i++) {
757 			head = dev_map_index_hash(dtab, i);
758 			hlist_for_each_entry_safe(dst, next, head, index_hlist) {
759 				if (is_ifindex_excluded(excluded_devices, num_excluded,
760 							dst->dev->ifindex))
761 					continue;
762 
763 				/* we only need n-1 clones; last_dst enqueued below */
764 				if (!last_dst) {
765 					last_dst = dst;
766 					continue;
767 				}
768 
769 				err = dev_map_redirect_clone(last_dst, skb, xdp_prog);
770 				if (err)
771 					return err;
772 
773 				last_dst = dst;
774 			}
775 		}
776 	}
777 
778 	/* consume the first skb and return */
779 	if (last_dst)
780 		return dev_map_generic_redirect(last_dst, skb, xdp_prog);
781 
782 	/* dtab is empty */
783 	consume_skb(skb);
784 	return 0;
785 }
786 
787 static void *dev_map_lookup_elem(struct bpf_map *map, void *key)
788 {
789 	struct bpf_dtab_netdev *obj = __dev_map_lookup_elem(map, *(u32 *)key);
790 
791 	return obj ? &obj->val : NULL;
792 }
793 
794 static void *dev_map_hash_lookup_elem(struct bpf_map *map, void *key)
795 {
796 	struct bpf_dtab_netdev *obj = __dev_map_hash_lookup_elem(map,
797 								*(u32 *)key);
798 	return obj ? &obj->val : NULL;
799 }
800 
801 static void __dev_map_entry_free(struct rcu_head *rcu)
802 {
803 	struct bpf_dtab_netdev *dev;
804 
805 	dev = container_of(rcu, struct bpf_dtab_netdev, rcu);
806 	if (dev->xdp_prog)
807 		bpf_prog_put(dev->xdp_prog);
808 	dev_put(dev->dev);
809 	kfree(dev);
810 }
811 
812 static long dev_map_delete_elem(struct bpf_map *map, void *key)
813 {
814 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
815 	struct bpf_dtab_netdev *old_dev;
816 	int k = *(u32 *)key;
817 
818 	if (k >= map->max_entries)
819 		return -EINVAL;
820 
821 	old_dev = unrcu_pointer(xchg(&dtab->netdev_map[k], NULL));
822 	if (old_dev) {
823 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
824 		atomic_dec((atomic_t *)&dtab->items);
825 	}
826 	return 0;
827 }
828 
829 static long dev_map_hash_delete_elem(struct bpf_map *map, void *key)
830 {
831 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
832 	struct bpf_dtab_netdev *old_dev;
833 	int k = *(u32 *)key;
834 	unsigned long flags;
835 	int ret = -ENOENT;
836 
837 	spin_lock_irqsave(&dtab->index_lock, flags);
838 
839 	old_dev = __dev_map_hash_lookup_elem(map, k);
840 	if (old_dev) {
841 		dtab->items--;
842 		hlist_del_init_rcu(&old_dev->index_hlist);
843 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
844 		ret = 0;
845 	}
846 	spin_unlock_irqrestore(&dtab->index_lock, flags);
847 
848 	return ret;
849 }
850 
851 static struct bpf_dtab_netdev *__dev_map_alloc_node(struct net *net,
852 						    struct bpf_dtab *dtab,
853 						    struct bpf_devmap_val *val,
854 						    unsigned int idx)
855 {
856 	struct bpf_prog *prog = NULL;
857 	struct bpf_dtab_netdev *dev;
858 
859 	dev = bpf_map_kmalloc_node(&dtab->map, sizeof(*dev),
860 				   GFP_NOWAIT | __GFP_NOWARN,
861 				   dtab->map.numa_node);
862 	if (!dev)
863 		return ERR_PTR(-ENOMEM);
864 
865 	dev->dev = dev_get_by_index(net, val->ifindex);
866 	if (!dev->dev)
867 		goto err_out;
868 
869 	if (val->bpf_prog.fd > 0) {
870 		prog = bpf_prog_get_type_dev(val->bpf_prog.fd,
871 					     BPF_PROG_TYPE_XDP, false);
872 		if (IS_ERR(prog))
873 			goto err_put_dev;
874 		if (prog->expected_attach_type != BPF_XDP_DEVMAP ||
875 		    !bpf_prog_map_compatible(&dtab->map, prog))
876 			goto err_put_prog;
877 	}
878 
879 	dev->idx = idx;
880 	if (prog) {
881 		dev->xdp_prog = prog;
882 		dev->val.bpf_prog.id = prog->aux->id;
883 	} else {
884 		dev->xdp_prog = NULL;
885 		dev->val.bpf_prog.id = 0;
886 	}
887 	dev->val.ifindex = val->ifindex;
888 
889 	return dev;
890 err_put_prog:
891 	bpf_prog_put(prog);
892 err_put_dev:
893 	dev_put(dev->dev);
894 err_out:
895 	kfree(dev);
896 	return ERR_PTR(-EINVAL);
897 }
898 
899 static long __dev_map_update_elem(struct net *net, struct bpf_map *map,
900 				  void *key, void *value, u64 map_flags)
901 {
902 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
903 	struct bpf_dtab_netdev *dev, *old_dev;
904 	struct bpf_devmap_val val = {};
905 	u32 i = *(u32 *)key;
906 
907 	if (unlikely(map_flags > BPF_EXIST))
908 		return -EINVAL;
909 	if (unlikely(i >= dtab->map.max_entries))
910 		return -E2BIG;
911 	if (unlikely(map_flags == BPF_NOEXIST))
912 		return -EEXIST;
913 
914 	/* already verified value_size <= sizeof val */
915 	memcpy(&val, value, map->value_size);
916 
917 	if (!val.ifindex) {
918 		dev = NULL;
919 		/* can not specify fd if ifindex is 0 */
920 		if (val.bpf_prog.fd > 0)
921 			return -EINVAL;
922 	} else {
923 		dev = __dev_map_alloc_node(net, dtab, &val, i);
924 		if (IS_ERR(dev))
925 			return PTR_ERR(dev);
926 	}
927 
928 	/* Use call_rcu() here to ensure rcu critical sections have completed
929 	 * Remembering the driver side flush operation will happen before the
930 	 * net device is removed.
931 	 */
932 	old_dev = unrcu_pointer(xchg(&dtab->netdev_map[i], RCU_INITIALIZER(dev)));
933 	if (old_dev)
934 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
935 	else
936 		atomic_inc((atomic_t *)&dtab->items);
937 
938 	return 0;
939 }
940 
941 static long dev_map_update_elem(struct bpf_map *map, void *key, void *value,
942 				u64 map_flags)
943 {
944 	return __dev_map_update_elem(current->nsproxy->net_ns,
945 				     map, key, value, map_flags);
946 }
947 
948 static long __dev_map_hash_update_elem(struct net *net, struct bpf_map *map,
949 				       void *key, void *value, u64 map_flags)
950 {
951 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
952 	struct bpf_dtab_netdev *dev, *old_dev;
953 	struct bpf_devmap_val val = {};
954 	u32 idx = *(u32 *)key;
955 	unsigned long flags;
956 	int err = -EEXIST;
957 
958 	/* already verified value_size <= sizeof val */
959 	memcpy(&val, value, map->value_size);
960 
961 	if (unlikely(map_flags > BPF_EXIST || !val.ifindex))
962 		return -EINVAL;
963 
964 	spin_lock_irqsave(&dtab->index_lock, flags);
965 
966 	old_dev = __dev_map_hash_lookup_elem(map, idx);
967 	if (old_dev && (map_flags & BPF_NOEXIST))
968 		goto out_err;
969 
970 	dev = __dev_map_alloc_node(net, dtab, &val, idx);
971 	if (IS_ERR(dev)) {
972 		err = PTR_ERR(dev);
973 		goto out_err;
974 	}
975 
976 	if (old_dev) {
977 		hlist_del_rcu(&old_dev->index_hlist);
978 	} else {
979 		if (dtab->items >= dtab->map.max_entries) {
980 			spin_unlock_irqrestore(&dtab->index_lock, flags);
981 			call_rcu(&dev->rcu, __dev_map_entry_free);
982 			return -E2BIG;
983 		}
984 		dtab->items++;
985 	}
986 
987 	hlist_add_head_rcu(&dev->index_hlist,
988 			   dev_map_index_hash(dtab, idx));
989 	spin_unlock_irqrestore(&dtab->index_lock, flags);
990 
991 	if (old_dev)
992 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
993 
994 	return 0;
995 
996 out_err:
997 	spin_unlock_irqrestore(&dtab->index_lock, flags);
998 	return err;
999 }
1000 
1001 static long dev_map_hash_update_elem(struct bpf_map *map, void *key, void *value,
1002 				     u64 map_flags)
1003 {
1004 	return __dev_map_hash_update_elem(current->nsproxy->net_ns,
1005 					 map, key, value, map_flags);
1006 }
1007 
1008 static long dev_map_redirect(struct bpf_map *map, u64 ifindex, u64 flags)
1009 {
1010 	return __bpf_xdp_redirect_map(map, ifindex, flags,
1011 				      BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS,
1012 				      __dev_map_lookup_elem);
1013 }
1014 
1015 static long dev_hash_map_redirect(struct bpf_map *map, u64 ifindex, u64 flags)
1016 {
1017 	return __bpf_xdp_redirect_map(map, ifindex, flags,
1018 				      BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS,
1019 				      __dev_map_hash_lookup_elem);
1020 }
1021 
1022 static u64 dev_map_mem_usage(const struct bpf_map *map)
1023 {
1024 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
1025 	u64 usage = sizeof(struct bpf_dtab);
1026 
1027 	if (map->map_type == BPF_MAP_TYPE_DEVMAP_HASH)
1028 		usage += (u64)dtab->n_buckets * sizeof(struct hlist_head);
1029 	else
1030 		usage += (u64)map->max_entries * sizeof(struct bpf_dtab_netdev *);
1031 	usage += atomic_read((atomic_t *)&dtab->items) *
1032 			 (u64)sizeof(struct bpf_dtab_netdev);
1033 	return usage;
1034 }
1035 
1036 BTF_ID_LIST_SINGLE(dev_map_btf_ids, struct, bpf_dtab)
1037 const struct bpf_map_ops dev_map_ops = {
1038 	.map_meta_equal = bpf_map_meta_equal,
1039 	.map_alloc = dev_map_alloc,
1040 	.map_free = dev_map_free,
1041 	.map_get_next_key = dev_map_get_next_key,
1042 	.map_lookup_elem = dev_map_lookup_elem,
1043 	.map_update_elem = dev_map_update_elem,
1044 	.map_delete_elem = dev_map_delete_elem,
1045 	.map_check_btf = map_check_no_btf,
1046 	.map_mem_usage = dev_map_mem_usage,
1047 	.map_btf_id = &dev_map_btf_ids[0],
1048 	.map_redirect = dev_map_redirect,
1049 };
1050 
1051 const struct bpf_map_ops dev_map_hash_ops = {
1052 	.map_meta_equal = bpf_map_meta_equal,
1053 	.map_alloc = dev_map_alloc,
1054 	.map_free = dev_map_free,
1055 	.map_get_next_key = dev_map_hash_get_next_key,
1056 	.map_lookup_elem = dev_map_hash_lookup_elem,
1057 	.map_update_elem = dev_map_hash_update_elem,
1058 	.map_delete_elem = dev_map_hash_delete_elem,
1059 	.map_check_btf = map_check_no_btf,
1060 	.map_mem_usage = dev_map_mem_usage,
1061 	.map_btf_id = &dev_map_btf_ids[0],
1062 	.map_redirect = dev_hash_map_redirect,
1063 };
1064 
1065 static void dev_map_hash_remove_netdev(struct bpf_dtab *dtab,
1066 				       struct net_device *netdev)
1067 {
1068 	unsigned long flags;
1069 	u32 i;
1070 
1071 	spin_lock_irqsave(&dtab->index_lock, flags);
1072 	for (i = 0; i < dtab->n_buckets; i++) {
1073 		struct bpf_dtab_netdev *dev;
1074 		struct hlist_head *head;
1075 		struct hlist_node *next;
1076 
1077 		head = dev_map_index_hash(dtab, i);
1078 
1079 		hlist_for_each_entry_safe(dev, next, head, index_hlist) {
1080 			if (netdev != dev->dev)
1081 				continue;
1082 
1083 			dtab->items--;
1084 			hlist_del_rcu(&dev->index_hlist);
1085 			call_rcu(&dev->rcu, __dev_map_entry_free);
1086 		}
1087 	}
1088 	spin_unlock_irqrestore(&dtab->index_lock, flags);
1089 }
1090 
1091 static int dev_map_notification(struct notifier_block *notifier,
1092 				ulong event, void *ptr)
1093 {
1094 	struct net_device *netdev = netdev_notifier_info_to_dev(ptr);
1095 	struct bpf_dtab *dtab;
1096 	int i, cpu;
1097 
1098 	switch (event) {
1099 	case NETDEV_REGISTER:
1100 		if (!netdev->netdev_ops->ndo_xdp_xmit || netdev->xdp_bulkq)
1101 			break;
1102 
1103 		/* will be freed in free_netdev() */
1104 		netdev->xdp_bulkq = alloc_percpu(struct xdp_dev_bulk_queue);
1105 		if (!netdev->xdp_bulkq)
1106 			return NOTIFY_BAD;
1107 
1108 		for_each_possible_cpu(cpu)
1109 			per_cpu_ptr(netdev->xdp_bulkq, cpu)->dev = netdev;
1110 		break;
1111 	case NETDEV_UNREGISTER:
1112 		/* This rcu_read_lock/unlock pair is needed because
1113 		 * dev_map_list is an RCU list AND to ensure a delete
1114 		 * operation does not free a netdev_map entry while we
1115 		 * are comparing it against the netdev being unregistered.
1116 		 */
1117 		rcu_read_lock();
1118 		list_for_each_entry_rcu(dtab, &dev_map_list, list) {
1119 			if (dtab->map.map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
1120 				dev_map_hash_remove_netdev(dtab, netdev);
1121 				continue;
1122 			}
1123 
1124 			for (i = 0; i < dtab->map.max_entries; i++) {
1125 				struct bpf_dtab_netdev *dev, *odev;
1126 
1127 				dev = rcu_dereference(dtab->netdev_map[i]);
1128 				if (!dev || netdev != dev->dev)
1129 					continue;
1130 				odev = unrcu_pointer(cmpxchg(&dtab->netdev_map[i], RCU_INITIALIZER(dev), NULL));
1131 				if (dev == odev) {
1132 					call_rcu(&dev->rcu,
1133 						 __dev_map_entry_free);
1134 					atomic_dec((atomic_t *)&dtab->items);
1135 				}
1136 			}
1137 		}
1138 		rcu_read_unlock();
1139 		break;
1140 	default:
1141 		break;
1142 	}
1143 	return NOTIFY_OK;
1144 }
1145 
1146 static struct notifier_block dev_map_notifier = {
1147 	.notifier_call = dev_map_notification,
1148 };
1149 
1150 static int __init dev_map_init(void)
1151 {
1152 	/* Assure tracepoint shadow struct _bpf_dtab_netdev is in sync */
1153 	BUILD_BUG_ON(offsetof(struct bpf_dtab_netdev, dev) !=
1154 		     offsetof(struct _bpf_dtab_netdev, dev));
1155 	register_netdevice_notifier(&dev_map_notifier);
1156 
1157 	return 0;
1158 }
1159 
1160 subsys_initcall(dev_map_init);
1161