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