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