• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 	unsigned int count;
61 };
62 
63 struct bpf_dtab_netdev {
64 	struct net_device *dev; /* must be first member, due to tracepoint */
65 	struct hlist_node index_hlist;
66 	struct bpf_dtab *dtab;
67 	struct bpf_prog *xdp_prog;
68 	struct rcu_head rcu;
69 	unsigned int idx;
70 	struct bpf_devmap_val val;
71 };
72 
73 struct bpf_dtab {
74 	struct bpf_map map;
75 	struct bpf_dtab_netdev **netdev_map; /* DEVMAP type only */
76 	struct list_head list;
77 
78 	/* these are only used for DEVMAP_HASH type maps */
79 	struct hlist_head *dev_index_head;
80 	spinlock_t index_lock;
81 	unsigned int items;
82 	u32 n_buckets;
83 };
84 
85 static DEFINE_PER_CPU(struct list_head, dev_flush_list);
86 static DEFINE_SPINLOCK(dev_map_lock);
87 static LIST_HEAD(dev_map_list);
88 
dev_map_create_hash(unsigned int entries,int numa_node)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 
dev_map_index_hash(struct bpf_dtab * dtab,int idx)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 
dev_map_init_map(struct bpf_dtab * dtab,union bpf_attr * attr)109 static int dev_map_init_map(struct bpf_dtab *dtab, union bpf_attr *attr)
110 {
111 	u32 valsize = attr->value_size;
112 	u64 cost = 0;
113 	int err;
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 	/* Lookup returns a pointer straight to dev->ifindex, so make sure the
126 	 * verifier prevents writes from the BPF side
127 	 */
128 	attr->map_flags |= BPF_F_RDONLY_PROG;
129 
130 
131 	bpf_map_init_from_attr(&dtab->map, attr);
132 
133 	if (attr->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
134 		/* hash table size must be power of 2; roundup_pow_of_two() can
135 		 * overflow into UB on 32-bit arches, so check that first
136 		 */
137 		if (dtab->map.max_entries > 1UL << 31)
138 			return -EINVAL;
139 
140 		dtab->n_buckets = roundup_pow_of_two(dtab->map.max_entries);
141 		cost += (u64) sizeof(struct hlist_head) * dtab->n_buckets;
142 	} else {
143 		cost += (u64) dtab->map.max_entries * sizeof(struct bpf_dtab_netdev *);
144 	}
145 
146 	/* if map size is larger than memlock limit, reject it */
147 	err = bpf_map_charge_init(&dtab->map.memory, cost);
148 	if (err)
149 		return -EINVAL;
150 
151 	if (attr->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
152 		dtab->dev_index_head = dev_map_create_hash(dtab->n_buckets,
153 							   dtab->map.numa_node);
154 		if (!dtab->dev_index_head)
155 			goto free_charge;
156 
157 		spin_lock_init(&dtab->index_lock);
158 	} else {
159 		dtab->netdev_map = bpf_map_area_alloc((u64) dtab->map.max_entries *
160 						      sizeof(struct bpf_dtab_netdev *),
161 						      dtab->map.numa_node);
162 		if (!dtab->netdev_map)
163 			goto free_charge;
164 	}
165 
166 	return 0;
167 
168 free_charge:
169 	bpf_map_charge_finish(&dtab->map.memory);
170 	return -ENOMEM;
171 }
172 
dev_map_alloc(union bpf_attr * attr)173 static struct bpf_map *dev_map_alloc(union bpf_attr *attr)
174 {
175 	struct bpf_dtab *dtab;
176 	int err;
177 
178 	if (!capable(CAP_NET_ADMIN))
179 		return ERR_PTR(-EPERM);
180 
181 	dtab = kzalloc(sizeof(*dtab), GFP_USER);
182 	if (!dtab)
183 		return ERR_PTR(-ENOMEM);
184 
185 	err = dev_map_init_map(dtab, attr);
186 	if (err) {
187 		kfree(dtab);
188 		return ERR_PTR(err);
189 	}
190 
191 	spin_lock(&dev_map_lock);
192 	list_add_tail_rcu(&dtab->list, &dev_map_list);
193 	spin_unlock(&dev_map_lock);
194 
195 	return &dtab->map;
196 }
197 
dev_map_free(struct bpf_map * map)198 static void dev_map_free(struct bpf_map *map)
199 {
200 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
201 	u32 i;
202 
203 	/* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
204 	 * so the programs (can be more than one that used this map) were
205 	 * disconnected from events. The following synchronize_rcu() guarantees
206 	 * both rcu read critical sections complete and waits for
207 	 * preempt-disable regions (NAPI being the relevant context here) so we
208 	 * are certain there will be no further reads against the netdev_map and
209 	 * all flush operations are complete. Flush operations can only be done
210 	 * from NAPI context for this reason.
211 	 */
212 
213 	spin_lock(&dev_map_lock);
214 	list_del_rcu(&dtab->list);
215 	spin_unlock(&dev_map_lock);
216 
217 	bpf_clear_redirect_map(map);
218 	synchronize_rcu();
219 
220 	/* Make sure prior __dev_map_entry_free() have completed. */
221 	rcu_barrier();
222 
223 	if (dtab->map.map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
224 		for (i = 0; i < dtab->n_buckets; i++) {
225 			struct bpf_dtab_netdev *dev;
226 			struct hlist_head *head;
227 			struct hlist_node *next;
228 
229 			head = dev_map_index_hash(dtab, i);
230 
231 			hlist_for_each_entry_safe(dev, next, head, index_hlist) {
232 				hlist_del_rcu(&dev->index_hlist);
233 				if (dev->xdp_prog)
234 					bpf_prog_put(dev->xdp_prog);
235 				dev_put(dev->dev);
236 				kfree(dev);
237 			}
238 		}
239 
240 		bpf_map_area_free(dtab->dev_index_head);
241 	} else {
242 		for (i = 0; i < dtab->map.max_entries; i++) {
243 			struct bpf_dtab_netdev *dev;
244 
245 			dev = dtab->netdev_map[i];
246 			if (!dev)
247 				continue;
248 
249 			if (dev->xdp_prog)
250 				bpf_prog_put(dev->xdp_prog);
251 			dev_put(dev->dev);
252 			kfree(dev);
253 		}
254 
255 		bpf_map_area_free(dtab->netdev_map);
256 	}
257 
258 	kfree(dtab);
259 }
260 
dev_map_get_next_key(struct bpf_map * map,void * key,void * next_key)261 static int dev_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
262 {
263 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
264 	u32 index = key ? *(u32 *)key : U32_MAX;
265 	u32 *next = next_key;
266 
267 	if (index >= dtab->map.max_entries) {
268 		*next = 0;
269 		return 0;
270 	}
271 
272 	if (index == dtab->map.max_entries - 1)
273 		return -ENOENT;
274 	*next = index + 1;
275 	return 0;
276 }
277 
__dev_map_hash_lookup_elem(struct bpf_map * map,u32 key)278 struct bpf_dtab_netdev *__dev_map_hash_lookup_elem(struct bpf_map *map, u32 key)
279 {
280 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
281 	struct hlist_head *head = dev_map_index_hash(dtab, key);
282 	struct bpf_dtab_netdev *dev;
283 
284 	hlist_for_each_entry_rcu(dev, head, index_hlist,
285 				 lockdep_is_held(&dtab->index_lock))
286 		if (dev->idx == key)
287 			return dev;
288 
289 	return NULL;
290 }
291 
dev_map_hash_get_next_key(struct bpf_map * map,void * key,void * next_key)292 static int dev_map_hash_get_next_key(struct bpf_map *map, void *key,
293 				    void *next_key)
294 {
295 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
296 	u32 idx, *next = next_key;
297 	struct bpf_dtab_netdev *dev, *next_dev;
298 	struct hlist_head *head;
299 	int i = 0;
300 
301 	if (!key)
302 		goto find_first;
303 
304 	idx = *(u32 *)key;
305 
306 	dev = __dev_map_hash_lookup_elem(map, idx);
307 	if (!dev)
308 		goto find_first;
309 
310 	next_dev = hlist_entry_safe(rcu_dereference_raw(hlist_next_rcu(&dev->index_hlist)),
311 				    struct bpf_dtab_netdev, index_hlist);
312 
313 	if (next_dev) {
314 		*next = next_dev->idx;
315 		return 0;
316 	}
317 
318 	i = idx & (dtab->n_buckets - 1);
319 	i++;
320 
321  find_first:
322 	for (; i < dtab->n_buckets; i++) {
323 		head = dev_map_index_hash(dtab, i);
324 
325 		next_dev = hlist_entry_safe(rcu_dereference_raw(hlist_first_rcu(head)),
326 					    struct bpf_dtab_netdev,
327 					    index_hlist);
328 		if (next_dev) {
329 			*next = next_dev->idx;
330 			return 0;
331 		}
332 	}
333 
334 	return -ENOENT;
335 }
336 
dev_map_can_have_prog(struct bpf_map * map)337 bool dev_map_can_have_prog(struct bpf_map *map)
338 {
339 	if ((map->map_type == BPF_MAP_TYPE_DEVMAP ||
340 	     map->map_type == BPF_MAP_TYPE_DEVMAP_HASH) &&
341 	    map->value_size != offsetofend(struct bpf_devmap_val, ifindex))
342 		return true;
343 
344 	return false;
345 }
346 
bq_xmit_all(struct xdp_dev_bulk_queue * bq,u32 flags)347 static void bq_xmit_all(struct xdp_dev_bulk_queue *bq, u32 flags)
348 {
349 	struct net_device *dev = bq->dev;
350 	int sent = 0, drops = 0, err = 0;
351 	int i;
352 
353 	if (unlikely(!bq->count))
354 		return;
355 
356 	for (i = 0; i < bq->count; i++) {
357 		struct xdp_frame *xdpf = bq->q[i];
358 
359 		prefetch(xdpf);
360 	}
361 
362 	sent = dev->netdev_ops->ndo_xdp_xmit(dev, bq->count, bq->q, flags);
363 	if (sent < 0) {
364 		err = sent;
365 		sent = 0;
366 		goto error;
367 	}
368 	drops = bq->count - sent;
369 out:
370 	bq->count = 0;
371 
372 	trace_xdp_devmap_xmit(bq->dev_rx, dev, sent, drops, err);
373 	bq->dev_rx = NULL;
374 	__list_del_clearprev(&bq->flush_node);
375 	return;
376 error:
377 	/* If ndo_xdp_xmit fails with an errno, no frames have been
378 	 * xmit'ed and it's our responsibility to them free all.
379 	 */
380 	for (i = 0; i < bq->count; i++) {
381 		struct xdp_frame *xdpf = bq->q[i];
382 
383 		xdp_return_frame_rx_napi(xdpf);
384 		drops++;
385 	}
386 	goto out;
387 }
388 
389 /* __dev_flush is called from xdp_do_flush() which _must_ be signaled
390  * from the driver before returning from its napi->poll() routine. The poll()
391  * routine is called either from busy_poll context or net_rx_action signaled
392  * from NET_RX_SOFTIRQ. Either way the poll routine must complete before the
393  * net device can be torn down. On devmap tear down we ensure the flush list
394  * is empty before completing to ensure all flush operations have completed.
395  * When drivers update the bpf program they may need to ensure any flush ops
396  * are also complete. Using synchronize_rcu or call_rcu will suffice for this
397  * because both wait for napi context to exit.
398  */
__dev_flush(void)399 void __dev_flush(void)
400 {
401 	struct list_head *flush_list = this_cpu_ptr(&dev_flush_list);
402 	struct xdp_dev_bulk_queue *bq, *tmp;
403 
404 	list_for_each_entry_safe(bq, tmp, flush_list, flush_node)
405 		bq_xmit_all(bq, XDP_XMIT_FLUSH);
406 }
407 
408 /* rcu_read_lock (from syscall and BPF contexts) ensures that if a delete and/or
409  * update happens in parallel here a dev_put wont happen until after reading the
410  * ifindex.
411  */
__dev_map_lookup_elem(struct bpf_map * map,u32 key)412 struct bpf_dtab_netdev *__dev_map_lookup_elem(struct bpf_map *map, u32 key)
413 {
414 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
415 	struct bpf_dtab_netdev *obj;
416 
417 	if (key >= map->max_entries)
418 		return NULL;
419 
420 	obj = READ_ONCE(dtab->netdev_map[key]);
421 	return obj;
422 }
423 
424 /* Runs under RCU-read-side, plus in softirq under NAPI protection.
425  * Thus, safe percpu variable access.
426  */
bq_enqueue(struct net_device * dev,struct xdp_frame * xdpf,struct net_device * dev_rx)427 static void bq_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
428 		       struct net_device *dev_rx)
429 {
430 	struct list_head *flush_list = this_cpu_ptr(&dev_flush_list);
431 	struct xdp_dev_bulk_queue *bq = this_cpu_ptr(dev->xdp_bulkq);
432 
433 	if (unlikely(bq->count == DEV_MAP_BULK_SIZE))
434 		bq_xmit_all(bq, 0);
435 
436 	/* Ingress dev_rx will be the same for all xdp_frame's in
437 	 * bulk_queue, because bq stored per-CPU and must be flushed
438 	 * from net_device drivers NAPI func end.
439 	 */
440 	if (!bq->dev_rx)
441 		bq->dev_rx = dev_rx;
442 
443 	bq->q[bq->count++] = xdpf;
444 
445 	if (!bq->flush_node.prev)
446 		list_add(&bq->flush_node, flush_list);
447 }
448 
__xdp_enqueue(struct net_device * dev,struct xdp_buff * xdp,struct net_device * dev_rx)449 static inline int __xdp_enqueue(struct net_device *dev, struct xdp_buff *xdp,
450 			       struct net_device *dev_rx)
451 {
452 	struct xdp_frame *xdpf;
453 	int err;
454 
455 	if (!dev->netdev_ops->ndo_xdp_xmit)
456 		return -EOPNOTSUPP;
457 
458 	err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
459 	if (unlikely(err))
460 		return err;
461 
462 	xdpf = xdp_convert_buff_to_frame(xdp);
463 	if (unlikely(!xdpf))
464 		return -EOVERFLOW;
465 
466 	bq_enqueue(dev, xdpf, dev_rx);
467 	return 0;
468 }
469 
dev_map_run_prog(struct net_device * dev,struct xdp_buff * xdp,struct bpf_prog * xdp_prog)470 static struct xdp_buff *dev_map_run_prog(struct net_device *dev,
471 					 struct xdp_buff *xdp,
472 					 struct bpf_prog *xdp_prog)
473 {
474 	struct xdp_txq_info txq = { .dev = dev };
475 	u32 act;
476 
477 	xdp_set_data_meta_invalid(xdp);
478 	xdp->txq = &txq;
479 
480 	act = bpf_prog_run_xdp(xdp_prog, xdp);
481 	switch (act) {
482 	case XDP_PASS:
483 		return xdp;
484 	case XDP_DROP:
485 		break;
486 	default:
487 		bpf_warn_invalid_xdp_action(act);
488 		fallthrough;
489 	case XDP_ABORTED:
490 		trace_xdp_exception(dev, xdp_prog, act);
491 		break;
492 	}
493 
494 	xdp_return_buff(xdp);
495 	return NULL;
496 }
497 
dev_xdp_enqueue(struct net_device * dev,struct xdp_buff * xdp,struct net_device * dev_rx)498 int dev_xdp_enqueue(struct net_device *dev, struct xdp_buff *xdp,
499 		    struct net_device *dev_rx)
500 {
501 	return __xdp_enqueue(dev, xdp, dev_rx);
502 }
503 
dev_map_enqueue(struct bpf_dtab_netdev * dst,struct xdp_buff * xdp,struct net_device * dev_rx)504 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_buff *xdp,
505 		    struct net_device *dev_rx)
506 {
507 	struct net_device *dev = dst->dev;
508 
509 	if (dst->xdp_prog) {
510 		xdp = dev_map_run_prog(dev, xdp, dst->xdp_prog);
511 		if (!xdp)
512 			return 0;
513 	}
514 	return __xdp_enqueue(dev, xdp, dev_rx);
515 }
516 
dev_map_generic_redirect(struct bpf_dtab_netdev * dst,struct sk_buff * skb,struct bpf_prog * xdp_prog)517 int dev_map_generic_redirect(struct bpf_dtab_netdev *dst, struct sk_buff *skb,
518 			     struct bpf_prog *xdp_prog)
519 {
520 	int err;
521 
522 	err = xdp_ok_fwd_dev(dst->dev, skb->len);
523 	if (unlikely(err))
524 		return err;
525 	skb->dev = dst->dev;
526 	generic_xdp_tx(skb, xdp_prog);
527 
528 	return 0;
529 }
530 
dev_map_lookup_elem(struct bpf_map * map,void * key)531 static void *dev_map_lookup_elem(struct bpf_map *map, void *key)
532 {
533 	struct bpf_dtab_netdev *obj = __dev_map_lookup_elem(map, *(u32 *)key);
534 
535 	return obj ? &obj->val : NULL;
536 }
537 
dev_map_hash_lookup_elem(struct bpf_map * map,void * key)538 static void *dev_map_hash_lookup_elem(struct bpf_map *map, void *key)
539 {
540 	struct bpf_dtab_netdev *obj = __dev_map_hash_lookup_elem(map,
541 								*(u32 *)key);
542 	return obj ? &obj->val : NULL;
543 }
544 
__dev_map_entry_free(struct rcu_head * rcu)545 static void __dev_map_entry_free(struct rcu_head *rcu)
546 {
547 	struct bpf_dtab_netdev *dev;
548 
549 	dev = container_of(rcu, struct bpf_dtab_netdev, rcu);
550 	if (dev->xdp_prog)
551 		bpf_prog_put(dev->xdp_prog);
552 	dev_put(dev->dev);
553 	kfree(dev);
554 }
555 
dev_map_delete_elem(struct bpf_map * map,void * key)556 static int dev_map_delete_elem(struct bpf_map *map, void *key)
557 {
558 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
559 	struct bpf_dtab_netdev *old_dev;
560 	u32 k = *(u32 *)key;
561 
562 	if (k >= map->max_entries)
563 		return -EINVAL;
564 
565 	/* Use call_rcu() here to ensure any rcu critical sections have
566 	 * completed as well as any flush operations because call_rcu
567 	 * will wait for preempt-disable region to complete, NAPI in this
568 	 * context.  And additionally, the driver tear down ensures all
569 	 * soft irqs are complete before removing the net device in the
570 	 * case of dev_put equals zero.
571 	 */
572 	old_dev = xchg(&dtab->netdev_map[k], NULL);
573 	if (old_dev)
574 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
575 	return 0;
576 }
577 
dev_map_hash_delete_elem(struct bpf_map * map,void * key)578 static int dev_map_hash_delete_elem(struct bpf_map *map, void *key)
579 {
580 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
581 	struct bpf_dtab_netdev *old_dev;
582 	u32 k = *(u32 *)key;
583 	unsigned long flags;
584 	int ret = -ENOENT;
585 
586 	spin_lock_irqsave(&dtab->index_lock, flags);
587 
588 	old_dev = __dev_map_hash_lookup_elem(map, k);
589 	if (old_dev) {
590 		dtab->items--;
591 		hlist_del_init_rcu(&old_dev->index_hlist);
592 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
593 		ret = 0;
594 	}
595 	spin_unlock_irqrestore(&dtab->index_lock, flags);
596 
597 	return ret;
598 }
599 
__dev_map_alloc_node(struct net * net,struct bpf_dtab * dtab,struct bpf_devmap_val * val,unsigned int idx)600 static struct bpf_dtab_netdev *__dev_map_alloc_node(struct net *net,
601 						    struct bpf_dtab *dtab,
602 						    struct bpf_devmap_val *val,
603 						    unsigned int idx)
604 {
605 	struct bpf_prog *prog = NULL;
606 	struct bpf_dtab_netdev *dev;
607 
608 	dev = kmalloc_node(sizeof(*dev), GFP_ATOMIC | __GFP_NOWARN,
609 			   dtab->map.numa_node);
610 	if (!dev)
611 		return ERR_PTR(-ENOMEM);
612 
613 	dev->dev = dev_get_by_index(net, val->ifindex);
614 	if (!dev->dev)
615 		goto err_out;
616 
617 	if (val->bpf_prog.fd > 0) {
618 		prog = bpf_prog_get_type_dev(val->bpf_prog.fd,
619 					     BPF_PROG_TYPE_XDP, false);
620 		if (IS_ERR(prog))
621 			goto err_put_dev;
622 		if (prog->expected_attach_type != BPF_XDP_DEVMAP)
623 			goto err_put_prog;
624 	}
625 
626 	dev->idx = idx;
627 	dev->dtab = dtab;
628 	if (prog) {
629 		dev->xdp_prog = prog;
630 		dev->val.bpf_prog.id = prog->aux->id;
631 	} else {
632 		dev->xdp_prog = NULL;
633 		dev->val.bpf_prog.id = 0;
634 	}
635 	dev->val.ifindex = val->ifindex;
636 
637 	return dev;
638 err_put_prog:
639 	bpf_prog_put(prog);
640 err_put_dev:
641 	dev_put(dev->dev);
642 err_out:
643 	kfree(dev);
644 	return ERR_PTR(-EINVAL);
645 }
646 
__dev_map_update_elem(struct net * net,struct bpf_map * map,void * key,void * value,u64 map_flags)647 static int __dev_map_update_elem(struct net *net, struct bpf_map *map,
648 				 void *key, void *value, u64 map_flags)
649 {
650 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
651 	struct bpf_dtab_netdev *dev, *old_dev;
652 	struct bpf_devmap_val val = {};
653 	u32 i = *(u32 *)key;
654 
655 	if (unlikely(map_flags > BPF_EXIST))
656 		return -EINVAL;
657 	if (unlikely(i >= dtab->map.max_entries))
658 		return -E2BIG;
659 	if (unlikely(map_flags == BPF_NOEXIST))
660 		return -EEXIST;
661 
662 	/* already verified value_size <= sizeof val */
663 	memcpy(&val, value, map->value_size);
664 
665 	if (!val.ifindex) {
666 		dev = NULL;
667 		/* can not specify fd if ifindex is 0 */
668 		if (val.bpf_prog.fd > 0)
669 			return -EINVAL;
670 	} else {
671 		dev = __dev_map_alloc_node(net, dtab, &val, i);
672 		if (IS_ERR(dev))
673 			return PTR_ERR(dev);
674 	}
675 
676 	/* Use call_rcu() here to ensure rcu critical sections have completed
677 	 * Remembering the driver side flush operation will happen before the
678 	 * net device is removed.
679 	 */
680 	old_dev = xchg(&dtab->netdev_map[i], dev);
681 	if (old_dev)
682 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
683 
684 	return 0;
685 }
686 
dev_map_update_elem(struct bpf_map * map,void * key,void * value,u64 map_flags)687 static int dev_map_update_elem(struct bpf_map *map, void *key, void *value,
688 			       u64 map_flags)
689 {
690 	return __dev_map_update_elem(current->nsproxy->net_ns,
691 				     map, key, value, map_flags);
692 }
693 
__dev_map_hash_update_elem(struct net * net,struct bpf_map * map,void * key,void * value,u64 map_flags)694 static int __dev_map_hash_update_elem(struct net *net, struct bpf_map *map,
695 				     void *key, void *value, u64 map_flags)
696 {
697 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
698 	struct bpf_dtab_netdev *dev, *old_dev;
699 	struct bpf_devmap_val val = {};
700 	u32 idx = *(u32 *)key;
701 	unsigned long flags;
702 	int err = -EEXIST;
703 
704 	/* already verified value_size <= sizeof val */
705 	memcpy(&val, value, map->value_size);
706 
707 	if (unlikely(map_flags > BPF_EXIST || !val.ifindex))
708 		return -EINVAL;
709 
710 	spin_lock_irqsave(&dtab->index_lock, flags);
711 
712 	old_dev = __dev_map_hash_lookup_elem(map, idx);
713 	if (old_dev && (map_flags & BPF_NOEXIST))
714 		goto out_err;
715 
716 	dev = __dev_map_alloc_node(net, dtab, &val, idx);
717 	if (IS_ERR(dev)) {
718 		err = PTR_ERR(dev);
719 		goto out_err;
720 	}
721 
722 	if (old_dev) {
723 		hlist_del_rcu(&old_dev->index_hlist);
724 	} else {
725 		if (dtab->items >= dtab->map.max_entries) {
726 			spin_unlock_irqrestore(&dtab->index_lock, flags);
727 			call_rcu(&dev->rcu, __dev_map_entry_free);
728 			return -E2BIG;
729 		}
730 		dtab->items++;
731 	}
732 
733 	hlist_add_head_rcu(&dev->index_hlist,
734 			   dev_map_index_hash(dtab, idx));
735 	spin_unlock_irqrestore(&dtab->index_lock, flags);
736 
737 	if (old_dev)
738 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
739 
740 	return 0;
741 
742 out_err:
743 	spin_unlock_irqrestore(&dtab->index_lock, flags);
744 	return err;
745 }
746 
dev_map_hash_update_elem(struct bpf_map * map,void * key,void * value,u64 map_flags)747 static int dev_map_hash_update_elem(struct bpf_map *map, void *key, void *value,
748 				   u64 map_flags)
749 {
750 	return __dev_map_hash_update_elem(current->nsproxy->net_ns,
751 					 map, key, value, map_flags);
752 }
753 
754 static int dev_map_btf_id;
755 const struct bpf_map_ops dev_map_ops = {
756 	.map_meta_equal = bpf_map_meta_equal,
757 	.map_alloc = dev_map_alloc,
758 	.map_free = dev_map_free,
759 	.map_get_next_key = dev_map_get_next_key,
760 	.map_lookup_elem = dev_map_lookup_elem,
761 	.map_update_elem = dev_map_update_elem,
762 	.map_delete_elem = dev_map_delete_elem,
763 	.map_check_btf = map_check_no_btf,
764 	.map_btf_name = "bpf_dtab",
765 	.map_btf_id = &dev_map_btf_id,
766 };
767 
768 static int dev_map_hash_map_btf_id;
769 const struct bpf_map_ops dev_map_hash_ops = {
770 	.map_meta_equal = bpf_map_meta_equal,
771 	.map_alloc = dev_map_alloc,
772 	.map_free = dev_map_free,
773 	.map_get_next_key = dev_map_hash_get_next_key,
774 	.map_lookup_elem = dev_map_hash_lookup_elem,
775 	.map_update_elem = dev_map_hash_update_elem,
776 	.map_delete_elem = dev_map_hash_delete_elem,
777 	.map_check_btf = map_check_no_btf,
778 	.map_btf_name = "bpf_dtab",
779 	.map_btf_id = &dev_map_hash_map_btf_id,
780 };
781 
dev_map_hash_remove_netdev(struct bpf_dtab * dtab,struct net_device * netdev)782 static void dev_map_hash_remove_netdev(struct bpf_dtab *dtab,
783 				       struct net_device *netdev)
784 {
785 	unsigned long flags;
786 	u32 i;
787 
788 	spin_lock_irqsave(&dtab->index_lock, flags);
789 	for (i = 0; i < dtab->n_buckets; i++) {
790 		struct bpf_dtab_netdev *dev;
791 		struct hlist_head *head;
792 		struct hlist_node *next;
793 
794 		head = dev_map_index_hash(dtab, i);
795 
796 		hlist_for_each_entry_safe(dev, next, head, index_hlist) {
797 			if (netdev != dev->dev)
798 				continue;
799 
800 			dtab->items--;
801 			hlist_del_rcu(&dev->index_hlist);
802 			call_rcu(&dev->rcu, __dev_map_entry_free);
803 		}
804 	}
805 	spin_unlock_irqrestore(&dtab->index_lock, flags);
806 }
807 
dev_map_notification(struct notifier_block * notifier,ulong event,void * ptr)808 static int dev_map_notification(struct notifier_block *notifier,
809 				ulong event, void *ptr)
810 {
811 	struct net_device *netdev = netdev_notifier_info_to_dev(ptr);
812 	struct bpf_dtab *dtab;
813 	int i, cpu;
814 
815 	switch (event) {
816 	case NETDEV_REGISTER:
817 		if (!netdev->netdev_ops->ndo_xdp_xmit || netdev->xdp_bulkq)
818 			break;
819 
820 		/* will be freed in free_netdev() */
821 		netdev->xdp_bulkq = alloc_percpu(struct xdp_dev_bulk_queue);
822 		if (!netdev->xdp_bulkq)
823 			return NOTIFY_BAD;
824 
825 		for_each_possible_cpu(cpu)
826 			per_cpu_ptr(netdev->xdp_bulkq, cpu)->dev = netdev;
827 		break;
828 	case NETDEV_UNREGISTER:
829 		/* This rcu_read_lock/unlock pair is needed because
830 		 * dev_map_list is an RCU list AND to ensure a delete
831 		 * operation does not free a netdev_map entry while we
832 		 * are comparing it against the netdev being unregistered.
833 		 */
834 		rcu_read_lock();
835 		list_for_each_entry_rcu(dtab, &dev_map_list, list) {
836 			if (dtab->map.map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
837 				dev_map_hash_remove_netdev(dtab, netdev);
838 				continue;
839 			}
840 
841 			for (i = 0; i < dtab->map.max_entries; i++) {
842 				struct bpf_dtab_netdev *dev, *odev;
843 
844 				dev = READ_ONCE(dtab->netdev_map[i]);
845 				if (!dev || netdev != dev->dev)
846 					continue;
847 				odev = cmpxchg(&dtab->netdev_map[i], dev, NULL);
848 				if (dev == odev)
849 					call_rcu(&dev->rcu,
850 						 __dev_map_entry_free);
851 			}
852 		}
853 		rcu_read_unlock();
854 		break;
855 	default:
856 		break;
857 	}
858 	return NOTIFY_OK;
859 }
860 
861 static struct notifier_block dev_map_notifier = {
862 	.notifier_call = dev_map_notification,
863 };
864 
dev_map_init(void)865 static int __init dev_map_init(void)
866 {
867 	int cpu;
868 
869 	/* Assure tracepoint shadow struct _bpf_dtab_netdev is in sync */
870 	BUILD_BUG_ON(offsetof(struct bpf_dtab_netdev, dev) !=
871 		     offsetof(struct _bpf_dtab_netdev, dev));
872 	register_netdevice_notifier(&dev_map_notifier);
873 
874 	for_each_possible_cpu(cpu)
875 		INIT_LIST_HEAD(&per_cpu(dev_flush_list, cpu));
876 	return 0;
877 }
878 
879 subsys_initcall(dev_map_init);
880