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