1 // SPDX-License-Identifier: GPL-2.0-only
4 * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
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'.
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.
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.
19 #include <linux/bpf.h>
20 #include <linux/filter.h>
21 #include <linux/ptr_ring.h>
24 #include <linux/sched.h>
25 #include <linux/workqueue.h>
26 #include <linux/kthread.h>
27 #include <linux/capability.h>
28 #include <trace/events/xdp.h>
30 #include <linux/netdevice.h> /* netif_receive_skb_list */
31 #include <linux/etherdevice.h> /* eth_type_trans */
33 /* General idea: XDP packets getting XDP redirected to another CPU,
34 * will maximum be stored/queued for one driver ->poll() call. It is
35 * guaranteed that queueing the frame and the flush operation happen on
36 * same CPU. Thus, cpu_map_flush operation can deduct via this_cpu_ptr()
37 * which queue in bpf_cpu_map_entry contains packets.
40 #define CPU_MAP_BULK_SIZE 8 /* 8 == one cacheline on 64-bit archs */
41 struct bpf_cpu_map_entry;
44 struct xdp_bulk_queue {
45 void *q[CPU_MAP_BULK_SIZE];
46 struct list_head flush_node;
47 struct bpf_cpu_map_entry *obj;
51 /* Struct for every remote "destination" CPU in map */
52 struct bpf_cpu_map_entry {
53 u32 cpu; /* kthread CPU and map index */
54 int map_id; /* Back reference to map */
56 /* XDP can run multiple RX-ring queues, need __percpu enqueue store */
57 struct xdp_bulk_queue __percpu *bulkq;
59 struct bpf_cpu_map *cmap;
61 /* Queue with potential multi-producers, and single-consumer kthread */
62 struct ptr_ring *queue;
63 struct task_struct *kthread;
65 struct bpf_cpumap_val value;
66 struct bpf_prog *prog;
68 atomic_t refcnt; /* Control when this struct can be free'ed */
71 struct work_struct kthread_stop_wq;
76 /* Below members specific for map type */
77 struct bpf_cpu_map_entry **cpu_map;
80 static DEFINE_PER_CPU(struct list_head, cpu_map_flush_list);
82 static struct bpf_map *cpu_map_alloc(union bpf_attr *attr)
84 u32 value_size = attr->value_size;
85 struct bpf_cpu_map *cmap;
89 return ERR_PTR(-EPERM);
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);
98 cmap = kzalloc(sizeof(*cmap), GFP_USER | __GFP_ACCOUNT);
100 return ERR_PTR(-ENOMEM);
102 bpf_map_init_from_attr(&cmap->map, attr);
104 /* Pre-limit array size based on NR_CPUS, not final CPU check */
105 if (cmap->map.max_entries > NR_CPUS) {
110 /* Alloc array for possible remote "destination" CPUs */
111 cmap->cpu_map = bpf_map_area_alloc(cmap->map.max_entries *
112 sizeof(struct bpf_cpu_map_entry *),
113 cmap->map.numa_node);
123 static void get_cpu_map_entry(struct bpf_cpu_map_entry *rcpu)
125 atomic_inc(&rcpu->refcnt);
128 /* called from workqueue, to workaround syscall using preempt_disable */
129 static void cpu_map_kthread_stop(struct work_struct *work)
131 struct bpf_cpu_map_entry *rcpu;
133 rcpu = container_of(work, struct bpf_cpu_map_entry, kthread_stop_wq);
135 /* Wait for flush in __cpu_map_entry_free(), via full RCU barrier,
136 * as it waits until all in-flight call_rcu() callbacks complete.
140 /* kthread_stop will wake_up_process and wait for it to complete */
141 kthread_stop(rcpu->kthread);
144 static void __cpu_map_ring_cleanup(struct ptr_ring *ring)
146 /* The tear-down procedure should have made sure that queue is
147 * empty. See __cpu_map_entry_replace() and work-queue
148 * invoked cpu_map_kthread_stop(). Catch any broken behaviour
149 * gracefully and warn once.
151 struct xdp_frame *xdpf;
153 while ((xdpf = ptr_ring_consume(ring)))
154 if (WARN_ON_ONCE(xdpf))
155 xdp_return_frame(xdpf);
158 static void put_cpu_map_entry(struct bpf_cpu_map_entry *rcpu)
160 if (atomic_dec_and_test(&rcpu->refcnt)) {
162 bpf_prog_put(rcpu->prog);
163 /* The queue should be empty at this point */
164 __cpu_map_ring_cleanup(rcpu->queue);
165 ptr_ring_cleanup(rcpu->queue, NULL);
171 static int cpu_map_bpf_prog_run_xdp(struct bpf_cpu_map_entry *rcpu,
172 void **frames, int n,
173 struct xdp_cpumap_stats *stats)
175 struct xdp_rxq_info rxq;
184 xdp_set_return_frame_no_direct();
187 for (i = 0; i < n; i++) {
188 struct xdp_frame *xdpf = frames[i];
192 rxq.dev = xdpf->dev_rx;
194 /* TODO: report queue_index to xdp_rxq_info */
196 xdp_convert_frame_to_buff(xdpf, &xdp);
198 act = bpf_prog_run_xdp(rcpu->prog, &xdp);
201 err = xdp_update_frame_from_buff(&xdp, xdpf);
203 xdp_return_frame(xdpf);
206 frames[nframes++] = xdpf;
211 err = xdp_do_redirect(xdpf->dev_rx, &xdp,
214 xdp_return_frame(xdpf);
221 bpf_warn_invalid_xdp_action(act);
224 xdp_return_frame(xdpf);
233 xdp_clear_return_frame_no_direct();
235 rcu_read_unlock_bh(); /* resched point, may call do_softirq() */
240 #define CPUMAP_BATCH 8
242 static int cpu_map_kthread_run(void *data)
244 struct bpf_cpu_map_entry *rcpu = data;
246 set_current_state(TASK_INTERRUPTIBLE);
248 /* When kthread gives stop order, then rcpu have been disconnected
249 * from map, thus no new packets can enter. Remaining in-flight
250 * per CPU stored packets are flushed to this queue. Wait honoring
251 * kthread_stop signal until queue is empty.
253 while (!kthread_should_stop() || !__ptr_ring_empty(rcpu->queue)) {
254 struct xdp_cpumap_stats stats = {}; /* zero stats */
255 unsigned int kmem_alloc_drops = 0, sched = 0;
256 gfp_t gfp = __GFP_ZERO | GFP_ATOMIC;
257 void *frames[CPUMAP_BATCH];
258 void *skbs[CPUMAP_BATCH];
259 int i, n, m, nframes;
262 /* Release CPU reschedule checks */
263 if (__ptr_ring_empty(rcpu->queue)) {
264 set_current_state(TASK_INTERRUPTIBLE);
265 /* Recheck to avoid lost wake-up */
266 if (__ptr_ring_empty(rcpu->queue)) {
270 __set_current_state(TASK_RUNNING);
273 sched = cond_resched();
277 * The bpf_cpu_map_entry is single consumer, with this
278 * kthread CPU pinned. Lockless access to ptr_ring
279 * consume side valid as no-resize allowed of queue.
281 n = __ptr_ring_consume_batched(rcpu->queue, frames,
283 for (i = 0; i < n; i++) {
285 struct page *page = virt_to_page(f);
287 /* Bring struct page memory area to curr CPU. Read by
288 * build_skb_around via page_is_pfmemalloc(), and when
289 * freed written by page_frag_free call.
294 /* Support running another XDP prog on this CPU */
295 nframes = cpu_map_bpf_prog_run_xdp(rcpu, frames, n, &stats);
297 m = kmem_cache_alloc_bulk(skbuff_head_cache, gfp, nframes, skbs);
298 if (unlikely(m == 0)) {
299 for (i = 0; i < nframes; i++)
300 skbs[i] = NULL; /* effect: xdp_return_frame */
301 kmem_alloc_drops += nframes;
306 for (i = 0; i < nframes; i++) {
307 struct xdp_frame *xdpf = frames[i];
308 struct sk_buff *skb = skbs[i];
310 skb = __xdp_build_skb_from_frame(xdpf, skb,
313 xdp_return_frame(xdpf);
317 list_add_tail(&skb->list, &list);
319 netif_receive_skb_list(&list);
321 /* Feedback loop via tracepoint */
322 trace_xdp_cpumap_kthread(rcpu->map_id, n, kmem_alloc_drops,
325 local_bh_enable(); /* resched point, may call do_softirq() */
327 __set_current_state(TASK_RUNNING);
329 put_cpu_map_entry(rcpu);
333 bool cpu_map_prog_allowed(struct bpf_map *map)
335 return map->map_type == BPF_MAP_TYPE_CPUMAP &&
336 map->value_size != offsetofend(struct bpf_cpumap_val, qsize);
339 static int __cpu_map_load_bpf_program(struct bpf_cpu_map_entry *rcpu, int fd)
341 struct bpf_prog *prog;
343 prog = bpf_prog_get_type(fd, BPF_PROG_TYPE_XDP);
345 return PTR_ERR(prog);
347 if (prog->expected_attach_type != BPF_XDP_CPUMAP) {
352 rcpu->value.bpf_prog.id = prog->aux->id;
358 static struct bpf_cpu_map_entry *
359 __cpu_map_entry_alloc(struct bpf_map *map, struct bpf_cpumap_val *value,
362 int numa, err, i, fd = value->bpf_prog.fd;
363 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
364 struct bpf_cpu_map_entry *rcpu;
365 struct xdp_bulk_queue *bq;
367 /* Have map->numa_node, but choose node of redirect target CPU */
368 numa = cpu_to_node(cpu);
370 rcpu = bpf_map_kmalloc_node(map, sizeof(*rcpu), gfp | __GFP_ZERO, numa);
374 /* Alloc percpu bulkq */
375 rcpu->bulkq = bpf_map_alloc_percpu(map, sizeof(*rcpu->bulkq),
376 sizeof(void *), gfp);
380 for_each_possible_cpu(i) {
381 bq = per_cpu_ptr(rcpu->bulkq, i);
386 rcpu->queue = bpf_map_kmalloc_node(map, sizeof(*rcpu->queue), gfp,
391 err = ptr_ring_init(rcpu->queue, value->qsize, gfp);
396 rcpu->map_id = map->id;
397 rcpu->value.qsize = value->qsize;
399 if (fd > 0 && __cpu_map_load_bpf_program(rcpu, fd))
403 rcpu->kthread = kthread_create_on_node(cpu_map_kthread_run, rcpu, numa,
404 "cpumap/%d/map:%d", cpu,
406 if (IS_ERR(rcpu->kthread))
409 get_cpu_map_entry(rcpu); /* 1-refcnt for being in cmap->cpu_map[] */
410 get_cpu_map_entry(rcpu); /* 1-refcnt for kthread */
412 /* Make sure kthread runs on a single CPU */
413 kthread_bind(rcpu->kthread, cpu);
414 wake_up_process(rcpu->kthread);
420 bpf_prog_put(rcpu->prog);
422 ptr_ring_cleanup(rcpu->queue, NULL);
426 free_percpu(rcpu->bulkq);
432 static void __cpu_map_entry_free(struct rcu_head *rcu)
434 struct bpf_cpu_map_entry *rcpu;
436 /* This cpu_map_entry have been disconnected from map and one
437 * RCU grace-period have elapsed. Thus, XDP cannot queue any
438 * new packets and cannot change/set flush_needed that can
441 rcpu = container_of(rcu, struct bpf_cpu_map_entry, rcu);
443 free_percpu(rcpu->bulkq);
444 /* Cannot kthread_stop() here, last put free rcpu resources */
445 put_cpu_map_entry(rcpu);
448 /* After xchg pointer to bpf_cpu_map_entry, use the call_rcu() to
449 * ensure any driver rcu critical sections have completed, but this
450 * does not guarantee a flush has happened yet. Because driver side
451 * rcu_read_lock/unlock only protects the running XDP program. The
452 * atomic xchg and NULL-ptr check in __cpu_map_flush() makes sure a
453 * pending flush op doesn't fail.
455 * The bpf_cpu_map_entry is still used by the kthread, and there can
456 * still be pending packets (in queue and percpu bulkq). A refcnt
457 * makes sure to last user (kthread_stop vs. call_rcu) free memory
460 * The rcu callback __cpu_map_entry_free flush remaining packets in
461 * percpu bulkq to queue. Due to caller map_delete_elem() disable
462 * preemption, cannot call kthread_stop() to make sure queue is empty.
463 * Instead a work_queue is started for stopping kthread,
464 * cpu_map_kthread_stop, which waits for an RCU grace period before
465 * stopping kthread, emptying the queue.
467 static void __cpu_map_entry_replace(struct bpf_cpu_map *cmap,
468 u32 key_cpu, struct bpf_cpu_map_entry *rcpu)
470 struct bpf_cpu_map_entry *old_rcpu;
472 old_rcpu = xchg(&cmap->cpu_map[key_cpu], rcpu);
474 call_rcu(&old_rcpu->rcu, __cpu_map_entry_free);
475 INIT_WORK(&old_rcpu->kthread_stop_wq, cpu_map_kthread_stop);
476 schedule_work(&old_rcpu->kthread_stop_wq);
480 static int cpu_map_delete_elem(struct bpf_map *map, void *key)
482 struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
483 u32 key_cpu = *(u32 *)key;
485 if (key_cpu >= map->max_entries)
488 /* notice caller map_delete_elem() use preempt_disable() */
489 __cpu_map_entry_replace(cmap, key_cpu, NULL);
493 static int cpu_map_update_elem(struct bpf_map *map, void *key, void *value,
496 struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
497 struct bpf_cpumap_val cpumap_value = {};
498 struct bpf_cpu_map_entry *rcpu;
499 /* Array index key correspond to CPU number */
500 u32 key_cpu = *(u32 *)key;
502 memcpy(&cpumap_value, value, map->value_size);
504 if (unlikely(map_flags > BPF_EXIST))
506 if (unlikely(key_cpu >= cmap->map.max_entries))
508 if (unlikely(map_flags == BPF_NOEXIST))
510 if (unlikely(cpumap_value.qsize > 16384)) /* sanity limit on qsize */
513 /* Make sure CPU is a valid possible cpu */
514 if (key_cpu >= nr_cpumask_bits || !cpu_possible(key_cpu))
517 if (cpumap_value.qsize == 0) {
518 rcpu = NULL; /* Same as deleting */
520 /* Updating qsize cause re-allocation of bpf_cpu_map_entry */
521 rcpu = __cpu_map_entry_alloc(map, &cpumap_value, key_cpu);
527 __cpu_map_entry_replace(cmap, key_cpu, rcpu);
532 static void cpu_map_free(struct bpf_map *map)
534 struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
537 /* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
538 * so the bpf programs (can be more than one that used this map) were
539 * disconnected from events. Wait for outstanding critical sections in
540 * these programs to complete. The rcu critical section only guarantees
541 * no further "XDP/bpf-side" reads against bpf_cpu_map->cpu_map.
542 * It does __not__ ensure pending flush operations (if any) are
548 /* For cpu_map the remote CPUs can still be using the entries
549 * (struct bpf_cpu_map_entry).
551 for (i = 0; i < cmap->map.max_entries; i++) {
552 struct bpf_cpu_map_entry *rcpu;
554 rcpu = READ_ONCE(cmap->cpu_map[i]);
558 /* bq flush and cleanup happens after RCU grace-period */
559 __cpu_map_entry_replace(cmap, i, NULL); /* call_rcu */
561 bpf_map_area_free(cmap->cpu_map);
565 static void *__cpu_map_lookup_elem(struct bpf_map *map, u32 key)
567 struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
568 struct bpf_cpu_map_entry *rcpu;
570 if (key >= map->max_entries)
573 rcpu = READ_ONCE(cmap->cpu_map[key]);
577 static void *cpu_map_lookup_elem(struct bpf_map *map, void *key)
579 struct bpf_cpu_map_entry *rcpu =
580 __cpu_map_lookup_elem(map, *(u32 *)key);
582 return rcpu ? &rcpu->value : NULL;
585 static int cpu_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
587 struct bpf_cpu_map *cmap = container_of(map, struct bpf_cpu_map, map);
588 u32 index = key ? *(u32 *)key : U32_MAX;
589 u32 *next = next_key;
591 if (index >= cmap->map.max_entries) {
596 if (index == cmap->map.max_entries - 1)
602 static int cpu_map_redirect(struct bpf_map *map, u32 ifindex, u64 flags)
604 return __bpf_xdp_redirect_map(map, ifindex, flags, __cpu_map_lookup_elem);
607 static int cpu_map_btf_id;
608 const struct bpf_map_ops cpu_map_ops = {
609 .map_meta_equal = bpf_map_meta_equal,
610 .map_alloc = cpu_map_alloc,
611 .map_free = cpu_map_free,
612 .map_delete_elem = cpu_map_delete_elem,
613 .map_update_elem = cpu_map_update_elem,
614 .map_lookup_elem = cpu_map_lookup_elem,
615 .map_get_next_key = cpu_map_get_next_key,
616 .map_check_btf = map_check_no_btf,
617 .map_btf_name = "bpf_cpu_map",
618 .map_btf_id = &cpu_map_btf_id,
619 .map_redirect = cpu_map_redirect,
622 static void bq_flush_to_queue(struct xdp_bulk_queue *bq)
624 struct bpf_cpu_map_entry *rcpu = bq->obj;
625 unsigned int processed = 0, drops = 0;
626 const int to_cpu = rcpu->cpu;
630 if (unlikely(!bq->count))
634 spin_lock(&q->producer_lock);
636 for (i = 0; i < bq->count; i++) {
637 struct xdp_frame *xdpf = bq->q[i];
640 err = __ptr_ring_produce(q, xdpf);
643 xdp_return_frame_rx_napi(xdpf);
648 spin_unlock(&q->producer_lock);
650 __list_del_clearprev(&bq->flush_node);
652 /* Feedback loop via tracepoints */
653 trace_xdp_cpumap_enqueue(rcpu->map_id, processed, drops, to_cpu);
656 /* Runs under RCU-read-side, plus in softirq under NAPI protection.
657 * Thus, safe percpu variable access.
659 static void bq_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_frame *xdpf)
661 struct list_head *flush_list = this_cpu_ptr(&cpu_map_flush_list);
662 struct xdp_bulk_queue *bq = this_cpu_ptr(rcpu->bulkq);
664 if (unlikely(bq->count == CPU_MAP_BULK_SIZE))
665 bq_flush_to_queue(bq);
667 /* Notice, xdp_buff/page MUST be queued here, long enough for
668 * driver to code invoking us to finished, due to driver
669 * (e.g. ixgbe) recycle tricks based on page-refcnt.
671 * Thus, incoming xdp_frame is always queued here (else we race
672 * with another CPU on page-refcnt and remaining driver code).
673 * Queue time is very short, as driver will invoke flush
674 * operation, when completing napi->poll call.
676 bq->q[bq->count++] = xdpf;
678 if (!bq->flush_node.prev)
679 list_add(&bq->flush_node, flush_list);
682 int cpu_map_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_buff *xdp,
683 struct net_device *dev_rx)
685 struct xdp_frame *xdpf;
687 xdpf = xdp_convert_buff_to_frame(xdp);
691 /* Info needed when constructing SKB on remote CPU */
692 xdpf->dev_rx = dev_rx;
694 bq_enqueue(rcpu, xdpf);
698 void __cpu_map_flush(void)
700 struct list_head *flush_list = this_cpu_ptr(&cpu_map_flush_list);
701 struct xdp_bulk_queue *bq, *tmp;
703 list_for_each_entry_safe(bq, tmp, flush_list, flush_node) {
704 bq_flush_to_queue(bq);
706 /* If already running, costs spin_lock_irqsave + smb_mb */
707 wake_up_process(bq->obj->kthread);
711 static int __init cpu_map_init(void)
715 for_each_possible_cpu(cpu)
716 INIT_LIST_HEAD(&per_cpu(cpu_map_flush_list, cpu));
720 subsys_initcall(cpu_map_init);