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