xref: /linux-6.15/kernel/bpf/cpumap.c (revision 57efe762)
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 #include <net/hotdata.h>
28 
29 #include <linux/sched.h>
30 #include <linux/workqueue.h>
31 #include <linux/kthread.h>
32 #include <linux/completion.h>
33 #include <trace/events/xdp.h>
34 #include <linux/btf_ids.h>
35 
36 #include <linux/netdevice.h>
37 #include <net/gro.h>
38 
39 /* General idea: XDP packets getting XDP redirected to another CPU,
40  * will maximum be stored/queued for one driver ->poll() call.  It is
41  * guaranteed that queueing the frame and the flush operation happen on
42  * same CPU.  Thus, cpu_map_flush operation can deduct via this_cpu_ptr()
43  * which queue in bpf_cpu_map_entry contains packets.
44  */
45 
46 #define CPU_MAP_BULK_SIZE 8  /* 8 == one cacheline on 64-bit archs */
47 struct bpf_cpu_map_entry;
48 struct bpf_cpu_map;
49 
50 struct xdp_bulk_queue {
51 	void *q[CPU_MAP_BULK_SIZE];
52 	struct list_head flush_node;
53 	struct bpf_cpu_map_entry *obj;
54 	unsigned int count;
55 };
56 
57 /* Struct for every remote "destination" CPU in map */
58 struct bpf_cpu_map_entry {
59 	u32 cpu;    /* kthread CPU and map index */
60 	int map_id; /* Back reference to map */
61 
62 	/* XDP can run multiple RX-ring queues, need __percpu enqueue store */
63 	struct xdp_bulk_queue __percpu *bulkq;
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 	struct gro_node gro;
72 
73 	struct completion kthread_running;
74 	struct rcu_work free_work;
75 };
76 
77 struct bpf_cpu_map {
78 	struct bpf_map map;
79 	/* Below members specific for map type */
80 	struct bpf_cpu_map_entry __rcu **cpu_map;
81 };
82 
83 static struct bpf_map *cpu_map_alloc(union bpf_attr *attr)
84 {
85 	u32 value_size = attr->value_size;
86 	struct bpf_cpu_map *cmap;
87 
88 	/* check sanity of attributes */
89 	if (attr->max_entries == 0 || attr->key_size != 4 ||
90 	    (value_size != offsetofend(struct bpf_cpumap_val, qsize) &&
91 	     value_size != offsetofend(struct bpf_cpumap_val, bpf_prog.fd)) ||
92 	    attr->map_flags & ~BPF_F_NUMA_NODE)
93 		return ERR_PTR(-EINVAL);
94 
95 	/* Pre-limit array size based on NR_CPUS, not final CPU check */
96 	if (attr->max_entries > NR_CPUS)
97 		return ERR_PTR(-E2BIG);
98 
99 	cmap = bpf_map_area_alloc(sizeof(*cmap), NUMA_NO_NODE);
100 	if (!cmap)
101 		return ERR_PTR(-ENOMEM);
102 
103 	bpf_map_init_from_attr(&cmap->map, attr);
104 
105 	/* Alloc array for possible remote "destination" CPUs */
106 	cmap->cpu_map = bpf_map_area_alloc(cmap->map.max_entries *
107 					   sizeof(struct bpf_cpu_map_entry *),
108 					   cmap->map.numa_node);
109 	if (!cmap->cpu_map) {
110 		bpf_map_area_free(cmap);
111 		return ERR_PTR(-ENOMEM);
112 	}
113 
114 	return &cmap->map;
115 }
116 
117 static void __cpu_map_ring_cleanup(struct ptr_ring *ring)
118 {
119 	/* The tear-down procedure should have made sure that queue is
120 	 * empty.  See __cpu_map_entry_replace() and work-queue
121 	 * invoked cpu_map_kthread_stop(). Catch any broken behaviour
122 	 * gracefully and warn once.
123 	 */
124 	void *ptr;
125 
126 	while ((ptr = ptr_ring_consume(ring))) {
127 		WARN_ON_ONCE(1);
128 		if (unlikely(__ptr_test_bit(0, &ptr))) {
129 			__ptr_clear_bit(0, &ptr);
130 			kfree_skb(ptr);
131 			continue;
132 		}
133 		xdp_return_frame(ptr);
134 	}
135 }
136 
137 static u32 cpu_map_bpf_prog_run_skb(struct bpf_cpu_map_entry *rcpu,
138 				    void **skbs, u32 skb_n,
139 				    struct xdp_cpumap_stats *stats)
140 {
141 	struct xdp_buff xdp;
142 	u32 act, pass = 0;
143 	int err;
144 
145 	for (u32 i = 0; i < skb_n; i++) {
146 		struct sk_buff *skb = skbs[i];
147 
148 		act = bpf_prog_run_generic_xdp(skb, &xdp, rcpu->prog);
149 		switch (act) {
150 		case XDP_PASS:
151 			skbs[pass++] = skb;
152 			break;
153 		case XDP_REDIRECT:
154 			err = xdp_do_generic_redirect(skb->dev, skb, &xdp,
155 						      rcpu->prog);
156 			if (unlikely(err)) {
157 				kfree_skb(skb);
158 				stats->drop++;
159 			} else {
160 				stats->redirect++;
161 			}
162 			break;
163 		default:
164 			bpf_warn_invalid_xdp_action(NULL, rcpu->prog, act);
165 			fallthrough;
166 		case XDP_ABORTED:
167 			trace_xdp_exception(skb->dev, rcpu->prog, act);
168 			fallthrough;
169 		case XDP_DROP:
170 			napi_consume_skb(skb, true);
171 			stats->drop++;
172 			break;
173 		}
174 	}
175 
176 	stats->pass += pass;
177 
178 	return pass;
179 }
180 
181 static int cpu_map_bpf_prog_run_xdp(struct bpf_cpu_map_entry *rcpu,
182 				    void **frames, int n,
183 				    struct xdp_cpumap_stats *stats)
184 {
185 	struct xdp_rxq_info rxq = {};
186 	struct xdp_buff xdp;
187 	int i, nframes = 0;
188 
189 	xdp_set_return_frame_no_direct();
190 	xdp.rxq = &rxq;
191 
192 	for (i = 0; i < n; i++) {
193 		struct xdp_frame *xdpf = frames[i];
194 		u32 act;
195 		int err;
196 
197 		rxq.dev = xdpf->dev_rx;
198 		rxq.mem.type = xdpf->mem_type;
199 		/* TODO: report queue_index to xdp_rxq_info */
200 
201 		xdp_convert_frame_to_buff(xdpf, &xdp);
202 
203 		act = bpf_prog_run_xdp(rcpu->prog, &xdp);
204 		switch (act) {
205 		case XDP_PASS:
206 			err = xdp_update_frame_from_buff(&xdp, xdpf);
207 			if (err < 0) {
208 				xdp_return_frame(xdpf);
209 				stats->drop++;
210 			} else {
211 				frames[nframes++] = xdpf;
212 			}
213 			break;
214 		case XDP_REDIRECT:
215 			err = xdp_do_redirect(xdpf->dev_rx, &xdp,
216 					      rcpu->prog);
217 			if (unlikely(err)) {
218 				xdp_return_frame(xdpf);
219 				stats->drop++;
220 			} else {
221 				stats->redirect++;
222 			}
223 			break;
224 		default:
225 			bpf_warn_invalid_xdp_action(NULL, rcpu->prog, act);
226 			fallthrough;
227 		case XDP_DROP:
228 			xdp_return_frame(xdpf);
229 			stats->drop++;
230 			break;
231 		}
232 	}
233 
234 	xdp_clear_return_frame_no_direct();
235 	stats->pass += nframes;
236 
237 	return nframes;
238 }
239 
240 #define CPUMAP_BATCH 8
241 
242 struct cpu_map_ret {
243 	u32 xdp_n;
244 	u32 skb_n;
245 };
246 
247 static void cpu_map_bpf_prog_run(struct bpf_cpu_map_entry *rcpu, void **frames,
248 				 void **skbs, struct cpu_map_ret *ret,
249 				 struct xdp_cpumap_stats *stats)
250 {
251 	struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
252 
253 	if (!rcpu->prog)
254 		goto out;
255 
256 	rcu_read_lock_bh();
257 	bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
258 
259 	ret->xdp_n = cpu_map_bpf_prog_run_xdp(rcpu, frames, ret->xdp_n, stats);
260 	if (unlikely(ret->skb_n))
261 		ret->skb_n = cpu_map_bpf_prog_run_skb(rcpu, skbs, ret->skb_n,
262 						      stats);
263 
264 	if (stats->redirect)
265 		xdp_do_flush();
266 
267 	bpf_net_ctx_clear(bpf_net_ctx);
268 	rcu_read_unlock_bh(); /* resched point, may call do_softirq() */
269 
270 out:
271 	if (unlikely(ret->skb_n) && ret->xdp_n)
272 		memmove(&skbs[ret->xdp_n], skbs, ret->skb_n * sizeof(*skbs));
273 }
274 
275 static void cpu_map_gro_flush(struct bpf_cpu_map_entry *rcpu, bool empty)
276 {
277 	/*
278 	 * If the ring is not empty, there'll be a new iteration soon, and we
279 	 * only need to do a full flush if a tick is long (> 1 ms).
280 	 * If the ring is empty, to not hold GRO packets in the stack for too
281 	 * long, do a full flush.
282 	 * This is equivalent to how NAPI decides whether to perform a full
283 	 * flush.
284 	 */
285 	gro_flush(&rcpu->gro, !empty && HZ >= 1000);
286 	gro_normal_list(&rcpu->gro);
287 }
288 
289 static int cpu_map_kthread_run(void *data)
290 {
291 	struct bpf_cpu_map_entry *rcpu = data;
292 	unsigned long last_qs = jiffies;
293 	u32 packets = 0;
294 
295 	complete(&rcpu->kthread_running);
296 	set_current_state(TASK_INTERRUPTIBLE);
297 
298 	/* When kthread gives stop order, then rcpu have been disconnected
299 	 * from map, thus no new packets can enter. Remaining in-flight
300 	 * per CPU stored packets are flushed to this queue.  Wait honoring
301 	 * kthread_stop signal until queue is empty.
302 	 */
303 	while (!kthread_should_stop() || !__ptr_ring_empty(rcpu->queue)) {
304 		struct xdp_cpumap_stats stats = {}; /* zero stats */
305 		unsigned int kmem_alloc_drops = 0, sched = 0;
306 		gfp_t gfp = __GFP_ZERO | GFP_ATOMIC;
307 		struct cpu_map_ret ret = { };
308 		void *frames[CPUMAP_BATCH];
309 		void *skbs[CPUMAP_BATCH];
310 		u32 i, n, m;
311 		bool empty;
312 
313 		/* Release CPU reschedule checks */
314 		if (__ptr_ring_empty(rcpu->queue)) {
315 			set_current_state(TASK_INTERRUPTIBLE);
316 			/* Recheck to avoid lost wake-up */
317 			if (__ptr_ring_empty(rcpu->queue)) {
318 				schedule();
319 				sched = 1;
320 				last_qs = jiffies;
321 			} else {
322 				__set_current_state(TASK_RUNNING);
323 			}
324 		} else {
325 			rcu_softirq_qs_periodic(last_qs);
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; 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 				skbs[ret.skb_n++] = skb;
345 				continue;
346 			}
347 
348 			frames[ret.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 		cpu_map_bpf_prog_run(rcpu, frames, skbs, &ret, &stats);
360 		if (!ret.xdp_n) {
361 			local_bh_disable();
362 			goto stats;
363 		}
364 
365 		m = kmem_cache_alloc_bulk(net_hotdata.skbuff_cache, gfp,
366 					  ret.xdp_n, skbs);
367 		if (unlikely(m < ret.xdp_n)) {
368 			for (i = m; i < ret.xdp_n; i++)
369 				xdp_return_frame(frames[i]);
370 
371 			if (ret.skb_n)
372 				memmove(&skbs[m], &skbs[ret.xdp_n],
373 					ret.skb_n * sizeof(*skbs));
374 
375 			kmem_alloc_drops += ret.xdp_n - m;
376 			ret.xdp_n = m;
377 		}
378 
379 		local_bh_disable();
380 		for (i = 0; i < ret.xdp_n; i++) {
381 			struct xdp_frame *xdpf = frames[i];
382 
383 			/* Can fail only when !skb -- already handled above */
384 			__xdp_build_skb_from_frame(xdpf, skbs[i], xdpf->dev_rx);
385 		}
386 
387 stats:
388 		/* Feedback loop via tracepoint.
389 		 * NB: keep before recv to allow measuring enqueue/dequeue latency.
390 		 */
391 		trace_xdp_cpumap_kthread(rcpu->map_id, n, kmem_alloc_drops,
392 					 sched, &stats);
393 
394 		for (i = 0; i < ret.xdp_n + ret.skb_n; i++)
395 			gro_receive_skb(&rcpu->gro, skbs[i]);
396 
397 		/* Flush either every 64 packets or in case of empty ring */
398 		packets += n;
399 		empty = __ptr_ring_empty(rcpu->queue);
400 		if (packets >= NAPI_POLL_WEIGHT || empty) {
401 			cpu_map_gro_flush(rcpu, empty);
402 			packets = 0;
403 		}
404 
405 		local_bh_enable(); /* resched point, may call do_softirq() */
406 	}
407 	__set_current_state(TASK_RUNNING);
408 
409 	return 0;
410 }
411 
412 static int __cpu_map_load_bpf_program(struct bpf_cpu_map_entry *rcpu,
413 				      struct bpf_map *map, int fd)
414 {
415 	struct bpf_prog *prog;
416 
417 	prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_XDP);
418 	if (IS_ERR(prog))
419 		return PTR_ERR(prog);
420 
421 	if (prog->expected_attach_type != BPF_XDP_CPUMAP ||
422 	    !bpf_prog_map_compatible(map, prog)) {
423 		bpf_prog_put(prog);
424 		return -EINVAL;
425 	}
426 
427 	rcpu->value.bpf_prog.id = prog->aux->id;
428 	rcpu->prog = prog;
429 
430 	return 0;
431 }
432 
433 static struct bpf_cpu_map_entry *
434 __cpu_map_entry_alloc(struct bpf_map *map, struct bpf_cpumap_val *value,
435 		      u32 cpu)
436 {
437 	int numa, err, i, fd = value->bpf_prog.fd;
438 	gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
439 	struct bpf_cpu_map_entry *rcpu;
440 	struct xdp_bulk_queue *bq;
441 
442 	/* Have map->numa_node, but choose node of redirect target CPU */
443 	numa = cpu_to_node(cpu);
444 
445 	rcpu = bpf_map_kmalloc_node(map, sizeof(*rcpu), gfp | __GFP_ZERO, numa);
446 	if (!rcpu)
447 		return NULL;
448 
449 	/* Alloc percpu bulkq */
450 	rcpu->bulkq = bpf_map_alloc_percpu(map, sizeof(*rcpu->bulkq),
451 					   sizeof(void *), gfp);
452 	if (!rcpu->bulkq)
453 		goto free_rcu;
454 
455 	for_each_possible_cpu(i) {
456 		bq = per_cpu_ptr(rcpu->bulkq, i);
457 		bq->obj = rcpu;
458 	}
459 
460 	/* Alloc queue */
461 	rcpu->queue = bpf_map_kmalloc_node(map, sizeof(*rcpu->queue), gfp,
462 					   numa);
463 	if (!rcpu->queue)
464 		goto free_bulkq;
465 
466 	err = ptr_ring_init(rcpu->queue, value->qsize, gfp);
467 	if (err)
468 		goto free_queue;
469 
470 	rcpu->cpu    = cpu;
471 	rcpu->map_id = map->id;
472 	rcpu->value.qsize  = value->qsize;
473 	gro_init(&rcpu->gro);
474 
475 	if (fd > 0 && __cpu_map_load_bpf_program(rcpu, map, fd))
476 		goto free_ptr_ring;
477 
478 	/* Setup kthread */
479 	init_completion(&rcpu->kthread_running);
480 	rcpu->kthread = kthread_create_on_node(cpu_map_kthread_run, rcpu, numa,
481 					       "cpumap/%d/map:%d", cpu,
482 					       map->id);
483 	if (IS_ERR(rcpu->kthread))
484 		goto free_prog;
485 
486 	/* Make sure kthread runs on a single CPU */
487 	kthread_bind(rcpu->kthread, cpu);
488 	wake_up_process(rcpu->kthread);
489 
490 	/* Make sure kthread has been running, so kthread_stop() will not
491 	 * stop the kthread prematurely and all pending frames or skbs
492 	 * will be handled by the kthread before kthread_stop() returns.
493 	 */
494 	wait_for_completion(&rcpu->kthread_running);
495 
496 	return rcpu;
497 
498 free_prog:
499 	if (rcpu->prog)
500 		bpf_prog_put(rcpu->prog);
501 free_ptr_ring:
502 	gro_cleanup(&rcpu->gro);
503 	ptr_ring_cleanup(rcpu->queue, NULL);
504 free_queue:
505 	kfree(rcpu->queue);
506 free_bulkq:
507 	free_percpu(rcpu->bulkq);
508 free_rcu:
509 	kfree(rcpu);
510 	return NULL;
511 }
512 
513 static void __cpu_map_entry_free(struct work_struct *work)
514 {
515 	struct bpf_cpu_map_entry *rcpu;
516 
517 	/* This cpu_map_entry have been disconnected from map and one
518 	 * RCU grace-period have elapsed. Thus, XDP cannot queue any
519 	 * new packets and cannot change/set flush_needed that can
520 	 * find this entry.
521 	 */
522 	rcpu = container_of(to_rcu_work(work), struct bpf_cpu_map_entry, free_work);
523 
524 	/* kthread_stop will wake_up_process and wait for it to complete.
525 	 * cpu_map_kthread_run() makes sure the pointer ring is empty
526 	 * before exiting.
527 	 */
528 	kthread_stop(rcpu->kthread);
529 
530 	if (rcpu->prog)
531 		bpf_prog_put(rcpu->prog);
532 	gro_cleanup(&rcpu->gro);
533 	/* The queue should be empty at this point */
534 	__cpu_map_ring_cleanup(rcpu->queue);
535 	ptr_ring_cleanup(rcpu->queue, NULL);
536 	kfree(rcpu->queue);
537 	free_percpu(rcpu->bulkq);
538 	kfree(rcpu);
539 }
540 
541 /* After the xchg of the bpf_cpu_map_entry pointer, we need to make sure the old
542  * entry is no longer in use before freeing. We use queue_rcu_work() to call
543  * __cpu_map_entry_free() in a separate workqueue after waiting for an RCU grace
544  * period. This means that (a) all pending enqueue and flush operations have
545  * completed (because of the RCU callback), and (b) we are in a workqueue
546  * context where we can stop the kthread and wait for it to exit before freeing
547  * everything.
548  */
549 static void __cpu_map_entry_replace(struct bpf_cpu_map *cmap,
550 				    u32 key_cpu, struct bpf_cpu_map_entry *rcpu)
551 {
552 	struct bpf_cpu_map_entry *old_rcpu;
553 
554 	old_rcpu = unrcu_pointer(xchg(&cmap->cpu_map[key_cpu], RCU_INITIALIZER(rcpu)));
555 	if (old_rcpu) {
556 		INIT_RCU_WORK(&old_rcpu->free_work, __cpu_map_entry_free);
557 		queue_rcu_work(system_wq, &old_rcpu->free_work);
558 	}
559 }
560 
561 static long cpu_map_delete_elem(struct bpf_map *map, void *key)
562 {
563 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
564 	u32 key_cpu = *(u32 *)key;
565 
566 	if (key_cpu >= map->max_entries)
567 		return -EINVAL;
568 
569 	/* notice caller map_delete_elem() uses rcu_read_lock() */
570 	__cpu_map_entry_replace(cmap, key_cpu, NULL);
571 	return 0;
572 }
573 
574 static long cpu_map_update_elem(struct bpf_map *map, void *key, void *value,
575 				u64 map_flags)
576 {
577 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
578 	struct bpf_cpumap_val cpumap_value = {};
579 	struct bpf_cpu_map_entry *rcpu;
580 	/* Array index key correspond to CPU number */
581 	u32 key_cpu = *(u32 *)key;
582 
583 	memcpy(&cpumap_value, value, map->value_size);
584 
585 	if (unlikely(map_flags > BPF_EXIST))
586 		return -EINVAL;
587 	if (unlikely(key_cpu >= cmap->map.max_entries))
588 		return -E2BIG;
589 	if (unlikely(map_flags == BPF_NOEXIST))
590 		return -EEXIST;
591 	if (unlikely(cpumap_value.qsize > 16384)) /* sanity limit on qsize */
592 		return -EOVERFLOW;
593 
594 	/* Make sure CPU is a valid possible cpu */
595 	if (key_cpu >= nr_cpumask_bits || !cpu_possible(key_cpu))
596 		return -ENODEV;
597 
598 	if (cpumap_value.qsize == 0) {
599 		rcpu = NULL; /* Same as deleting */
600 	} else {
601 		/* Updating qsize cause re-allocation of bpf_cpu_map_entry */
602 		rcpu = __cpu_map_entry_alloc(map, &cpumap_value, key_cpu);
603 		if (!rcpu)
604 			return -ENOMEM;
605 	}
606 	rcu_read_lock();
607 	__cpu_map_entry_replace(cmap, key_cpu, rcpu);
608 	rcu_read_unlock();
609 	return 0;
610 }
611 
612 static void cpu_map_free(struct bpf_map *map)
613 {
614 	struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
615 	u32 i;
616 
617 	/* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
618 	 * so the bpf programs (can be more than one that used this map) were
619 	 * disconnected from events. Wait for outstanding critical sections in
620 	 * these programs to complete. synchronize_rcu() below not only
621 	 * guarantees no further "XDP/bpf-side" reads against
622 	 * bpf_cpu_map->cpu_map, but also ensure pending flush operations
623 	 * (if any) are completed.
624 	 */
625 	synchronize_rcu();
626 
627 	/* The only possible user of bpf_cpu_map_entry is
628 	 * cpu_map_kthread_run().
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 		/* Stop kthread and cleanup entry directly */
638 		__cpu_map_entry_free(&rcpu->free_work.work);
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  */
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 
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 
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 
686 static long cpu_map_redirect(struct bpf_map *map, u64 index, u64 flags)
687 {
688 	return __bpf_xdp_redirect_map(map, index, flags, 0,
689 				      __cpu_map_lookup_elem);
690 }
691 
692 static u64 cpu_map_mem_usage(const struct bpf_map *map)
693 {
694 	u64 usage = sizeof(struct bpf_cpu_map);
695 
696 	/* Currently the dynamically allocated elements are not counted */
697 	usage += (u64)map->max_entries * sizeof(struct bpf_cpu_map_entry *);
698 	return usage;
699 }
700 
701 BTF_ID_LIST_SINGLE(cpu_map_btf_ids, struct, bpf_cpu_map)
702 const struct bpf_map_ops cpu_map_ops = {
703 	.map_meta_equal		= bpf_map_meta_equal,
704 	.map_alloc		= cpu_map_alloc,
705 	.map_free		= cpu_map_free,
706 	.map_delete_elem	= cpu_map_delete_elem,
707 	.map_update_elem	= cpu_map_update_elem,
708 	.map_lookup_elem	= cpu_map_lookup_elem,
709 	.map_get_next_key	= cpu_map_get_next_key,
710 	.map_check_btf		= map_check_no_btf,
711 	.map_mem_usage		= cpu_map_mem_usage,
712 	.map_btf_id		= &cpu_map_btf_ids[0],
713 	.map_redirect		= cpu_map_redirect,
714 };
715 
716 static void bq_flush_to_queue(struct xdp_bulk_queue *bq)
717 {
718 	struct bpf_cpu_map_entry *rcpu = bq->obj;
719 	unsigned int processed = 0, drops = 0;
720 	const int to_cpu = rcpu->cpu;
721 	struct ptr_ring *q;
722 	int i;
723 
724 	if (unlikely(!bq->count))
725 		return;
726 
727 	q = rcpu->queue;
728 	spin_lock(&q->producer_lock);
729 
730 	for (i = 0; i < bq->count; i++) {
731 		struct xdp_frame *xdpf = bq->q[i];
732 		int err;
733 
734 		err = __ptr_ring_produce(q, xdpf);
735 		if (err) {
736 			drops++;
737 			xdp_return_frame_rx_napi(xdpf);
738 		}
739 		processed++;
740 	}
741 	bq->count = 0;
742 	spin_unlock(&q->producer_lock);
743 
744 	__list_del_clearprev(&bq->flush_node);
745 
746 	/* Feedback loop via tracepoints */
747 	trace_xdp_cpumap_enqueue(rcpu->map_id, processed, drops, to_cpu);
748 }
749 
750 /* Runs under RCU-read-side, plus in softirq under NAPI protection.
751  * Thus, safe percpu variable access.
752  */
753 static void bq_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_frame *xdpf)
754 {
755 	struct xdp_bulk_queue *bq = this_cpu_ptr(rcpu->bulkq);
756 
757 	if (unlikely(bq->count == CPU_MAP_BULK_SIZE))
758 		bq_flush_to_queue(bq);
759 
760 	/* Notice, xdp_buff/page MUST be queued here, long enough for
761 	 * driver to code invoking us to finished, due to driver
762 	 * (e.g. ixgbe) recycle tricks based on page-refcnt.
763 	 *
764 	 * Thus, incoming xdp_frame is always queued here (else we race
765 	 * with another CPU on page-refcnt and remaining driver code).
766 	 * Queue time is very short, as driver will invoke flush
767 	 * operation, when completing napi->poll call.
768 	 */
769 	bq->q[bq->count++] = xdpf;
770 
771 	if (!bq->flush_node.prev) {
772 		struct list_head *flush_list = bpf_net_ctx_get_cpu_map_flush_list();
773 
774 		list_add(&bq->flush_node, flush_list);
775 	}
776 }
777 
778 int cpu_map_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_frame *xdpf,
779 		    struct net_device *dev_rx)
780 {
781 	/* Info needed when constructing SKB on remote CPU */
782 	xdpf->dev_rx = dev_rx;
783 
784 	bq_enqueue(rcpu, xdpf);
785 	return 0;
786 }
787 
788 int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu,
789 			     struct sk_buff *skb)
790 {
791 	int ret;
792 
793 	__skb_pull(skb, skb->mac_len);
794 	skb_set_redirected(skb, false);
795 	__ptr_set_bit(0, &skb);
796 
797 	ret = ptr_ring_produce(rcpu->queue, skb);
798 	if (ret < 0)
799 		goto trace;
800 
801 	wake_up_process(rcpu->kthread);
802 trace:
803 	trace_xdp_cpumap_enqueue(rcpu->map_id, !ret, !!ret, rcpu->cpu);
804 	return ret;
805 }
806 
807 void __cpu_map_flush(struct list_head *flush_list)
808 {
809 	struct xdp_bulk_queue *bq, *tmp;
810 
811 	list_for_each_entry_safe(bq, tmp, flush_list, flush_node) {
812 		bq_flush_to_queue(bq);
813 
814 		/* If already running, costs spin_lock_irqsave + smb_mb */
815 		wake_up_process(bq->obj->kthread);
816 	}
817 }
818