3 * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
4 * Released under terms in GPL version 2. See COPYING.
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>
23 #include <linux/sched.h>
24 #include <linux/workqueue.h>
25 #include <linux/kthread.h>
26 #include <linux/capability.h>
27 #include <trace/events/xdp.h>
29 #include <linux/netdevice.h> /* netif_receive_skb_core */
30 #include <linux/etherdevice.h> /* eth_type_trans */
32 /* General idea: XDP packets getting XDP redirected to another CPU,
33 * will maximum be stored/queued for one driver ->poll() call. It is
34 * guaranteed that setting flush bit and flush operation happen on
35 * same CPU. Thus, cpu_map_flush operation can deduct via this_cpu_ptr()
36 * which queue in bpf_cpu_map_entry contains packets.
39 #define CPU_MAP_BULK_SIZE 8 /* 8 == one cacheline on 64-bit archs */
40 struct xdp_bulk_queue
{
41 void *q
[CPU_MAP_BULK_SIZE
];
45 /* Struct for every remote "destination" CPU in map */
46 struct bpf_cpu_map_entry
{
47 u32 cpu
; /* kthread CPU and map index */
48 int map_id
; /* Back reference to map */
49 u32 qsize
; /* Queue size placeholder for map lookup */
51 /* XDP can run multiple RX-ring queues, need __percpu enqueue store */
52 struct xdp_bulk_queue __percpu
*bulkq
;
54 /* Queue with potential multi-producers, and single-consumer kthread */
55 struct ptr_ring
*queue
;
56 struct task_struct
*kthread
;
57 struct work_struct kthread_stop_wq
;
59 atomic_t refcnt
; /* Control when this struct can be free'ed */
65 /* Below members specific for map type */
66 struct bpf_cpu_map_entry
**cpu_map
;
67 unsigned long __percpu
*flush_needed
;
70 static int bq_flush_to_queue(struct bpf_cpu_map_entry
*rcpu
,
71 struct xdp_bulk_queue
*bq
);
73 static u64
cpu_map_bitmap_size(const union bpf_attr
*attr
)
75 return BITS_TO_LONGS(attr
->max_entries
) * sizeof(unsigned long);
78 static struct bpf_map
*cpu_map_alloc(union bpf_attr
*attr
)
80 struct bpf_cpu_map
*cmap
;
85 if (!capable(CAP_SYS_ADMIN
))
86 return ERR_PTR(-EPERM
);
88 /* check sanity of attributes */
89 if (attr
->max_entries
== 0 || attr
->key_size
!= 4 ||
90 attr
->value_size
!= 4 || attr
->map_flags
& ~BPF_F_NUMA_NODE
)
91 return ERR_PTR(-EINVAL
);
93 cmap
= kzalloc(sizeof(*cmap
), GFP_USER
);
95 return ERR_PTR(-ENOMEM
);
97 /* mandatory map attributes */
98 cmap
->map
.map_type
= attr
->map_type
;
99 cmap
->map
.key_size
= attr
->key_size
;
100 cmap
->map
.value_size
= attr
->value_size
;
101 cmap
->map
.max_entries
= attr
->max_entries
;
102 cmap
->map
.map_flags
= attr
->map_flags
;
103 cmap
->map
.numa_node
= bpf_map_attr_numa_node(attr
);
105 /* Pre-limit array size based on NR_CPUS, not final CPU check */
106 if (cmap
->map
.max_entries
> NR_CPUS
) {
111 /* make sure page count doesn't overflow */
112 cost
= (u64
) cmap
->map
.max_entries
* sizeof(struct bpf_cpu_map_entry
*);
113 cost
+= cpu_map_bitmap_size(attr
) * num_possible_cpus();
114 if (cost
>= U32_MAX
- PAGE_SIZE
)
116 cmap
->map
.pages
= round_up(cost
, PAGE_SIZE
) >> PAGE_SHIFT
;
118 /* Notice returns -EPERM on if map size is larger than memlock limit */
119 ret
= bpf_map_precharge_memlock(cmap
->map
.pages
);
125 /* A per cpu bitfield with a bit per possible CPU in map */
126 cmap
->flush_needed
= __alloc_percpu(cpu_map_bitmap_size(attr
),
127 __alignof__(unsigned long));
128 if (!cmap
->flush_needed
)
131 /* Alloc array for possible remote "destination" CPUs */
132 cmap
->cpu_map
= bpf_map_area_alloc(cmap
->map
.max_entries
*
133 sizeof(struct bpf_cpu_map_entry
*),
134 cmap
->map
.numa_node
);
140 free_percpu(cmap
->flush_needed
);
146 void __cpu_map_queue_destructor(void *ptr
)
148 /* The tear-down procedure should have made sure that queue is
149 * empty. See __cpu_map_entry_replace() and work-queue
150 * invoked cpu_map_kthread_stop(). Catch any broken behaviour
151 * gracefully and warn once.
153 if (WARN_ON_ONCE(ptr
))
157 static void put_cpu_map_entry(struct bpf_cpu_map_entry
*rcpu
)
159 if (atomic_dec_and_test(&rcpu
->refcnt
)) {
160 /* The queue should be empty at this point */
161 ptr_ring_cleanup(rcpu
->queue
, __cpu_map_queue_destructor
);
167 static void get_cpu_map_entry(struct bpf_cpu_map_entry
*rcpu
)
169 atomic_inc(&rcpu
->refcnt
);
172 /* called from workqueue, to workaround syscall using preempt_disable */
173 static void cpu_map_kthread_stop(struct work_struct
*work
)
175 struct bpf_cpu_map_entry
*rcpu
;
177 rcpu
= container_of(work
, struct bpf_cpu_map_entry
, kthread_stop_wq
);
179 /* Wait for flush in __cpu_map_entry_free(), via full RCU barrier,
180 * as it waits until all in-flight call_rcu() callbacks complete.
184 /* kthread_stop will wake_up_process and wait for it to complete */
185 kthread_stop(rcpu
->kthread
);
188 /* For now, xdp_pkt is a cpumap internal data structure, with info
189 * carried between enqueue to dequeue. It is mapped into the top
190 * headroom of the packet, to avoid allocating separate mem.
197 struct net_device
*dev_rx
;
200 /* Convert xdp_buff to xdp_pkt */
201 static struct xdp_pkt
*convert_to_xdp_pkt(struct xdp_buff
*xdp
)
203 struct xdp_pkt
*xdp_pkt
;
207 /* Assure headroom is available for storing info */
208 headroom
= xdp
->data
- xdp
->data_hard_start
;
209 metasize
= xdp
->data
- xdp
->data_meta
;
210 metasize
= metasize
> 0 ? metasize
: 0;
211 if (unlikely((headroom
- metasize
) < sizeof(*xdp_pkt
)))
214 /* Store info in top of packet */
215 xdp_pkt
= xdp
->data_hard_start
;
217 xdp_pkt
->data
= xdp
->data
;
218 xdp_pkt
->len
= xdp
->data_end
- xdp
->data
;
219 xdp_pkt
->headroom
= headroom
- sizeof(*xdp_pkt
);
220 xdp_pkt
->metasize
= metasize
;
225 struct sk_buff
*cpu_map_build_skb(struct bpf_cpu_map_entry
*rcpu
,
226 struct xdp_pkt
*xdp_pkt
)
228 unsigned int frame_size
;
229 void *pkt_data_start
;
232 /* build_skb need to place skb_shared_info after SKB end, and
233 * also want to know the memory "truesize". Thus, need to
234 * know the memory frame size backing xdp_buff.
236 * XDP was designed to have PAGE_SIZE frames, but this
237 * assumption is not longer true with ixgbe and i40e. It
238 * would be preferred to set frame_size to 2048 or 4096
239 * depending on the driver.
241 * frame_len = frame_size - sizeof(*xdp_pkt);
243 * Instead, with info avail, skb_shared_info in placed after
244 * packet len. This, unfortunately fakes the truesize.
245 * Another disadvantage of this approach, the skb_shared_info
246 * is not at a fixed memory location, with mixed length
247 * packets, which is bad for cache-line hotness.
249 frame_size
= SKB_DATA_ALIGN(xdp_pkt
->len
) + xdp_pkt
->headroom
+
250 SKB_DATA_ALIGN(sizeof(struct skb_shared_info
));
252 pkt_data_start
= xdp_pkt
->data
- xdp_pkt
->headroom
;
253 skb
= build_skb(pkt_data_start
, frame_size
);
257 skb_reserve(skb
, xdp_pkt
->headroom
);
258 __skb_put(skb
, xdp_pkt
->len
);
259 if (xdp_pkt
->metasize
)
260 skb_metadata_set(skb
, xdp_pkt
->metasize
);
262 /* Essential SKB info: protocol and skb->dev */
263 skb
->protocol
= eth_type_trans(skb
, xdp_pkt
->dev_rx
);
265 /* Optional SKB info, currently missing:
266 * - HW checksum info (skb->ip_summed)
267 * - HW RX hash (skb_set_hash)
268 * - RX ring dev queue index (skb_record_rx_queue)
274 static int cpu_map_kthread_run(void *data
)
276 struct bpf_cpu_map_entry
*rcpu
= data
;
278 set_current_state(TASK_INTERRUPTIBLE
);
280 /* When kthread gives stop order, then rcpu have been disconnected
281 * from map, thus no new packets can enter. Remaining in-flight
282 * per CPU stored packets are flushed to this queue. Wait honoring
283 * kthread_stop signal until queue is empty.
285 while (!kthread_should_stop() || !__ptr_ring_empty(rcpu
->queue
)) {
286 unsigned int processed
= 0, drops
= 0, sched
= 0;
287 struct xdp_pkt
*xdp_pkt
;
289 /* Release CPU reschedule checks */
290 if (__ptr_ring_empty(rcpu
->queue
)) {
291 set_current_state(TASK_INTERRUPTIBLE
);
292 /* Recheck to avoid lost wake-up */
293 if (__ptr_ring_empty(rcpu
->queue
)) {
297 __set_current_state(TASK_RUNNING
);
300 sched
= cond_resched();
303 /* Process packets in rcpu->queue */
306 * The bpf_cpu_map_entry is single consumer, with this
307 * kthread CPU pinned. Lockless access to ptr_ring
308 * consume side valid as no-resize allowed of queue.
310 while ((xdp_pkt
= __ptr_ring_consume(rcpu
->queue
))) {
314 skb
= cpu_map_build_skb(rcpu
, xdp_pkt
);
316 page_frag_free(xdp_pkt
);
320 /* Inject into network stack */
321 ret
= netif_receive_skb_core(skb
);
322 if (ret
== NET_RX_DROP
)
325 /* Limit BH-disable period */
326 if (++processed
== 8)
329 /* Feedback loop via tracepoint */
330 trace_xdp_cpumap_kthread(rcpu
->map_id
, processed
, drops
, sched
);
332 local_bh_enable(); /* resched point, may call do_softirq() */
334 __set_current_state(TASK_RUNNING
);
336 put_cpu_map_entry(rcpu
);
340 struct bpf_cpu_map_entry
*__cpu_map_entry_alloc(u32 qsize
, u32 cpu
, int map_id
)
342 gfp_t gfp
= GFP_ATOMIC
|__GFP_NOWARN
;
343 struct bpf_cpu_map_entry
*rcpu
;
346 /* Have map->numa_node, but choose node of redirect target CPU */
347 numa
= cpu_to_node(cpu
);
349 rcpu
= kzalloc_node(sizeof(*rcpu
), gfp
, numa
);
353 /* Alloc percpu bulkq */
354 rcpu
->bulkq
= __alloc_percpu_gfp(sizeof(*rcpu
->bulkq
),
355 sizeof(void *), gfp
);
360 rcpu
->queue
= kzalloc_node(sizeof(*rcpu
->queue
), gfp
, numa
);
364 err
= ptr_ring_init(rcpu
->queue
, qsize
, gfp
);
369 rcpu
->map_id
= map_id
;
373 rcpu
->kthread
= kthread_create_on_node(cpu_map_kthread_run
, rcpu
, numa
,
374 "cpumap/%d/map:%d", cpu
, map_id
);
375 if (IS_ERR(rcpu
->kthread
))
378 get_cpu_map_entry(rcpu
); /* 1-refcnt for being in cmap->cpu_map[] */
379 get_cpu_map_entry(rcpu
); /* 1-refcnt for kthread */
381 /* Make sure kthread runs on a single CPU */
382 kthread_bind(rcpu
->kthread
, cpu
);
383 wake_up_process(rcpu
->kthread
);
388 ptr_ring_cleanup(rcpu
->queue
, NULL
);
392 free_percpu(rcpu
->bulkq
);
398 void __cpu_map_entry_free(struct rcu_head
*rcu
)
400 struct bpf_cpu_map_entry
*rcpu
;
403 /* This cpu_map_entry have been disconnected from map and one
404 * RCU graze-period have elapsed. Thus, XDP cannot queue any
405 * new packets and cannot change/set flush_needed that can
408 rcpu
= container_of(rcu
, struct bpf_cpu_map_entry
, rcu
);
410 /* Flush remaining packets in percpu bulkq */
411 for_each_online_cpu(cpu
) {
412 struct xdp_bulk_queue
*bq
= per_cpu_ptr(rcpu
->bulkq
, cpu
);
414 /* No concurrent bq_enqueue can run at this point */
415 bq_flush_to_queue(rcpu
, bq
);
417 free_percpu(rcpu
->bulkq
);
418 /* Cannot kthread_stop() here, last put free rcpu resources */
419 put_cpu_map_entry(rcpu
);
422 /* After xchg pointer to bpf_cpu_map_entry, use the call_rcu() to
423 * ensure any driver rcu critical sections have completed, but this
424 * does not guarantee a flush has happened yet. Because driver side
425 * rcu_read_lock/unlock only protects the running XDP program. The
426 * atomic xchg and NULL-ptr check in __cpu_map_flush() makes sure a
427 * pending flush op doesn't fail.
429 * The bpf_cpu_map_entry is still used by the kthread, and there can
430 * still be pending packets (in queue and percpu bulkq). A refcnt
431 * makes sure to last user (kthread_stop vs. call_rcu) free memory
434 * The rcu callback __cpu_map_entry_free flush remaining packets in
435 * percpu bulkq to queue. Due to caller map_delete_elem() disable
436 * preemption, cannot call kthread_stop() to make sure queue is empty.
437 * Instead a work_queue is started for stopping kthread,
438 * cpu_map_kthread_stop, which waits for an RCU graze period before
439 * stopping kthread, emptying the queue.
441 void __cpu_map_entry_replace(struct bpf_cpu_map
*cmap
,
442 u32 key_cpu
, struct bpf_cpu_map_entry
*rcpu
)
444 struct bpf_cpu_map_entry
*old_rcpu
;
446 old_rcpu
= xchg(&cmap
->cpu_map
[key_cpu
], rcpu
);
448 call_rcu(&old_rcpu
->rcu
, __cpu_map_entry_free
);
449 INIT_WORK(&old_rcpu
->kthread_stop_wq
, cpu_map_kthread_stop
);
450 schedule_work(&old_rcpu
->kthread_stop_wq
);
454 int cpu_map_delete_elem(struct bpf_map
*map
, void *key
)
456 struct bpf_cpu_map
*cmap
= container_of(map
, struct bpf_cpu_map
, map
);
457 u32 key_cpu
= *(u32
*)key
;
459 if (key_cpu
>= map
->max_entries
)
462 /* notice caller map_delete_elem() use preempt_disable() */
463 __cpu_map_entry_replace(cmap
, key_cpu
, NULL
);
467 int cpu_map_update_elem(struct bpf_map
*map
, void *key
, void *value
,
470 struct bpf_cpu_map
*cmap
= container_of(map
, struct bpf_cpu_map
, map
);
471 struct bpf_cpu_map_entry
*rcpu
;
473 /* Array index key correspond to CPU number */
474 u32 key_cpu
= *(u32
*)key
;
475 /* Value is the queue size */
476 u32 qsize
= *(u32
*)value
;
478 if (unlikely(map_flags
> BPF_EXIST
))
480 if (unlikely(key_cpu
>= cmap
->map
.max_entries
))
482 if (unlikely(map_flags
== BPF_NOEXIST
))
484 if (unlikely(qsize
> 16384)) /* sanity limit on qsize */
487 /* Make sure CPU is a valid possible cpu */
488 if (!cpu_possible(key_cpu
))
492 rcpu
= NULL
; /* Same as deleting */
494 /* Updating qsize cause re-allocation of bpf_cpu_map_entry */
495 rcpu
= __cpu_map_entry_alloc(qsize
, key_cpu
, map
->id
);
500 __cpu_map_entry_replace(cmap
, key_cpu
, rcpu
);
505 void cpu_map_free(struct bpf_map
*map
)
507 struct bpf_cpu_map
*cmap
= container_of(map
, struct bpf_cpu_map
, map
);
511 /* At this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0,
512 * so the bpf programs (can be more than one that used this map) were
513 * disconnected from events. Wait for outstanding critical sections in
514 * these programs to complete. The rcu critical section only guarantees
515 * no further "XDP/bpf-side" reads against bpf_cpu_map->cpu_map.
516 * It does __not__ ensure pending flush operations (if any) are
521 /* To ensure all pending flush operations have completed wait for flush
522 * bitmap to indicate all flush_needed bits to be zero on _all_ cpus.
523 * Because the above synchronize_rcu() ensures the map is disconnected
524 * from the program we can assume no new bits will be set.
526 for_each_online_cpu(cpu
) {
527 unsigned long *bitmap
= per_cpu_ptr(cmap
->flush_needed
, cpu
);
529 while (!bitmap_empty(bitmap
, cmap
->map
.max_entries
))
533 /* For cpu_map the remote CPUs can still be using the entries
534 * (struct bpf_cpu_map_entry).
536 for (i
= 0; i
< cmap
->map
.max_entries
; i
++) {
537 struct bpf_cpu_map_entry
*rcpu
;
539 rcpu
= READ_ONCE(cmap
->cpu_map
[i
]);
543 /* bq flush and cleanup happens after RCU graze-period */
544 __cpu_map_entry_replace(cmap
, i
, NULL
); /* call_rcu */
546 free_percpu(cmap
->flush_needed
);
547 bpf_map_area_free(cmap
->cpu_map
);
551 struct bpf_cpu_map_entry
*__cpu_map_lookup_elem(struct bpf_map
*map
, u32 key
)
553 struct bpf_cpu_map
*cmap
= container_of(map
, struct bpf_cpu_map
, map
);
554 struct bpf_cpu_map_entry
*rcpu
;
556 if (key
>= map
->max_entries
)
559 rcpu
= READ_ONCE(cmap
->cpu_map
[key
]);
563 static void *cpu_map_lookup_elem(struct bpf_map
*map
, void *key
)
565 struct bpf_cpu_map_entry
*rcpu
=
566 __cpu_map_lookup_elem(map
, *(u32
*)key
);
568 return rcpu
? &rcpu
->qsize
: NULL
;
571 static int cpu_map_get_next_key(struct bpf_map
*map
, void *key
, void *next_key
)
573 struct bpf_cpu_map
*cmap
= container_of(map
, struct bpf_cpu_map
, map
);
574 u32 index
= key
? *(u32
*)key
: U32_MAX
;
575 u32
*next
= next_key
;
577 if (index
>= cmap
->map
.max_entries
) {
582 if (index
== cmap
->map
.max_entries
- 1)
588 const struct bpf_map_ops cpu_map_ops
= {
589 .map_alloc
= cpu_map_alloc
,
590 .map_free
= cpu_map_free
,
591 .map_delete_elem
= cpu_map_delete_elem
,
592 .map_update_elem
= cpu_map_update_elem
,
593 .map_lookup_elem
= cpu_map_lookup_elem
,
594 .map_get_next_key
= cpu_map_get_next_key
,
597 static int bq_flush_to_queue(struct bpf_cpu_map_entry
*rcpu
,
598 struct xdp_bulk_queue
*bq
)
600 unsigned int processed
= 0, drops
= 0;
601 const int to_cpu
= rcpu
->cpu
;
605 if (unlikely(!bq
->count
))
609 spin_lock(&q
->producer_lock
);
611 for (i
= 0; i
< bq
->count
; i
++) {
612 void *xdp_pkt
= bq
->q
[i
];
615 err
= __ptr_ring_produce(q
, xdp_pkt
);
618 page_frag_free(xdp_pkt
); /* Free xdp_pkt */
623 spin_unlock(&q
->producer_lock
);
625 /* Feedback loop via tracepoints */
626 trace_xdp_cpumap_enqueue(rcpu
->map_id
, processed
, drops
, to_cpu
);
630 /* Runs under RCU-read-side, plus in softirq under NAPI protection.
631 * Thus, safe percpu variable access.
633 static int bq_enqueue(struct bpf_cpu_map_entry
*rcpu
, struct xdp_pkt
*xdp_pkt
)
635 struct xdp_bulk_queue
*bq
= this_cpu_ptr(rcpu
->bulkq
);
637 if (unlikely(bq
->count
== CPU_MAP_BULK_SIZE
))
638 bq_flush_to_queue(rcpu
, bq
);
640 /* Notice, xdp_buff/page MUST be queued here, long enough for
641 * driver to code invoking us to finished, due to driver
642 * (e.g. ixgbe) recycle tricks based on page-refcnt.
644 * Thus, incoming xdp_pkt is always queued here (else we race
645 * with another CPU on page-refcnt and remaining driver code).
646 * Queue time is very short, as driver will invoke flush
647 * operation, when completing napi->poll call.
649 bq
->q
[bq
->count
++] = xdp_pkt
;
653 int cpu_map_enqueue(struct bpf_cpu_map_entry
*rcpu
, struct xdp_buff
*xdp
,
654 struct net_device
*dev_rx
)
656 struct xdp_pkt
*xdp_pkt
;
658 xdp_pkt
= convert_to_xdp_pkt(xdp
);
659 if (unlikely(!xdp_pkt
))
662 /* Info needed when constructing SKB on remote CPU */
663 xdp_pkt
->dev_rx
= dev_rx
;
665 bq_enqueue(rcpu
, xdp_pkt
);
669 void __cpu_map_insert_ctx(struct bpf_map
*map
, u32 bit
)
671 struct bpf_cpu_map
*cmap
= container_of(map
, struct bpf_cpu_map
, map
);
672 unsigned long *bitmap
= this_cpu_ptr(cmap
->flush_needed
);
674 __set_bit(bit
, bitmap
);
677 void __cpu_map_flush(struct bpf_map
*map
)
679 struct bpf_cpu_map
*cmap
= container_of(map
, struct bpf_cpu_map
, map
);
680 unsigned long *bitmap
= this_cpu_ptr(cmap
->flush_needed
);
683 /* The napi->poll softirq makes sure __cpu_map_insert_ctx()
684 * and __cpu_map_flush() happen on same CPU. Thus, the percpu
685 * bitmap indicate which percpu bulkq have packets.
687 for_each_set_bit(bit
, bitmap
, map
->max_entries
) {
688 struct bpf_cpu_map_entry
*rcpu
= READ_ONCE(cmap
->cpu_map
[bit
]);
689 struct xdp_bulk_queue
*bq
;
691 /* This is possible if entry is removed by user space
692 * between xdp redirect and flush op.
697 __clear_bit(bit
, bitmap
);
699 /* Flush all frames in bulkq to real queue */
700 bq
= this_cpu_ptr(rcpu
->bulkq
);
701 bq_flush_to_queue(rcpu
, bq
);
703 /* If already running, costs spin_lock_irqsave + smb_mb */
704 wake_up_process(rcpu
->kthread
);