xref: /linux/kernel/bpf/devmap.c (revision 4201c9260a8d3c4ef238e51692a7e9b4e1e29efe)
1 /* Copyright (c) 2017 Covalent IO, Inc. http://covalent.io
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of version 2 of the GNU General Public
5  * License as published by the Free Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful, but
8  * WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10  * General Public License for more details.
11  */
12 
13 /* Devmaps primary use is as a backend map for XDP BPF helper call
14  * bpf_redirect_map(). Because XDP is mostly concerned with performance we
15  * spent some effort to ensure the datapath with redirect maps does not use
16  * any locking. This is a quick note on the details.
17  *
18  * We have three possible paths to get into the devmap control plane bpf
19  * syscalls, bpf programs, and driver side xmit/flush operations. A bpf syscall
20  * will invoke an update, delete, or lookup operation. To ensure updates and
21  * deletes appear atomic from the datapath side xchg() is used to modify the
22  * netdev_map array. Then because the datapath does a lookup into the netdev_map
23  * array (read-only) from an RCU critical section we use call_rcu() to wait for
24  * an rcu grace period before free'ing the old data structures. This ensures the
25  * datapath always has a valid copy. However, the datapath does a "flush"
26  * operation that pushes any pending packets in the driver outside the RCU
27  * critical section. Each bpf_dtab_netdev tracks these pending operations using
28  * an atomic per-cpu bitmap. The bpf_dtab_netdev object will not be destroyed
29  * until all bits are cleared indicating outstanding flush operations have
30  * completed.
31  *
32  * BPF syscalls may race with BPF program calls on any of the update, delete
33  * or lookup operations. As noted above the xchg() operation also keep the
34  * netdev_map consistent in this case. From the devmap side BPF programs
35  * calling into these operations are the same as multiple user space threads
36  * making system calls.
37  *
38  * Finally, any of the above may race with a netdev_unregister notifier. The
39  * unregister notifier must search for net devices in the map structure that
40  * contain a reference to the net device and remove them. This is a two step
41  * process (a) dereference the bpf_dtab_netdev object in netdev_map and (b)
42  * check to see if the ifindex is the same as the net_device being removed.
43  * When removing the dev a cmpxchg() is used to ensure the correct dev is
44  * removed, in the case of a concurrent update or delete operation it is
45  * possible that the initially referenced dev is no longer in the map. As the
46  * notifier hook walks the map we know that new dev references can not be
47  * added by the user because core infrastructure ensures dev_get_by_index()
48  * calls will fail at this point.
49  */
50 #include <linux/bpf.h>
51 #include <net/xdp.h>
52 #include <linux/filter.h>
53 #include <trace/events/xdp.h>
54 
55 #define DEV_CREATE_FLAG_MASK \
56 	(BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)
57 
58 #define DEV_MAP_BULK_SIZE 16
59 struct xdp_bulk_queue {
60 	struct xdp_frame *q[DEV_MAP_BULK_SIZE];
61 	struct net_device *dev_rx;
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 bpf_dtab *dtab;
68 	unsigned int bit;
69 	struct xdp_bulk_queue __percpu *bulkq;
70 	struct rcu_head rcu;
71 };
72 
73 struct bpf_dtab {
74 	struct bpf_map map;
75 	struct bpf_dtab_netdev **netdev_map;
76 	unsigned long __percpu *flush_needed;
77 	struct list_head list;
78 };
79 
80 static DEFINE_SPINLOCK(dev_map_lock);
81 static LIST_HEAD(dev_map_list);
82 
83 static u64 dev_map_bitmap_size(const union bpf_attr *attr)
84 {
85 	return BITS_TO_LONGS((u64) attr->max_entries) * sizeof(unsigned long);
86 }
87 
88 static struct bpf_map *dev_map_alloc(union bpf_attr *attr)
89 {
90 	struct bpf_dtab *dtab;
91 	int err = -EINVAL;
92 	u64 cost;
93 
94 	if (!capable(CAP_NET_ADMIN))
95 		return ERR_PTR(-EPERM);
96 
97 	/* check sanity of attributes */
98 	if (attr->max_entries == 0 || attr->key_size != 4 ||
99 	    attr->value_size != 4 || attr->map_flags & ~DEV_CREATE_FLAG_MASK)
100 		return ERR_PTR(-EINVAL);
101 
102 	dtab = kzalloc(sizeof(*dtab), GFP_USER);
103 	if (!dtab)
104 		return ERR_PTR(-ENOMEM);
105 
106 	bpf_map_init_from_attr(&dtab->map, attr);
107 
108 	/* make sure page count doesn't overflow */
109 	cost = (u64) dtab->map.max_entries * sizeof(struct bpf_dtab_netdev *);
110 	cost += dev_map_bitmap_size(attr) * num_possible_cpus();
111 
112 	/* if map size is larger than memlock limit, reject it */
113 	err = bpf_map_charge_init(&dtab->map.memory, cost);
114 	if (err)
115 		goto free_dtab;
116 
117 	err = -ENOMEM;
118 
119 	/* A per cpu bitfield with a bit per possible net device */
120 	dtab->flush_needed = __alloc_percpu_gfp(dev_map_bitmap_size(attr),
121 						__alignof__(unsigned long),
122 						GFP_KERNEL | __GFP_NOWARN);
123 	if (!dtab->flush_needed)
124 		goto free_charge;
125 
126 	dtab->netdev_map = bpf_map_area_alloc(dtab->map.max_entries *
127 					      sizeof(struct bpf_dtab_netdev *),
128 					      dtab->map.numa_node);
129 	if (!dtab->netdev_map)
130 		goto free_charge;
131 
132 	spin_lock(&dev_map_lock);
133 	list_add_tail_rcu(&dtab->list, &dev_map_list);
134 	spin_unlock(&dev_map_lock);
135 
136 	return &dtab->map;
137 free_charge:
138 	bpf_map_charge_finish(&dtab->map.memory);
139 free_dtab:
140 	free_percpu(dtab->flush_needed);
141 	kfree(dtab);
142 	return ERR_PTR(err);
143 }
144 
145 static void dev_map_free(struct bpf_map *map)
146 {
147 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
148 	int i, cpu;
149 
150 	/* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
151 	 * so the programs (can be more than one that used this map) were
152 	 * disconnected from events. Wait for outstanding critical sections in
153 	 * these programs to complete. The rcu critical section only guarantees
154 	 * no further reads against netdev_map. It does __not__ ensure pending
155 	 * flush operations (if any) are complete.
156 	 */
157 
158 	spin_lock(&dev_map_lock);
159 	list_del_rcu(&dtab->list);
160 	spin_unlock(&dev_map_lock);
161 
162 	bpf_clear_redirect_map(map);
163 	synchronize_rcu();
164 
165 	/* Make sure prior __dev_map_entry_free() have completed. */
166 	rcu_barrier();
167 
168 	/* To ensure all pending flush operations have completed wait for flush
169 	 * bitmap to indicate all flush_needed bits to be zero on _all_ cpus.
170 	 * Because the above synchronize_rcu() ensures the map is disconnected
171 	 * from the program we can assume no new bits will be set.
172 	 */
173 	for_each_online_cpu(cpu) {
174 		unsigned long *bitmap = per_cpu_ptr(dtab->flush_needed, cpu);
175 
176 		while (!bitmap_empty(bitmap, dtab->map.max_entries))
177 			cond_resched();
178 	}
179 
180 	for (i = 0; i < dtab->map.max_entries; i++) {
181 		struct bpf_dtab_netdev *dev;
182 
183 		dev = dtab->netdev_map[i];
184 		if (!dev)
185 			continue;
186 
187 		dev_put(dev->dev);
188 		kfree(dev);
189 	}
190 
191 	free_percpu(dtab->flush_needed);
192 	bpf_map_area_free(dtab->netdev_map);
193 	kfree(dtab);
194 }
195 
196 static int dev_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
197 {
198 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
199 	u32 index = key ? *(u32 *)key : U32_MAX;
200 	u32 *next = next_key;
201 
202 	if (index >= dtab->map.max_entries) {
203 		*next = 0;
204 		return 0;
205 	}
206 
207 	if (index == dtab->map.max_entries - 1)
208 		return -ENOENT;
209 	*next = index + 1;
210 	return 0;
211 }
212 
213 void __dev_map_insert_ctx(struct bpf_map *map, u32 bit)
214 {
215 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
216 	unsigned long *bitmap = this_cpu_ptr(dtab->flush_needed);
217 
218 	__set_bit(bit, bitmap);
219 }
220 
221 static int bq_xmit_all(struct bpf_dtab_netdev *obj,
222 		       struct xdp_bulk_queue *bq, u32 flags,
223 		       bool in_napi_ctx)
224 {
225 	struct net_device *dev = obj->dev;
226 	int sent = 0, drops = 0, err = 0;
227 	int i;
228 
229 	if (unlikely(!bq->count))
230 		return 0;
231 
232 	for (i = 0; i < bq->count; i++) {
233 		struct xdp_frame *xdpf = bq->q[i];
234 
235 		prefetch(xdpf);
236 	}
237 
238 	sent = dev->netdev_ops->ndo_xdp_xmit(dev, bq->count, bq->q, flags);
239 	if (sent < 0) {
240 		err = sent;
241 		sent = 0;
242 		goto error;
243 	}
244 	drops = bq->count - sent;
245 out:
246 	bq->count = 0;
247 
248 	trace_xdp_devmap_xmit(&obj->dtab->map, obj->bit,
249 			      sent, drops, bq->dev_rx, dev, err);
250 	bq->dev_rx = NULL;
251 	return 0;
252 error:
253 	/* If ndo_xdp_xmit fails with an errno, no frames have been
254 	 * xmit'ed and it's our responsibility to them free all.
255 	 */
256 	for (i = 0; i < bq->count; i++) {
257 		struct xdp_frame *xdpf = bq->q[i];
258 
259 		/* RX path under NAPI protection, can return frames faster */
260 		if (likely(in_napi_ctx))
261 			xdp_return_frame_rx_napi(xdpf);
262 		else
263 			xdp_return_frame(xdpf);
264 		drops++;
265 	}
266 	goto out;
267 }
268 
269 /* __dev_map_flush is called from xdp_do_flush_map() which _must_ be signaled
270  * from the driver before returning from its napi->poll() routine. The poll()
271  * routine is called either from busy_poll context or net_rx_action signaled
272  * from NET_RX_SOFTIRQ. Either way the poll routine must complete before the
273  * net device can be torn down. On devmap tear down we ensure the ctx bitmap
274  * is zeroed before completing to ensure all flush operations have completed.
275  */
276 void __dev_map_flush(struct bpf_map *map)
277 {
278 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
279 	unsigned long *bitmap = this_cpu_ptr(dtab->flush_needed);
280 	u32 bit;
281 
282 	for_each_set_bit(bit, bitmap, map->max_entries) {
283 		struct bpf_dtab_netdev *dev = READ_ONCE(dtab->netdev_map[bit]);
284 		struct xdp_bulk_queue *bq;
285 
286 		/* This is possible if the dev entry is removed by user space
287 		 * between xdp redirect and flush op.
288 		 */
289 		if (unlikely(!dev))
290 			continue;
291 
292 		__clear_bit(bit, bitmap);
293 
294 		bq = this_cpu_ptr(dev->bulkq);
295 		bq_xmit_all(dev, bq, XDP_XMIT_FLUSH, true);
296 	}
297 }
298 
299 /* rcu_read_lock (from syscall and BPF contexts) ensures that if a delete and/or
300  * update happens in parallel here a dev_put wont happen until after reading the
301  * ifindex.
302  */
303 struct bpf_dtab_netdev *__dev_map_lookup_elem(struct bpf_map *map, u32 key)
304 {
305 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
306 	struct bpf_dtab_netdev *obj;
307 
308 	if (key >= map->max_entries)
309 		return NULL;
310 
311 	obj = READ_ONCE(dtab->netdev_map[key]);
312 	return obj;
313 }
314 
315 /* Runs under RCU-read-side, plus in softirq under NAPI protection.
316  * Thus, safe percpu variable access.
317  */
318 static int bq_enqueue(struct bpf_dtab_netdev *obj, struct xdp_frame *xdpf,
319 		      struct net_device *dev_rx)
320 
321 {
322 	struct xdp_bulk_queue *bq = this_cpu_ptr(obj->bulkq);
323 
324 	if (unlikely(bq->count == DEV_MAP_BULK_SIZE))
325 		bq_xmit_all(obj, bq, 0, true);
326 
327 	/* Ingress dev_rx will be the same for all xdp_frame's in
328 	 * bulk_queue, because bq stored per-CPU and must be flushed
329 	 * from net_device drivers NAPI func end.
330 	 */
331 	if (!bq->dev_rx)
332 		bq->dev_rx = dev_rx;
333 
334 	bq->q[bq->count++] = xdpf;
335 	return 0;
336 }
337 
338 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_buff *xdp,
339 		    struct net_device *dev_rx)
340 {
341 	struct net_device *dev = dst->dev;
342 	struct xdp_frame *xdpf;
343 	int err;
344 
345 	if (!dev->netdev_ops->ndo_xdp_xmit)
346 		return -EOPNOTSUPP;
347 
348 	err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
349 	if (unlikely(err))
350 		return err;
351 
352 	xdpf = convert_to_xdp_frame(xdp);
353 	if (unlikely(!xdpf))
354 		return -EOVERFLOW;
355 
356 	return bq_enqueue(dst, xdpf, dev_rx);
357 }
358 
359 int dev_map_generic_redirect(struct bpf_dtab_netdev *dst, struct sk_buff *skb,
360 			     struct bpf_prog *xdp_prog)
361 {
362 	int err;
363 
364 	err = xdp_ok_fwd_dev(dst->dev, skb->len);
365 	if (unlikely(err))
366 		return err;
367 	skb->dev = dst->dev;
368 	generic_xdp_tx(skb, xdp_prog);
369 
370 	return 0;
371 }
372 
373 static void *dev_map_lookup_elem(struct bpf_map *map, void *key)
374 {
375 	struct bpf_dtab_netdev *obj = __dev_map_lookup_elem(map, *(u32 *)key);
376 	struct net_device *dev = obj ? obj->dev : NULL;
377 
378 	return dev ? &dev->ifindex : NULL;
379 }
380 
381 static void dev_map_flush_old(struct bpf_dtab_netdev *dev)
382 {
383 	if (dev->dev->netdev_ops->ndo_xdp_xmit) {
384 		struct xdp_bulk_queue *bq;
385 		unsigned long *bitmap;
386 
387 		int cpu;
388 
389 		for_each_online_cpu(cpu) {
390 			bitmap = per_cpu_ptr(dev->dtab->flush_needed, cpu);
391 			__clear_bit(dev->bit, bitmap);
392 
393 			bq = per_cpu_ptr(dev->bulkq, cpu);
394 			bq_xmit_all(dev, bq, XDP_XMIT_FLUSH, false);
395 		}
396 	}
397 }
398 
399 static void __dev_map_entry_free(struct rcu_head *rcu)
400 {
401 	struct bpf_dtab_netdev *dev;
402 
403 	dev = container_of(rcu, struct bpf_dtab_netdev, rcu);
404 	dev_map_flush_old(dev);
405 	free_percpu(dev->bulkq);
406 	dev_put(dev->dev);
407 	kfree(dev);
408 }
409 
410 static int dev_map_delete_elem(struct bpf_map *map, void *key)
411 {
412 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
413 	struct bpf_dtab_netdev *old_dev;
414 	int k = *(u32 *)key;
415 
416 	if (k >= map->max_entries)
417 		return -EINVAL;
418 
419 	/* Use call_rcu() here to ensure any rcu critical sections have
420 	 * completed, but this does not guarantee a flush has happened
421 	 * yet. Because driver side rcu_read_lock/unlock only protects the
422 	 * running XDP program. However, for pending flush operations the
423 	 * dev and ctx are stored in another per cpu map. And additionally,
424 	 * the driver tear down ensures all soft irqs are complete before
425 	 * removing the net device in the case of dev_put equals zero.
426 	 */
427 	old_dev = xchg(&dtab->netdev_map[k], NULL);
428 	if (old_dev)
429 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
430 	return 0;
431 }
432 
433 static int dev_map_update_elem(struct bpf_map *map, void *key, void *value,
434 				u64 map_flags)
435 {
436 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
437 	struct net *net = current->nsproxy->net_ns;
438 	gfp_t gfp = GFP_ATOMIC | __GFP_NOWARN;
439 	struct bpf_dtab_netdev *dev, *old_dev;
440 	u32 i = *(u32 *)key;
441 	u32 ifindex = *(u32 *)value;
442 
443 	if (unlikely(map_flags > BPF_EXIST))
444 		return -EINVAL;
445 	if (unlikely(i >= dtab->map.max_entries))
446 		return -E2BIG;
447 	if (unlikely(map_flags == BPF_NOEXIST))
448 		return -EEXIST;
449 
450 	if (!ifindex) {
451 		dev = NULL;
452 	} else {
453 		dev = kmalloc_node(sizeof(*dev), gfp, map->numa_node);
454 		if (!dev)
455 			return -ENOMEM;
456 
457 		dev->bulkq = __alloc_percpu_gfp(sizeof(*dev->bulkq),
458 						sizeof(void *), gfp);
459 		if (!dev->bulkq) {
460 			kfree(dev);
461 			return -ENOMEM;
462 		}
463 
464 		dev->dev = dev_get_by_index(net, ifindex);
465 		if (!dev->dev) {
466 			free_percpu(dev->bulkq);
467 			kfree(dev);
468 			return -EINVAL;
469 		}
470 
471 		dev->bit = i;
472 		dev->dtab = dtab;
473 	}
474 
475 	/* Use call_rcu() here to ensure rcu critical sections have completed
476 	 * Remembering the driver side flush operation will happen before the
477 	 * net device is removed.
478 	 */
479 	old_dev = xchg(&dtab->netdev_map[i], dev);
480 	if (old_dev)
481 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
482 
483 	return 0;
484 }
485 
486 const struct bpf_map_ops dev_map_ops = {
487 	.map_alloc = dev_map_alloc,
488 	.map_free = dev_map_free,
489 	.map_get_next_key = dev_map_get_next_key,
490 	.map_lookup_elem = dev_map_lookup_elem,
491 	.map_update_elem = dev_map_update_elem,
492 	.map_delete_elem = dev_map_delete_elem,
493 	.map_check_btf = map_check_no_btf,
494 };
495 
496 static int dev_map_notification(struct notifier_block *notifier,
497 				ulong event, void *ptr)
498 {
499 	struct net_device *netdev = netdev_notifier_info_to_dev(ptr);
500 	struct bpf_dtab *dtab;
501 	int i;
502 
503 	switch (event) {
504 	case NETDEV_UNREGISTER:
505 		/* This rcu_read_lock/unlock pair is needed because
506 		 * dev_map_list is an RCU list AND to ensure a delete
507 		 * operation does not free a netdev_map entry while we
508 		 * are comparing it against the netdev being unregistered.
509 		 */
510 		rcu_read_lock();
511 		list_for_each_entry_rcu(dtab, &dev_map_list, list) {
512 			for (i = 0; i < dtab->map.max_entries; i++) {
513 				struct bpf_dtab_netdev *dev, *odev;
514 
515 				dev = READ_ONCE(dtab->netdev_map[i]);
516 				if (!dev || netdev != dev->dev)
517 					continue;
518 				odev = cmpxchg(&dtab->netdev_map[i], dev, NULL);
519 				if (dev == odev)
520 					call_rcu(&dev->rcu,
521 						 __dev_map_entry_free);
522 			}
523 		}
524 		rcu_read_unlock();
525 		break;
526 	default:
527 		break;
528 	}
529 	return NOTIFY_OK;
530 }
531 
532 static struct notifier_block dev_map_notifier = {
533 	.notifier_call = dev_map_notification,
534 };
535 
536 static int __init dev_map_init(void)
537 {
538 	/* Assure tracepoint shadow struct _bpf_dtab_netdev is in sync */
539 	BUILD_BUG_ON(offsetof(struct bpf_dtab_netdev, dev) !=
540 		     offsetof(struct _bpf_dtab_netdev, dev));
541 	register_netdevice_notifier(&dev_map_notifier);
542 	return 0;
543 }
544 
545 subsys_initcall(dev_map_init);
546