xref: /linux-6.15/kernel/bpf/devmap.c (revision f26de110)
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 <linux/jhash.h>
52 #include <linux/filter.h>
53 #include <linux/rculist_nulls.h>
54 #include "percpu_freelist.h"
55 #include "bpf_lru_list.h"
56 #include "map_in_map.h"
57 
58 struct bpf_dtab_netdev {
59 	struct net_device *dev;
60 	int key;
61 	struct rcu_head rcu;
62 	struct bpf_dtab *dtab;
63 };
64 
65 struct bpf_dtab {
66 	struct bpf_map map;
67 	struct bpf_dtab_netdev **netdev_map;
68 	unsigned long int __percpu *flush_needed;
69 	struct list_head list;
70 };
71 
72 static DEFINE_SPINLOCK(dev_map_lock);
73 static LIST_HEAD(dev_map_list);
74 
75 static struct bpf_map *dev_map_alloc(union bpf_attr *attr)
76 {
77 	struct bpf_dtab *dtab;
78 	u64 cost;
79 	int err;
80 
81 	/* check sanity of attributes */
82 	if (attr->max_entries == 0 || attr->key_size != 4 ||
83 	    attr->value_size != 4 || attr->map_flags)
84 		return ERR_PTR(-EINVAL);
85 
86 	/* if value_size is bigger, the user space won't be able to
87 	 * access the elements.
88 	 */
89 	if (attr->value_size > KMALLOC_MAX_SIZE)
90 		return ERR_PTR(-E2BIG);
91 
92 	dtab = kzalloc(sizeof(*dtab), GFP_USER);
93 	if (!dtab)
94 		return ERR_PTR(-ENOMEM);
95 
96 	/* mandatory map attributes */
97 	dtab->map.map_type = attr->map_type;
98 	dtab->map.key_size = attr->key_size;
99 	dtab->map.value_size = attr->value_size;
100 	dtab->map.max_entries = attr->max_entries;
101 	dtab->map.map_flags = attr->map_flags;
102 
103 	err = -ENOMEM;
104 
105 	/* make sure page count doesn't overflow */
106 	cost = (u64) dtab->map.max_entries * sizeof(struct bpf_dtab_netdev *);
107 	cost += BITS_TO_LONGS(attr->max_entries) * sizeof(unsigned long);
108 	if (cost >= U32_MAX - PAGE_SIZE)
109 		goto free_dtab;
110 
111 	dtab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
112 
113 	/* if map size is larger than memlock limit, reject it early */
114 	err = bpf_map_precharge_memlock(dtab->map.pages);
115 	if (err)
116 		goto free_dtab;
117 
118 	err = -ENOMEM;
119 	/* A per cpu bitfield with a bit per possible net device */
120 	dtab->flush_needed = __alloc_percpu(
121 				BITS_TO_LONGS(attr->max_entries) *
122 				sizeof(unsigned long),
123 				__alignof__(unsigned long));
124 	if (!dtab->flush_needed)
125 		goto free_dtab;
126 
127 	dtab->netdev_map = bpf_map_area_alloc(dtab->map.max_entries *
128 					      sizeof(struct bpf_dtab_netdev *));
129 	if (!dtab->netdev_map)
130 		goto free_dtab;
131 
132 	spin_lock(&dev_map_lock);
133 	list_add_tail_rcu(&dtab->list, &dev_map_list);
134 	spin_unlock(&dev_map_lock);
135 	return &dtab->map;
136 
137 free_dtab:
138 	free_percpu(dtab->flush_needed);
139 	kfree(dtab);
140 	return ERR_PTR(err);
141 }
142 
143 static void dev_map_free(struct bpf_map *map)
144 {
145 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
146 	int i, cpu;
147 
148 	/* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
149 	 * so the programs (can be more than one that used this map) were
150 	 * disconnected from events. Wait for outstanding critical sections in
151 	 * these programs to complete. The rcu critical section only guarantees
152 	 * no further reads against netdev_map. It does __not__ ensure pending
153 	 * flush operations (if any) are complete.
154 	 */
155 	synchronize_rcu();
156 
157 	/* To ensure all pending flush operations have completed wait for flush
158 	 * bitmap to indicate all flush_needed bits to be zero on _all_ cpus.
159 	 * Because the above synchronize_rcu() ensures the map is disconnected
160 	 * from the program we can assume no new bits will be set.
161 	 */
162 	for_each_online_cpu(cpu) {
163 		unsigned long *bitmap = per_cpu_ptr(dtab->flush_needed, cpu);
164 
165 		while (!bitmap_empty(bitmap, dtab->map.max_entries))
166 			cpu_relax();
167 	}
168 
169 	/* Although we should no longer have datapath or bpf syscall operations
170 	 * at this point we we can still race with netdev notifier, hence the
171 	 * lock.
172 	 */
173 	for (i = 0; i < dtab->map.max_entries; i++) {
174 		struct bpf_dtab_netdev *dev;
175 
176 		dev = dtab->netdev_map[i];
177 		if (!dev)
178 			continue;
179 
180 		dev_put(dev->dev);
181 		kfree(dev);
182 	}
183 
184 	/* At this point bpf program is detached and all pending operations
185 	 * _must_ be complete
186 	 */
187 	spin_lock(&dev_map_lock);
188 	list_del_rcu(&dtab->list);
189 	spin_unlock(&dev_map_lock);
190 	free_percpu(dtab->flush_needed);
191 	bpf_map_area_free(dtab->netdev_map);
192 	kfree(dtab);
193 }
194 
195 static int dev_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
196 {
197 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
198 	u32 index = key ? *(u32 *)key : U32_MAX;
199 	u32 *next = (u32 *)next_key;
200 
201 	if (index >= dtab->map.max_entries) {
202 		*next = 0;
203 		return 0;
204 	}
205 
206 	if (index == dtab->map.max_entries - 1)
207 		return -ENOENT;
208 
209 	*next = index + 1;
210 	return 0;
211 }
212 
213 void __dev_map_insert_ctx(struct bpf_map *map, u32 key)
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(key, bitmap);
219 }
220 
221 struct net_device  *__dev_map_lookup_elem(struct bpf_map *map, u32 key)
222 {
223 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
224 	struct bpf_dtab_netdev *dev;
225 
226 	if (key >= map->max_entries)
227 		return NULL;
228 
229 	dev = READ_ONCE(dtab->netdev_map[key]);
230 	return dev ? dev->dev : NULL;
231 }
232 
233 /* __dev_map_flush is called from xdp_do_flush_map() which _must_ be signaled
234  * from the driver before returning from its napi->poll() routine. The poll()
235  * routine is called either from busy_poll context or net_rx_action signaled
236  * from NET_RX_SOFTIRQ. Either way the poll routine must complete before the
237  * net device can be torn down. On devmap tear down we ensure the ctx bitmap
238  * is zeroed before completing to ensure all flush operations have completed.
239  */
240 void __dev_map_flush(struct bpf_map *map)
241 {
242 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
243 	unsigned long *bitmap = this_cpu_ptr(dtab->flush_needed);
244 	u32 bit;
245 
246 	for_each_set_bit(bit, bitmap, map->max_entries) {
247 		struct bpf_dtab_netdev *dev = READ_ONCE(dtab->netdev_map[bit]);
248 		struct net_device *netdev;
249 
250 		/* This is possible if the dev entry is removed by user space
251 		 * between xdp redirect and flush op.
252 		 */
253 		if (unlikely(!dev))
254 			continue;
255 
256 		netdev = dev->dev;
257 
258 		__clear_bit(bit, bitmap);
259 		if (unlikely(!netdev || !netdev->netdev_ops->ndo_xdp_flush))
260 			continue;
261 
262 		netdev->netdev_ops->ndo_xdp_flush(netdev);
263 	}
264 }
265 
266 /* rcu_read_lock (from syscall and BPF contexts) ensures that if a delete and/or
267  * update happens in parallel here a dev_put wont happen until after reading the
268  * ifindex.
269  */
270 static void *dev_map_lookup_elem(struct bpf_map *map, void *key)
271 {
272 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
273 	struct bpf_dtab_netdev *dev;
274 	u32 i = *(u32 *)key;
275 
276 	if (i >= map->max_entries)
277 		return NULL;
278 
279 	dev = READ_ONCE(dtab->netdev_map[i]);
280 	return dev ? &dev->dev->ifindex : NULL;
281 }
282 
283 static void dev_map_flush_old(struct bpf_dtab_netdev *old_dev)
284 {
285 	if (old_dev->dev->netdev_ops->ndo_xdp_flush) {
286 		struct net_device *fl = old_dev->dev;
287 		unsigned long *bitmap;
288 		int cpu;
289 
290 		for_each_online_cpu(cpu) {
291 			bitmap = per_cpu_ptr(old_dev->dtab->flush_needed, cpu);
292 			__clear_bit(old_dev->key, bitmap);
293 
294 			fl->netdev_ops->ndo_xdp_flush(old_dev->dev);
295 		}
296 	}
297 }
298 
299 static void __dev_map_entry_free(struct rcu_head *rcu)
300 {
301 	struct bpf_dtab_netdev *old_dev;
302 
303 	old_dev = container_of(rcu, struct bpf_dtab_netdev, rcu);
304 	dev_map_flush_old(old_dev);
305 	dev_put(old_dev->dev);
306 	kfree(old_dev);
307 }
308 
309 static int dev_map_delete_elem(struct bpf_map *map, void *key)
310 {
311 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
312 	struct bpf_dtab_netdev *old_dev;
313 	int k = *(u32 *)key;
314 
315 	if (k >= map->max_entries)
316 		return -EINVAL;
317 
318 	/* Use synchronize_rcu() here to ensure any rcu critical sections
319 	 * have completed, but this does not guarantee a flush has happened
320 	 * yet. Because driver side rcu_read_lock/unlock only protects the
321 	 * running XDP program. However, for pending flush operations the
322 	 * dev and ctx are stored in another per cpu map. And additionally,
323 	 * the driver tear down ensures all soft irqs are complete before
324 	 * removing the net device in the case of dev_put equals zero.
325 	 */
326 	old_dev = xchg(&dtab->netdev_map[k], NULL);
327 	if (old_dev)
328 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
329 	return 0;
330 }
331 
332 static int dev_map_update_elem(struct bpf_map *map, void *key, void *value,
333 				u64 map_flags)
334 {
335 	struct bpf_dtab *dtab = container_of(map, struct bpf_dtab, map);
336 	struct net *net = current->nsproxy->net_ns;
337 	struct bpf_dtab_netdev *dev, *old_dev;
338 	u32 i = *(u32 *)key;
339 	u32 ifindex = *(u32 *)value;
340 
341 	if (unlikely(map_flags > BPF_EXIST))
342 		return -EINVAL;
343 
344 	if (unlikely(i >= dtab->map.max_entries))
345 		return -E2BIG;
346 
347 	if (unlikely(map_flags == BPF_NOEXIST))
348 		return -EEXIST;
349 
350 	if (!ifindex) {
351 		dev = NULL;
352 	} else {
353 		dev = kmalloc(sizeof(*dev), GFP_ATOMIC | __GFP_NOWARN);
354 		if (!dev)
355 			return -ENOMEM;
356 
357 		dev->dev = dev_get_by_index(net, ifindex);
358 		if (!dev->dev) {
359 			kfree(dev);
360 			return -EINVAL;
361 		}
362 
363 		dev->key = i;
364 		dev->dtab = dtab;
365 	}
366 
367 	/* Use call_rcu() here to ensure rcu critical sections have completed
368 	 * Remembering the driver side flush operation will happen before the
369 	 * net device is removed.
370 	 */
371 	old_dev = xchg(&dtab->netdev_map[i], dev);
372 	if (old_dev)
373 		call_rcu(&old_dev->rcu, __dev_map_entry_free);
374 
375 	return 0;
376 }
377 
378 const struct bpf_map_ops dev_map_ops = {
379 	.map_alloc = dev_map_alloc,
380 	.map_free = dev_map_free,
381 	.map_get_next_key = dev_map_get_next_key,
382 	.map_lookup_elem = dev_map_lookup_elem,
383 	.map_update_elem = dev_map_update_elem,
384 	.map_delete_elem = dev_map_delete_elem,
385 };
386 
387 static int dev_map_notification(struct notifier_block *notifier,
388 				ulong event, void *ptr)
389 {
390 	struct net_device *netdev = netdev_notifier_info_to_dev(ptr);
391 	struct bpf_dtab *dtab;
392 	int i;
393 
394 	switch (event) {
395 	case NETDEV_UNREGISTER:
396 		/* This rcu_read_lock/unlock pair is needed because
397 		 * dev_map_list is an RCU list AND to ensure a delete
398 		 * operation does not free a netdev_map entry while we
399 		 * are comparing it against the netdev being unregistered.
400 		 */
401 		rcu_read_lock();
402 		list_for_each_entry_rcu(dtab, &dev_map_list, list) {
403 			for (i = 0; i < dtab->map.max_entries; i++) {
404 				struct bpf_dtab_netdev *dev, *odev;
405 
406 				dev = READ_ONCE(dtab->netdev_map[i]);
407 				if (!dev ||
408 				    dev->dev->ifindex != netdev->ifindex)
409 					continue;
410 				odev = cmpxchg(&dtab->netdev_map[i], dev, NULL);
411 				if (dev == odev)
412 					call_rcu(&dev->rcu,
413 						 __dev_map_entry_free);
414 			}
415 		}
416 		rcu_read_unlock();
417 		break;
418 	default:
419 		break;
420 	}
421 	return NOTIFY_OK;
422 }
423 
424 static struct notifier_block dev_map_notifier = {
425 	.notifier_call = dev_map_notification,
426 };
427 
428 static int __init dev_map_init(void)
429 {
430 	register_netdevice_notifier(&dev_map_notifier);
431 	return 0;
432 }
433 
434 subsys_initcall(dev_map_init);
435