• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* bpf/cpumap.c
3  *
4  * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
5  */
6 
7 /* The 'cpumap' is primarily used as a backend map for XDP BPF helper
8  * call bpf_redirect_map() and XDP_REDIRECT action, like 'devmap'.
9  *
10  * Unlike devmap which redirects XDP frames out another NIC device,
11  * this map type redirects raw XDP frames to another CPU.  The remote
12  * CPU will do SKB-allocation and call the normal network stack.
13  *
14  * This is a scalability and isolation mechanism, that allow
15  * separating the early driver network XDP layer, from the rest of the
16  * netstack, and assigning dedicated CPUs for this stage.  This
17  * basically allows for 10G wirespeed pre-filtering via bpf.
18  */
19 #include <linux/bitops.h>
20 #include <linux/bpf.h>
21 #include <linux/filter.h>
22 #include <linux/ptr_ring.h>
23 #include <net/xdp.h>
24 
25 #include <linux/sched.h>
26 #include <linux/workqueue.h>
27 #include <linux/kthread.h>
28 #include <linux/capability.h>
29 #include <linux/completion.h>
30 #include <trace/events/xdp.h>
31 #include <linux/btf_ids.h>
32 
33 #include <linux/netdevice.h>   /* netif_receive_skb_list */
34 #include <linux/etherdevice.h> /* eth_type_trans */
35 
36 /* General idea: XDP packets getting XDP redirected to another CPU,
37  * will maximum be stored/queued for one driver ->poll() call.  It is
38  * guaranteed that queueing the frame and the flush operation happen on
39  * same CPU.  Thus, cpu_map_flush operation can deduct via this_cpu_ptr()
40  * which queue in bpf_cpu_map_entry contains packets.
41  */
42 
43 #define CPU_MAP_BULK_SIZE 8  /* 8 == one cacheline on 64-bit archs */
44 struct bpf_cpu_map_entry;
45 struct bpf_cpu_map;
46 
47 struct xdp_bulk_queue {
48 	void *q[CPU_MAP_BULK_SIZE];
49 	struct list_head flush_node;
50 	struct bpf_cpu_map_entry *obj;
51 	unsigned int count;
52 };
53 
54 /* Struct for every remote "destination" CPU in map */
55 struct bpf_cpu_map_entry {
56 	u32 cpu;    /* kthread CPU and map index */
57 	int map_id; /* Back reference to map */
58 
59 	/* XDP can run multiple RX-ring queues, need __percpu enqueue store */
60 	struct xdp_bulk_queue __percpu *bulkq;
61 
62 	struct bpf_cpu_map *cmap;
63 
64 	/* Queue with potential multi-producers, and single-consumer kthread */
65 	struct ptr_ring *queue;
66 	struct task_struct *kthread;
67 
68 	struct bpf_cpumap_val value;
69 	struct bpf_prog *prog;
70 
71 	atomic_t refcnt; /* Control when this struct can be free'ed */
72 	struct rcu_head rcu;
73 
74 	struct work_struct kthread_stop_wq;
75 	struct completion kthread_running;
76 };
77 
78 struct bpf_cpu_map {
79 	struct bpf_map map;
80 	/* Below members specific for map type */
81 	struct bpf_cpu_map_entry __rcu **cpu_map;
82 };
83 
84 static DEFINE_PER_CPU(struct list_head, cpu_map_flush_list);
85 
cpu_map_alloc(union bpf_attr * attr)86 static struct bpf_map *cpu_map_alloc(union bpf_attr *attr)
87 {
88 	u32 value_size = attr->value_size;
89 	struct bpf_cpu_map *cmap;
90 	int err = -ENOMEM;
91 
92 	if (!bpf_capable())
93 		return ERR_PTR(-EPERM);
94 
95 	/* check sanity of attributes */
96 	if (attr->max_entries == 0 || attr->key_size != 4 ||
97 	    (value_size != offsetofend(struct bpf_cpumap_val, qsize) &&
98 	     value_size != offsetofend(struct bpf_cpumap_val, bpf_prog.fd)) ||
99 	    attr->map_flags & ~BPF_F_NUMA_NODE)
100 		return ERR_PTR(-EINVAL);
101 
102 	cmap = bpf_map_area_alloc(sizeof(*cmap), NUMA_NO_NODE);
103 	if (!cmap)
104 		return ERR_PTR(-ENOMEM);
105 
106 	bpf_map_init_from_attr(&cmap->map, attr);
107 
108 	/* Pre-limit array size based on NR_CPUS, not final CPU check */
109 	if (cmap->map.max_entries > NR_CPUS) {
110 		err = -E2BIG;
111 		goto free_cmap;
112 	}
113 
114 	/* Alloc array for possible remote "destination" CPUs */
115 	cmap->cpu_map = bpf_map_area_alloc(cmap->map.max_entries *
116 					   sizeof(struct bpf_cpu_map_entry *),
117 					   cmap->map.numa_node);
118 	if (!cmap->cpu_map)
119 		goto free_cmap;
120 
121 	return &cmap->map;
122 free_cmap:
123 	bpf_map_area_free(cmap);
124 	return ERR_PTR(err);
125 }
126 
get_cpu_map_entry(struct bpf_cpu_map_entry * rcpu)127 static void get_cpu_map_entry(struct bpf_cpu_map_entry *rcpu)
128 {
129 	atomic_inc(&rcpu->refcnt);
130 }
131 
__cpu_map_ring_cleanup(struct ptr_ring * ring)132 static void __cpu_map_ring_cleanup(struct ptr_ring *ring)
133 {
134 	/* The tear-down procedure should have made sure that queue is
135 	 * empty.  See __cpu_map_entry_replace() and work-queue
136 	 * invoked cpu_map_kthread_stop(). Catch any broken behaviour
137 	 * gracefully and warn once.
138 	 */
139 	void *ptr;
140 
141 	while ((ptr = ptr_ring_consume(ring))) {
142 		WARN_ON_ONCE(1);
143 		if (unlikely(__ptr_test_bit(0, &ptr))) {
144 			__ptr_clear_bit(0, &ptr);
145 			kfree_skb(ptr);
146 			continue;
147 		}
148 		xdp_return_frame(ptr);
149 	}
150 }
151 
put_cpu_map_entry(struct bpf_cpu_map_entry * rcpu)152 static void put_cpu_map_entry(struct bpf_cpu_map_entry *rcpu)
153 {
154 	if (atomic_dec_and_test(&rcpu->refcnt)) {
155 		if (rcpu->prog)
156 			bpf_prog_put(rcpu->prog);
157 		/* The queue should be empty at this point */
158 		__cpu_map_ring_cleanup(rcpu->queue);
159 		ptr_ring_cleanup(rcpu->queue, NULL);
160 		kfree(rcpu->queue);
161 		kfree(rcpu);
162 	}
163 }
164 
165 /* called from workqueue, to workaround syscall using preempt_disable */
cpu_map_kthread_stop(struct work_struct * work)166 static void cpu_map_kthread_stop(struct work_struct *work)
167 {
168 	struct bpf_cpu_map_entry *rcpu;
169 
170 	rcpu = container_of(work, struct bpf_cpu_map_entry, kthread_stop_wq);
171 
172 	/* Wait for flush in __cpu_map_entry_free(), via full RCU barrier,
173 	 * as it waits until all in-flight call_rcu() callbacks complete.
174 	 */
175 	rcu_barrier();
176 
177 	/* kthread_stop will wake_up_process and wait for it to complete */
178 	kthread_stop(rcpu->kthread);
179 }
180 
cpu_map_bpf_prog_run_skb(struct bpf_cpu_map_entry * rcpu,struct list_head * listp,struct xdp_cpumap_stats * stats)181 static void cpu_map_bpf_prog_run_skb(struct bpf_cpu_map_entry *rcpu,
182 				     struct list_head *listp,
183 				     struct xdp_cpumap_stats *stats)
184 {
185 	struct sk_buff *skb, *tmp;
186 	struct xdp_buff xdp;
187 	u32 act;
188 	int err;
189 
190 	list_for_each_entry_safe(skb, tmp, listp, list) {
191 		act = bpf_prog_run_generic_xdp(skb, &xdp, rcpu->prog);
192 		switch (act) {
193 		case XDP_PASS:
194 			break;
195 		case XDP_REDIRECT:
196 			skb_list_del_init(skb);
197 			err = xdp_do_generic_redirect(skb->dev, skb, &xdp,
198 						      rcpu->prog);
199 			if (unlikely(err)) {
200 				kfree_skb(skb);
201 				stats->drop++;
202 			} else {
203 				stats->redirect++;
204 			}
205 			return;
206 		default:
207 			bpf_warn_invalid_xdp_action(NULL, rcpu->prog, act);
208 			fallthrough;
209 		case XDP_ABORTED:
210 			trace_xdp_exception(skb->dev, rcpu->prog, act);
211 			fallthrough;
212 		case XDP_DROP:
213 			skb_list_del_init(skb);
214 			kfree_skb(skb);
215 			stats->drop++;
216 			return;
217 		}
218 	}
219 }
220 
cpu_map_bpf_prog_run_xdp(struct bpf_cpu_map_entry * rcpu,void ** frames,int n,struct xdp_cpumap_stats * stats)221 static int cpu_map_bpf_prog_run_xdp(struct bpf_cpu_map_entry *rcpu,
222 				    void **frames, int n,
223 				    struct xdp_cpumap_stats *stats)
224 {
225 	struct xdp_rxq_info rxq;
226 	struct xdp_buff xdp;
227 	int i, nframes = 0;
228 
229 	xdp_set_return_frame_no_direct();
230 	xdp.rxq = &rxq;
231 
232 	for (i = 0; i < n; i++) {
233 		struct xdp_frame *xdpf = frames[i];
234 		u32 act;
235 		int err;
236 
237 		rxq.dev = xdpf->dev_rx;
238 		rxq.mem = xdpf->mem;
239 		/* TODO: report queue_index to xdp_rxq_info */
240 
241 		xdp_convert_frame_to_buff(xdpf, &xdp);
242 
243 		act = bpf_prog_run_xdp(rcpu->prog, &xdp);
244 		switch (act) {
245 		case XDP_PASS:
246 			err = xdp_update_frame_from_buff(&xdp, xdpf);
247 			if (err < 0) {
248 				xdp_return_frame(xdpf);
249 				stats->drop++;
250 			} else {
251 				frames[nframes++] = xdpf;
252 				stats->pass++;
253 			}
254 			break;
255 		case XDP_REDIRECT:
256 			err = xdp_do_redirect(xdpf->dev_rx, &xdp,
257 					      rcpu->prog);
258 			if (unlikely(err)) {
259 				xdp_return_frame(xdpf);
260 				stats->drop++;
261 			} else {
262 				stats->redirect++;
263 			}
264 			break;
265 		default:
266 			bpf_warn_invalid_xdp_action(NULL, rcpu->prog, act);
267 			fallthrough;
268 		case XDP_DROP:
269 			xdp_return_frame(xdpf);
270 			stats->drop++;
271 			break;
272 		}
273 	}
274 
275 	xdp_clear_return_frame_no_direct();
276 
277 	return nframes;
278 }
279 
280 #define CPUMAP_BATCH 8
281 
cpu_map_bpf_prog_run(struct bpf_cpu_map_entry * rcpu,void ** frames,int xdp_n,struct xdp_cpumap_stats * stats,struct list_head * list)282 static int cpu_map_bpf_prog_run(struct bpf_cpu_map_entry *rcpu, void **frames,
283 				int xdp_n, struct xdp_cpumap_stats *stats,
284 				struct list_head *list)
285 {
286 	int nframes;
287 
288 	if (!rcpu->prog)
289 		return xdp_n;
290 
291 	rcu_read_lock_bh();
292 
293 	nframes = cpu_map_bpf_prog_run_xdp(rcpu, frames, xdp_n, stats);
294 
295 	if (stats->redirect)
296 		xdp_do_flush();
297 
298 	if (unlikely(!list_empty(list)))
299 		cpu_map_bpf_prog_run_skb(rcpu, list, stats);
300 
301 	rcu_read_unlock_bh(); /* resched point, may call do_softirq() */
302 
303 	return nframes;
304 }
305 
cpu_map_kthread_run(void * data)306 static int cpu_map_kthread_run(void *data)
307 {
308 	struct bpf_cpu_map_entry *rcpu = data;
309 
310 	complete(&rcpu->kthread_running);
311 	set_current_state(TASK_INTERRUPTIBLE);
312 
313 	/* When kthread gives stop order, then rcpu have been disconnected
314 	 * from map, thus no new packets can enter. Remaining in-flight
315 	 * per CPU stored packets are flushed to this queue.  Wait honoring
316 	 * kthread_stop signal until queue is empty.
317 	 */
318 	while (!kthread_should_stop() || !__ptr_ring_empty(rcpu->queue)) {
319 		struct xdp_cpumap_stats stats = {}; /* zero stats */
320 		unsigned int kmem_alloc_drops = 0, sched = 0;
321 		gfp_t gfp = __GFP_ZERO | GFP_ATOMIC;
322 		int i, n, m, nframes, xdp_n;
323 		void *frames[CPUMAP_BATCH];
324 		void *skbs[CPUMAP_BATCH];
325 		LIST_HEAD(list);
326 
327 		/* Release CPU reschedule checks */
328 		if (__ptr_ring_empty(rcpu->queue)) {
329 			set_current_state(TASK_INTERRUPTIBLE);
330 			/* Recheck to avoid lost wake-up */
331 			if (__ptr_ring_empty(rcpu->queue)) {
332 				schedule();
333 				sched = 1;
334 			} else {
335 				__set_current_state(TASK_RUNNING);
336 			}
337 		} else {
338 			sched = cond_resched();
339 		}
340 
341 		/*
342 		 * The bpf_cpu_map_entry is single consumer, with this
343 		 * kthread CPU pinned. Lockless access to ptr_ring
344 		 * consume side valid as no-resize allowed of queue.
345 		 */
346 		n = __ptr_ring_consume_batched(rcpu->queue, frames,
347 					       CPUMAP_BATCH);
348 		for (i = 0, xdp_n = 0; i < n; i++) {
349 			void *f = frames[i];
350 			struct page *page;
351 
352 			if (unlikely(__ptr_test_bit(0, &f))) {
353 				struct sk_buff *skb = f;
354 
355 				__ptr_clear_bit(0, &skb);
356 				list_add_tail(&skb->list, &list);
357 				continue;
358 			}
359 
360 			frames[xdp_n++] = f;
361 			page = virt_to_page(f);
362 
363 			/* Bring struct page memory area to curr CPU. Read by
364 			 * build_skb_around via page_is_pfmemalloc(), and when
365 			 * freed written by page_frag_free call.
366 			 */
367 			prefetchw(page);
368 		}
369 
370 		/* Support running another XDP prog on this CPU */
371 		nframes = cpu_map_bpf_prog_run(rcpu, frames, xdp_n, &stats, &list);
372 		if (nframes) {
373 			m = kmem_cache_alloc_bulk(skbuff_head_cache, gfp, nframes, skbs);
374 			if (unlikely(m == 0)) {
375 				for (i = 0; i < nframes; i++)
376 					skbs[i] = NULL; /* effect: xdp_return_frame */
377 				kmem_alloc_drops += nframes;
378 			}
379 		}
380 
381 		local_bh_disable();
382 		for (i = 0; i < nframes; i++) {
383 			struct xdp_frame *xdpf = frames[i];
384 			struct sk_buff *skb = skbs[i];
385 
386 			skb = __xdp_build_skb_from_frame(xdpf, skb,
387 							 xdpf->dev_rx);
388 			if (!skb) {
389 				xdp_return_frame(xdpf);
390 				continue;
391 			}
392 
393 			list_add_tail(&skb->list, &list);
394 		}
395 		netif_receive_skb_list(&list);
396 
397 		/* Feedback loop via tracepoint */
398 		trace_xdp_cpumap_kthread(rcpu->map_id, n, kmem_alloc_drops,
399 					 sched, &stats);
400 
401 		local_bh_enable(); /* resched point, may call do_softirq() */
402 	}
403 	__set_current_state(TASK_RUNNING);
404 
405 	put_cpu_map_entry(rcpu);
406 	return 0;
407 }
408 
__cpu_map_load_bpf_program(struct bpf_cpu_map_entry * rcpu,struct bpf_map * map,int fd)409 static int __cpu_map_load_bpf_program(struct bpf_cpu_map_entry *rcpu,
410 				      struct bpf_map *map, int fd)
411 {
412 	struct bpf_prog *prog;
413 
414 	prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_XDP);
415 	if (IS_ERR(prog))
416 		return PTR_ERR(prog);
417 
418 	if (prog->expected_attach_type != BPF_XDP_CPUMAP ||
419 	    !bpf_prog_map_compatible(map, prog)) {
420 		bpf_prog_put(prog);
421 		return -EINVAL;
422 	}
423 
424 	rcpu->value.bpf_prog.id = prog->aux->id;
425 	rcpu->prog = prog;
426 
427 	return 0;
428 }
429 
430 static struct bpf_cpu_map_entry *
__cpu_map_entry_alloc(struct bpf_map * map,struct bpf_cpumap_val * value,u32 cpu)431 __cpu_map_entry_alloc(struct bpf_map *map, struct bpf_cpumap_val *value,
432 		      u32 cpu)
433 {
434 	int numa, err, i, fd = value->bpf_prog.fd;
435 	gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
436 	struct bpf_cpu_map_entry *rcpu;
437 	struct xdp_bulk_queue *bq;
438 
439 	/* Have map->numa_node, but choose node of redirect target CPU */
440 	numa = cpu_to_node(cpu);
441 
442 	rcpu = bpf_map_kmalloc_node(map, sizeof(*rcpu), gfp | __GFP_ZERO, numa);
443 	if (!rcpu)
444 		return NULL;
445 
446 	/* Alloc percpu bulkq */
447 	rcpu->bulkq = bpf_map_alloc_percpu(map, sizeof(*rcpu->bulkq),
448 					   sizeof(void *), gfp);
449 	if (!rcpu->bulkq)
450 		goto free_rcu;
451 
452 	for_each_possible_cpu(i) {
453 		bq = per_cpu_ptr(rcpu->bulkq, i);
454 		bq->obj = rcpu;
455 	}
456 
457 	/* Alloc queue */
458 	rcpu->queue = bpf_map_kmalloc_node(map, sizeof(*rcpu->queue), gfp,
459 					   numa);
460 	if (!rcpu->queue)
461 		goto free_bulkq;
462 
463 	err = ptr_ring_init(rcpu->queue, value->qsize, gfp);
464 	if (err)
465 		goto free_queue;
466 
467 	rcpu->cpu    = cpu;
468 	rcpu->map_id = map->id;
469 	rcpu->value.qsize  = value->qsize;
470 
471 	if (fd > 0 && __cpu_map_load_bpf_program(rcpu, map, fd))
472 		goto free_ptr_ring;
473 
474 	/* Setup kthread */
475 	init_completion(&rcpu->kthread_running);
476 	rcpu->kthread = kthread_create_on_node(cpu_map_kthread_run, rcpu, numa,
477 					       "cpumap/%d/map:%d", cpu,
478 					       map->id);
479 	if (IS_ERR(rcpu->kthread))
480 		goto free_prog;
481 
482 	get_cpu_map_entry(rcpu); /* 1-refcnt for being in cmap->cpu_map[] */
483 	get_cpu_map_entry(rcpu); /* 1-refcnt for kthread */
484 
485 	/* Make sure kthread runs on a single CPU */
486 	kthread_bind(rcpu->kthread, cpu);
487 	wake_up_process(rcpu->kthread);
488 
489 	/* Make sure kthread has been running, so kthread_stop() will not
490 	 * stop the kthread prematurely and all pending frames or skbs
491 	 * will be handled by the kthread before kthread_stop() returns.
492 	 */
493 	wait_for_completion(&rcpu->kthread_running);
494 
495 	return rcpu;
496 
497 free_prog:
498 	if (rcpu->prog)
499 		bpf_prog_put(rcpu->prog);
500 free_ptr_ring:
501 	ptr_ring_cleanup(rcpu->queue, NULL);
502 free_queue:
503 	kfree(rcpu->queue);
504 free_bulkq:
505 	free_percpu(rcpu->bulkq);
506 free_rcu:
507 	kfree(rcpu);
508 	return NULL;
509 }
510 
__cpu_map_entry_free(struct rcu_head * rcu)511 static void __cpu_map_entry_free(struct rcu_head *rcu)
512 {
513 	struct bpf_cpu_map_entry *rcpu;
514 
515 	/* This cpu_map_entry have been disconnected from map and one
516 	 * RCU grace-period have elapsed.  Thus, XDP cannot queue any
517 	 * new packets and cannot change/set flush_needed that can
518 	 * find this entry.
519 	 */
520 	rcpu = container_of(rcu, struct bpf_cpu_map_entry, rcu);
521 
522 	free_percpu(rcpu->bulkq);
523 	/* Cannot kthread_stop() here, last put free rcpu resources */
524 	put_cpu_map_entry(rcpu);
525 }
526 
527 /* After xchg pointer to bpf_cpu_map_entry, use the call_rcu() to
528  * ensure any driver rcu critical sections have completed, but this
529  * does not guarantee a flush has happened yet. Because driver side
530  * rcu_read_lock/unlock only protects the running XDP program.  The
531  * atomic xchg and NULL-ptr check in __cpu_map_flush() makes sure a
532  * pending flush op doesn't fail.
533  *
534  * The bpf_cpu_map_entry is still used by the kthread, and there can
535  * still be pending packets (in queue and percpu bulkq).  A refcnt
536  * makes sure to last user (kthread_stop vs. call_rcu) free memory
537  * resources.
538  *
539  * The rcu callback __cpu_map_entry_free flush remaining packets in
540  * percpu bulkq to queue.  Due to caller map_delete_elem() disable
541  * preemption, cannot call kthread_stop() to make sure queue is empty.
542  * Instead a work_queue is started for stopping kthread,
543  * cpu_map_kthread_stop, which waits for an RCU grace period before
544  * stopping kthread, emptying the queue.
545  */
__cpu_map_entry_replace(struct bpf_cpu_map * cmap,u32 key_cpu,struct bpf_cpu_map_entry * rcpu)546 static void __cpu_map_entry_replace(struct bpf_cpu_map *cmap,
547 				    u32 key_cpu, struct bpf_cpu_map_entry *rcpu)
548 {
549 	struct bpf_cpu_map_entry *old_rcpu;
550 
551 	old_rcpu = unrcu_pointer(xchg(&cmap->cpu_map[key_cpu], RCU_INITIALIZER(rcpu)));
552 	if (old_rcpu) {
553 		call_rcu(&old_rcpu->rcu, __cpu_map_entry_free);
554 		INIT_WORK(&old_rcpu->kthread_stop_wq, cpu_map_kthread_stop);
555 		schedule_work(&old_rcpu->kthread_stop_wq);
556 	}
557 }
558 
cpu_map_delete_elem(struct bpf_map * map,void * key)559 static int cpu_map_delete_elem(struct bpf_map *map, void *key)
560 {
561 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
562 	u32 key_cpu = *(u32 *)key;
563 
564 	if (key_cpu >= map->max_entries)
565 		return -EINVAL;
566 
567 	/* notice caller map_delete_elem() use preempt_disable() */
568 	__cpu_map_entry_replace(cmap, key_cpu, NULL);
569 	return 0;
570 }
571 
cpu_map_update_elem(struct bpf_map * map,void * key,void * value,u64 map_flags)572 static int cpu_map_update_elem(struct bpf_map *map, void *key, void *value,
573 			       u64 map_flags)
574 {
575 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
576 	struct bpf_cpumap_val cpumap_value = {};
577 	struct bpf_cpu_map_entry *rcpu;
578 	/* Array index key correspond to CPU number */
579 	u32 key_cpu = *(u32 *)key;
580 
581 	memcpy(&cpumap_value, value, map->value_size);
582 
583 	if (unlikely(map_flags > BPF_EXIST))
584 		return -EINVAL;
585 	if (unlikely(key_cpu >= cmap->map.max_entries))
586 		return -E2BIG;
587 	if (unlikely(map_flags == BPF_NOEXIST))
588 		return -EEXIST;
589 	if (unlikely(cpumap_value.qsize > 16384)) /* sanity limit on qsize */
590 		return -EOVERFLOW;
591 
592 	/* Make sure CPU is a valid possible cpu */
593 	if (key_cpu >= nr_cpumask_bits || !cpu_possible(key_cpu))
594 		return -ENODEV;
595 
596 	if (cpumap_value.qsize == 0) {
597 		rcpu = NULL; /* Same as deleting */
598 	} else {
599 		/* Updating qsize cause re-allocation of bpf_cpu_map_entry */
600 		rcpu = __cpu_map_entry_alloc(map, &cpumap_value, key_cpu);
601 		if (!rcpu)
602 			return -ENOMEM;
603 		rcpu->cmap = cmap;
604 	}
605 	rcu_read_lock();
606 	__cpu_map_entry_replace(cmap, key_cpu, rcpu);
607 	rcu_read_unlock();
608 	return 0;
609 }
610 
cpu_map_free(struct bpf_map * map)611 static void cpu_map_free(struct bpf_map *map)
612 {
613 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
614 	u32 i;
615 
616 	/* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
617 	 * so the bpf programs (can be more than one that used this map) were
618 	 * disconnected from events. Wait for outstanding critical sections in
619 	 * these programs to complete. The rcu critical section only guarantees
620 	 * no further "XDP/bpf-side" reads against bpf_cpu_map->cpu_map.
621 	 * It does __not__ ensure pending flush operations (if any) are
622 	 * complete.
623 	 */
624 
625 	synchronize_rcu();
626 
627 	/* For cpu_map the remote CPUs can still be using the entries
628 	 * (struct bpf_cpu_map_entry).
629 	 */
630 	for (i = 0; i < cmap->map.max_entries; i++) {
631 		struct bpf_cpu_map_entry *rcpu;
632 
633 		rcpu = rcu_dereference_raw(cmap->cpu_map[i]);
634 		if (!rcpu)
635 			continue;
636 
637 		/* bq flush and cleanup happens after RCU grace-period */
638 		__cpu_map_entry_replace(cmap, i, NULL); /* call_rcu */
639 	}
640 	bpf_map_area_free(cmap->cpu_map);
641 	bpf_map_area_free(cmap);
642 }
643 
644 /* Elements are kept alive by RCU; either by rcu_read_lock() (from syscall) or
645  * by local_bh_disable() (from XDP calls inside NAPI). The
646  * rcu_read_lock_bh_held() below makes lockdep accept both.
647  */
__cpu_map_lookup_elem(struct bpf_map * map,u32 key)648 static void *__cpu_map_lookup_elem(struct bpf_map *map, u32 key)
649 {
650 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
651 	struct bpf_cpu_map_entry *rcpu;
652 
653 	if (key >= map->max_entries)
654 		return NULL;
655 
656 	rcpu = rcu_dereference_check(cmap->cpu_map[key],
657 				     rcu_read_lock_bh_held());
658 	return rcpu;
659 }
660 
cpu_map_lookup_elem(struct bpf_map * map,void * key)661 static void *cpu_map_lookup_elem(struct bpf_map *map, void *key)
662 {
663 	struct bpf_cpu_map_entry *rcpu =
664 		__cpu_map_lookup_elem(map, *(u32 *)key);
665 
666 	return rcpu ? &rcpu->value : NULL;
667 }
668 
cpu_map_get_next_key(struct bpf_map * map,void * key,void * next_key)669 static int cpu_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
670 {
671 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
672 	u32 index = key ? *(u32 *)key : U32_MAX;
673 	u32 *next = next_key;
674 
675 	if (index >= cmap->map.max_entries) {
676 		*next = 0;
677 		return 0;
678 	}
679 
680 	if (index == cmap->map.max_entries - 1)
681 		return -ENOENT;
682 	*next = index + 1;
683 	return 0;
684 }
685 
cpu_map_redirect(struct bpf_map * map,u32 ifindex,u64 flags)686 static int cpu_map_redirect(struct bpf_map *map, u32 ifindex, u64 flags)
687 {
688 	return __bpf_xdp_redirect_map(map, ifindex, flags, 0,
689 				      __cpu_map_lookup_elem);
690 }
691 
692 BTF_ID_LIST_SINGLE(cpu_map_btf_ids, struct, bpf_cpu_map)
693 const struct bpf_map_ops cpu_map_ops = {
694 	.map_meta_equal		= bpf_map_meta_equal,
695 	.map_alloc		= cpu_map_alloc,
696 	.map_free		= cpu_map_free,
697 	.map_delete_elem	= cpu_map_delete_elem,
698 	.map_update_elem	= cpu_map_update_elem,
699 	.map_lookup_elem	= cpu_map_lookup_elem,
700 	.map_get_next_key	= cpu_map_get_next_key,
701 	.map_check_btf		= map_check_no_btf,
702 	.map_btf_id		= &cpu_map_btf_ids[0],
703 	.map_redirect		= cpu_map_redirect,
704 };
705 
bq_flush_to_queue(struct xdp_bulk_queue * bq)706 static void bq_flush_to_queue(struct xdp_bulk_queue *bq)
707 {
708 	struct bpf_cpu_map_entry *rcpu = bq->obj;
709 	unsigned int processed = 0, drops = 0;
710 	const int to_cpu = rcpu->cpu;
711 	struct ptr_ring *q;
712 	int i;
713 
714 	if (unlikely(!bq->count))
715 		return;
716 
717 	q = rcpu->queue;
718 	spin_lock(&q->producer_lock);
719 
720 	for (i = 0; i < bq->count; i++) {
721 		struct xdp_frame *xdpf = bq->q[i];
722 		int err;
723 
724 		err = __ptr_ring_produce(q, xdpf);
725 		if (err) {
726 			drops++;
727 			xdp_return_frame_rx_napi(xdpf);
728 		}
729 		processed++;
730 	}
731 	bq->count = 0;
732 	spin_unlock(&q->producer_lock);
733 
734 	__list_del_clearprev(&bq->flush_node);
735 
736 	/* Feedback loop via tracepoints */
737 	trace_xdp_cpumap_enqueue(rcpu->map_id, processed, drops, to_cpu);
738 }
739 
740 /* Runs under RCU-read-side, plus in softirq under NAPI protection.
741  * Thus, safe percpu variable access.
742  */
bq_enqueue(struct bpf_cpu_map_entry * rcpu,struct xdp_frame * xdpf)743 static void bq_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_frame *xdpf)
744 {
745 	struct list_head *flush_list = this_cpu_ptr(&cpu_map_flush_list);
746 	struct xdp_bulk_queue *bq = this_cpu_ptr(rcpu->bulkq);
747 
748 	if (unlikely(bq->count == CPU_MAP_BULK_SIZE))
749 		bq_flush_to_queue(bq);
750 
751 	/* Notice, xdp_buff/page MUST be queued here, long enough for
752 	 * driver to code invoking us to finished, due to driver
753 	 * (e.g. ixgbe) recycle tricks based on page-refcnt.
754 	 *
755 	 * Thus, incoming xdp_frame is always queued here (else we race
756 	 * with another CPU on page-refcnt and remaining driver code).
757 	 * Queue time is very short, as driver will invoke flush
758 	 * operation, when completing napi->poll call.
759 	 */
760 	bq->q[bq->count++] = xdpf;
761 
762 	if (!bq->flush_node.prev)
763 		list_add(&bq->flush_node, flush_list);
764 }
765 
cpu_map_enqueue(struct bpf_cpu_map_entry * rcpu,struct xdp_frame * xdpf,struct net_device * dev_rx)766 int cpu_map_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_frame *xdpf,
767 		    struct net_device *dev_rx)
768 {
769 	/* Info needed when constructing SKB on remote CPU */
770 	xdpf->dev_rx = dev_rx;
771 
772 	bq_enqueue(rcpu, xdpf);
773 	return 0;
774 }
775 
cpu_map_generic_redirect(struct bpf_cpu_map_entry * rcpu,struct sk_buff * skb)776 int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu,
777 			     struct sk_buff *skb)
778 {
779 	int ret;
780 
781 	__skb_pull(skb, skb->mac_len);
782 	skb_set_redirected(skb, false);
783 	__ptr_set_bit(0, &skb);
784 
785 	ret = ptr_ring_produce(rcpu->queue, skb);
786 	if (ret < 0)
787 		goto trace;
788 
789 	wake_up_process(rcpu->kthread);
790 trace:
791 	trace_xdp_cpumap_enqueue(rcpu->map_id, !ret, !!ret, rcpu->cpu);
792 	return ret;
793 }
794 
__cpu_map_flush(void)795 void __cpu_map_flush(void)
796 {
797 	struct list_head *flush_list = this_cpu_ptr(&cpu_map_flush_list);
798 	struct xdp_bulk_queue *bq, *tmp;
799 
800 	list_for_each_entry_safe(bq, tmp, flush_list, flush_node) {
801 		bq_flush_to_queue(bq);
802 
803 		/* If already running, costs spin_lock_irqsave + smb_mb */
804 		wake_up_process(bq->obj->kthread);
805 	}
806 }
807 
cpu_map_init(void)808 static int __init cpu_map_init(void)
809 {
810 	int cpu;
811 
812 	for_each_possible_cpu(cpu)
813 		INIT_LIST_HEAD(&per_cpu(cpu_map_flush_list, cpu));
814 	return 0;
815 }
816 
817 subsys_initcall(cpu_map_init);
818