Skip to content

Commit 457f443

Browse files
anakryikoAlexei Starovoitov
authored and
Alexei Starovoitov
committed
bpf: Implement BPF ring buffer and verifier support for it
This commit adds a new MPSC ring buffer implementation into BPF ecosystem, which allows multiple CPUs to submit data to a single shared ring buffer. On the consumption side, only single consumer is assumed. Motivation ---------- There are two distinctive motivators for this work, which are not satisfied by existing perf buffer, which prompted creation of a new ring buffer implementation. - more efficient memory utilization by sharing ring buffer across CPUs; - preserving ordering of events that happen sequentially in time, even across multiple CPUs (e.g., fork/exec/exit events for a task). These two problems are independent, but perf buffer fails to satisfy both. Both are a result of a choice to have per-CPU perf ring buffer. Both can be also solved by having an MPSC implementation of ring buffer. The ordering problem could technically be solved for perf buffer with some in-kernel counting, but given the first one requires an MPSC buffer, the same solution would solve the second problem automatically. Semantics and APIs ------------------ Single ring buffer is presented to BPF programs as an instance of BPF map of type BPF_MAP_TYPE_RINGBUF. Two other alternatives considered, but ultimately rejected. One way would be to, similar to BPF_MAP_TYPE_PERF_EVENT_ARRAY, make BPF_MAP_TYPE_RINGBUF could represent an array of ring buffers, but not enforce "same CPU only" rule. This would be more familiar interface compatible with existing perf buffer use in BPF, but would fail if application needed more advanced logic to lookup ring buffer by arbitrary key. HASH_OF_MAPS addresses this with current approach. Additionally, given the performance of BPF ringbuf, many use cases would just opt into a simple single ring buffer shared among all CPUs, for which current approach would be an overkill. Another approach could introduce a new concept, alongside BPF map, to represent generic "container" object, which doesn't necessarily have key/value interface with lookup/update/delete operations. This approach would add a lot of extra infrastructure that has to be built for observability and verifier support. It would also add another concept that BPF developers would have to familiarize themselves with, new syntax in libbpf, etc. But then would really provide no additional benefits over the approach of using a map. BPF_MAP_TYPE_RINGBUF doesn't support lookup/update/delete operations, but so doesn't few other map types (e.g., queue and stack; array doesn't support delete, etc). The approach chosen has an advantage of re-using existing BPF map infrastructure (introspection APIs in kernel, libbpf support, etc), being familiar concept (no need to teach users a new type of object in BPF program), and utilizing existing tooling (bpftool). For common scenario of using a single ring buffer for all CPUs, it's as simple and straightforward, as would be with a dedicated "container" object. On the other hand, by being a map, it can be combined with ARRAY_OF_MAPS and HASH_OF_MAPS map-in-maps to implement a wide variety of topologies, from one ring buffer for each CPU (e.g., as a replacement for perf buffer use cases), to a complicated application hashing/sharding of ring buffers (e.g., having a small pool of ring buffers with hashed task's tgid being a look up key to preserve order, but reduce contention). Key and value sizes are enforced to be zero. max_entries is used to specify the size of ring buffer and has to be a power of 2 value. There are a bunch of similarities between perf buffer (BPF_MAP_TYPE_PERF_EVENT_ARRAY) and new BPF ring buffer semantics: - variable-length records; - if there is no more space left in ring buffer, reservation fails, no blocking; - memory-mappable data area for user-space applications for ease of consumption and high performance; - epoll notifications for new incoming data; - but still the ability to do busy polling for new data to achieve the lowest latency, if necessary. BPF ringbuf provides two sets of APIs to BPF programs: - bpf_ringbuf_output() allows to *copy* data from one place to a ring buffer, similarly to bpf_perf_event_output(); - bpf_ringbuf_reserve()/bpf_ringbuf_commit()/bpf_ringbuf_discard() APIs split the whole process into two steps. First, a fixed amount of space is reserved. If successful, a pointer to a data inside ring buffer data area is returned, which BPF programs can use similarly to a data inside array/hash maps. Once ready, this piece of memory is either committed or discarded. Discard is similar to commit, but makes consumer ignore the record. bpf_ringbuf_output() has disadvantage of incurring extra memory copy, because record has to be prepared in some other place first. But it allows to submit records of the length that's not known to verifier beforehand. It also closely matches bpf_perf_event_output(), so will simplify migration significantly. bpf_ringbuf_reserve() avoids the extra copy of memory by providing a memory pointer directly to ring buffer memory. In a lot of cases records are larger than BPF stack space allows, so many programs have use extra per-CPU array as a temporary heap for preparing sample. bpf_ringbuf_reserve() avoid this needs completely. But in exchange, it only allows a known constant size of memory to be reserved, such that verifier can verify that BPF program can't access memory outside its reserved record space. bpf_ringbuf_output(), while slightly slower due to extra memory copy, covers some use cases that are not suitable for bpf_ringbuf_reserve(). The difference between commit and discard is very small. Discard just marks a record as discarded, and such records are supposed to be ignored by consumer code. Discard is useful for some advanced use-cases, such as ensuring all-or-nothing multi-record submission, or emulating temporary malloc()/free() within single BPF program invocation. Each reserved record is tracked by verifier through existing reference-tracking logic, similar to socket ref-tracking. It is thus impossible to reserve a record, but forget to submit (or discard) it. bpf_ringbuf_query() helper allows to query various properties of ring buffer. Currently 4 are supported: - BPF_RB_AVAIL_DATA returns amount of unconsumed data in ring buffer; - BPF_RB_RING_SIZE returns the size of ring buffer; - BPF_RB_CONS_POS/BPF_RB_PROD_POS returns current logical possition of consumer/producer, respectively. Returned values are momentarily snapshots of ring buffer state and could be off by the time helper returns, so this should be used only for debugging/reporting reasons or for implementing various heuristics, that take into account highly-changeable nature of some of those characteristics. One such heuristic might involve more fine-grained control over poll/epoll notifications about new data availability in ring buffer. Together with BPF_RB_NO_WAKEUP/BPF_RB_FORCE_WAKEUP flags for output/commit/discard helpers, it allows BPF program a high degree of control and, e.g., more efficient batched notifications. Default self-balancing strategy, though, should be adequate for most applications and will work reliable and efficiently already. Design and implementation ------------------------- This reserve/commit schema allows a natural way for multiple producers, either on different CPUs or even on the same CPU/in the same BPF program, to reserve independent records and work with them without blocking other producers. This means that if BPF program was interruped by another BPF program sharing the same ring buffer, they will both get a record reserved (provided there is enough space left) and can work with it and submit it independently. This applies to NMI context as well, except that due to using a spinlock during reservation, in NMI context, bpf_ringbuf_reserve() might fail to get a lock, in which case reservation will fail even if ring buffer is not full. The ring buffer itself internally is implemented as a power-of-2 sized circular buffer, with two logical and ever-increasing counters (which might wrap around on 32-bit architectures, that's not a problem): - consumer counter shows up to which logical position consumer consumed the data; - producer counter denotes amount of data reserved by all producers. Each time a record is reserved, producer that "owns" the record will successfully advance producer counter. At that point, data is still not yet ready to be consumed, though. Each record has 8 byte header, which contains the length of reserved record, as well as two extra bits: busy bit to denote that record is still being worked on, and discard bit, which might be set at commit time if record is discarded. In the latter case, consumer is supposed to skip the record and move on to the next one. Record header also encodes record's relative offset from the beginning of ring buffer data area (in pages). This allows bpf_ringbuf_commit()/bpf_ringbuf_discard() to accept only the pointer to the record itself, without requiring also the pointer to ring buffer itself. Ring buffer memory location will be restored from record metadata header. This significantly simplifies verifier, as well as improving API usability. Producer counter increments are serialized under spinlock, so there is a strict ordering between reservations. Commits, on the other hand, are completely lockless and independent. All records become available to consumer in the order of reservations, but only after all previous records where already committed. It is thus possible for slow producers to temporarily hold off submitted records, that were reserved later. Reservation/commit/consumer protocol is verified by litmus tests in Documentation/litmus-test/bpf-rb. One interesting implementation bit, that significantly simplifies (and thus speeds up as well) implementation of both producers and consumers is how data area is mapped twice contiguously back-to-back in the virtual memory. This allows to not take any special measures for samples that have to wrap around at the end of the circular buffer data area, because the next page after the last data page would be first data page again, and thus the sample will still appear completely contiguous in virtual memory. See comment and a simple ASCII diagram showing this visually in bpf_ringbuf_area_alloc(). Another feature that distinguishes BPF ringbuf from perf ring buffer is a self-pacing notifications of new data being availability. bpf_ringbuf_commit() implementation will send a notification of new record being available after commit only if consumer has already caught up right up to the record being committed. If not, consumer still has to catch up and thus will see new data anyways without needing an extra poll notification. Benchmarks (see tools/testing/selftests/bpf/benchs/bench_ringbuf.c) show that this allows to achieve a very high throughput without having to resort to tricks like "notify only every Nth sample", which are necessary with perf buffer. For extreme cases, when BPF program wants more manual control of notifications, commit/discard/output helpers accept BPF_RB_NO_WAKEUP and BPF_RB_FORCE_WAKEUP flags, which give full control over notifications of data availability, but require extra caution and diligence in using this API. Comparison to alternatives -------------------------- Before considering implementing BPF ring buffer from scratch existing alternatives in kernel were evaluated, but didn't seem to meet the needs. They largely fell into few categores: - per-CPU buffers (perf, ftrace, etc), which don't satisfy two motivations outlined above (ordering and memory consumption); - linked list-based implementations; while some were multi-producer designs, consuming these from user-space would be very complicated and most probably not performant; memory-mapping contiguous piece of memory is simpler and more performant for user-space consumers; - io_uring is SPSC, but also requires fixed-sized elements. Naively turning SPSC queue into MPSC w/ lock would have subpar performance compared to locked reserve + lockless commit, as with BPF ring buffer. Fixed sized elements would be too limiting for BPF programs, given existing BPF programs heavily rely on variable-sized perf buffer already; - specialized implementations (like a new printk ring buffer, [0]) with lots of printk-specific limitations and implications, that didn't seem to fit well for intended use with BPF programs. [0] https://lwn.net/Articles/779550/ Signed-off-by: Andrii Nakryiko <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Link: https://lore.kernel.org/bpf/[email protected] Signed-off-by: Alexei Starovoitov <[email protected]>
1 parent 43dd115 commit 457f443

File tree

19 files changed

+882
-70
lines changed

19 files changed

+882
-70
lines changed

Diff for: include/linux/bpf.h

+13
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ struct bpf_map_ops {
9090
int (*map_direct_value_meta)(const struct bpf_map *map,
9191
u64 imm, u32 *off);
9292
int (*map_mmap)(struct bpf_map *map, struct vm_area_struct *vma);
93+
__poll_t (*map_poll)(struct bpf_map *map, struct file *filp,
94+
struct poll_table_struct *pts);
9395
};
9496

9597
struct bpf_map_memory {
@@ -244,6 +246,9 @@ enum bpf_arg_type {
244246
ARG_PTR_TO_LONG, /* pointer to long */
245247
ARG_PTR_TO_SOCKET, /* pointer to bpf_sock (fullsock) */
246248
ARG_PTR_TO_BTF_ID, /* pointer to in-kernel struct */
249+
ARG_PTR_TO_ALLOC_MEM, /* pointer to dynamically allocated memory */
250+
ARG_PTR_TO_ALLOC_MEM_OR_NULL, /* pointer to dynamically allocated memory or NULL */
251+
ARG_CONST_ALLOC_SIZE_OR_ZERO, /* number of allocated bytes requested */
247252
};
248253

249254
/* type of values returned from helper functions */
@@ -255,6 +260,7 @@ enum bpf_return_type {
255260
RET_PTR_TO_SOCKET_OR_NULL, /* returns a pointer to a socket or NULL */
256261
RET_PTR_TO_TCP_SOCK_OR_NULL, /* returns a pointer to a tcp_sock or NULL */
257262
RET_PTR_TO_SOCK_COMMON_OR_NULL, /* returns a pointer to a sock_common or NULL */
263+
RET_PTR_TO_ALLOC_MEM_OR_NULL, /* returns a pointer to dynamically allocated memory or NULL */
258264
};
259265

260266
/* eBPF function prototype used by verifier to allow BPF_CALLs from eBPF programs
@@ -322,6 +328,8 @@ enum bpf_reg_type {
322328
PTR_TO_XDP_SOCK, /* reg points to struct xdp_sock */
323329
PTR_TO_BTF_ID, /* reg points to kernel struct */
324330
PTR_TO_BTF_ID_OR_NULL, /* reg points to kernel struct or NULL */
331+
PTR_TO_MEM, /* reg points to valid memory region */
332+
PTR_TO_MEM_OR_NULL, /* reg points to valid memory region or NULL */
325333
};
326334

327335
/* The information passed from prog-specific *_is_valid_access
@@ -1611,6 +1619,11 @@ extern const struct bpf_func_proto bpf_tcp_sock_proto;
16111619
extern const struct bpf_func_proto bpf_jiffies64_proto;
16121620
extern const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto;
16131621
extern const struct bpf_func_proto bpf_event_output_data_proto;
1622+
extern const struct bpf_func_proto bpf_ringbuf_output_proto;
1623+
extern const struct bpf_func_proto bpf_ringbuf_reserve_proto;
1624+
extern const struct bpf_func_proto bpf_ringbuf_submit_proto;
1625+
extern const struct bpf_func_proto bpf_ringbuf_discard_proto;
1626+
extern const struct bpf_func_proto bpf_ringbuf_query_proto;
16141627

16151628
const struct bpf_func_proto *bpf_tracing_func_proto(
16161629
enum bpf_func_id func_id, const struct bpf_prog *prog);

Diff for: include/linux/bpf_types.h

+1
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_STACK, stack_map_ops)
118118
#if defined(CONFIG_BPF_JIT)
119119
BPF_MAP_TYPE(BPF_MAP_TYPE_STRUCT_OPS, bpf_struct_ops_map_ops)
120120
#endif
121+
BPF_MAP_TYPE(BPF_MAP_TYPE_RINGBUF, ringbuf_map_ops)
121122

122123
BPF_LINK_TYPE(BPF_LINK_TYPE_RAW_TRACEPOINT, raw_tracepoint)
123124
BPF_LINK_TYPE(BPF_LINK_TYPE_TRACING, tracing)

Diff for: include/linux/bpf_verifier.h

+4
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ struct bpf_reg_state {
5454

5555
u32 btf_id; /* for PTR_TO_BTF_ID */
5656

57+
u32 mem_size; /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */
58+
5759
/* Max size from any of the above. */
5860
unsigned long raw;
5961
};
@@ -63,6 +65,8 @@ struct bpf_reg_state {
6365
* offset, so they can share range knowledge.
6466
* For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we
6567
* came from, when one is tested for != NULL.
68+
* For PTR_TO_MEM_OR_NULL this is used to identify memory allocation
69+
* for the purpose of tracking that it's freed.
6670
* For PTR_TO_SOCKET this is used to share which pointers retain the
6771
* same reference to the socket, to determine proper reference freeing.
6872
*/

Diff for: include/uapi/linux/bpf.h

+83-1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ enum bpf_map_type {
147147
BPF_MAP_TYPE_SK_STORAGE,
148148
BPF_MAP_TYPE_DEVMAP_HASH,
149149
BPF_MAP_TYPE_STRUCT_OPS,
150+
BPF_MAP_TYPE_RINGBUF,
150151
};
151152

152153
/* Note that tracing related programs such as
@@ -3157,6 +3158,59 @@ union bpf_attr {
31573158
* **bpf_sk_cgroup_id**\ ().
31583159
* Return
31593160
* The id is returned or 0 in case the id could not be retrieved.
3161+
*
3162+
* void *bpf_ringbuf_output(void *ringbuf, void *data, u64 size, u64 flags)
3163+
* Description
3164+
* Copy *size* bytes from *data* into a ring buffer *ringbuf*.
3165+
* If BPF_RB_NO_WAKEUP is specified in *flags*, no notification of
3166+
* new data availability is sent.
3167+
* IF BPF_RB_FORCE_WAKEUP is specified in *flags*, notification of
3168+
* new data availability is sent unconditionally.
3169+
* Return
3170+
* 0, on success;
3171+
* < 0, on error.
3172+
*
3173+
* void *bpf_ringbuf_reserve(void *ringbuf, u64 size, u64 flags)
3174+
* Description
3175+
* Reserve *size* bytes of payload in a ring buffer *ringbuf*.
3176+
* Return
3177+
* Valid pointer with *size* bytes of memory available; NULL,
3178+
* otherwise.
3179+
*
3180+
* void bpf_ringbuf_submit(void *data, u64 flags)
3181+
* Description
3182+
* Submit reserved ring buffer sample, pointed to by *data*.
3183+
* If BPF_RB_NO_WAKEUP is specified in *flags*, no notification of
3184+
* new data availability is sent.
3185+
* IF BPF_RB_FORCE_WAKEUP is specified in *flags*, notification of
3186+
* new data availability is sent unconditionally.
3187+
* Return
3188+
* Nothing. Always succeeds.
3189+
*
3190+
* void bpf_ringbuf_discard(void *data, u64 flags)
3191+
* Description
3192+
* Discard reserved ring buffer sample, pointed to by *data*.
3193+
* If BPF_RB_NO_WAKEUP is specified in *flags*, no notification of
3194+
* new data availability is sent.
3195+
* IF BPF_RB_FORCE_WAKEUP is specified in *flags*, notification of
3196+
* new data availability is sent unconditionally.
3197+
* Return
3198+
* Nothing. Always succeeds.
3199+
*
3200+
* u64 bpf_ringbuf_query(void *ringbuf, u64 flags)
3201+
* Description
3202+
* Query various characteristics of provided ring buffer. What
3203+
* exactly is queries is determined by *flags*:
3204+
* - BPF_RB_AVAIL_DATA - amount of data not yet consumed;
3205+
* - BPF_RB_RING_SIZE - the size of ring buffer;
3206+
* - BPF_RB_CONS_POS - consumer position (can wrap around);
3207+
* - BPF_RB_PROD_POS - producer(s) position (can wrap around);
3208+
* Data returned is just a momentary snapshots of actual values
3209+
* and could be inaccurate, so this facility should be used to
3210+
* power heuristics and for reporting, not to make 100% correct
3211+
* calculation.
3212+
* Return
3213+
* Requested value, or 0, if flags are not recognized.
31603214
*/
31613215
#define __BPF_FUNC_MAPPER(FN) \
31623216
FN(unspec), \
@@ -3288,7 +3342,12 @@ union bpf_attr {
32883342
FN(seq_printf), \
32893343
FN(seq_write), \
32903344
FN(sk_cgroup_id), \
3291-
FN(sk_ancestor_cgroup_id),
3345+
FN(sk_ancestor_cgroup_id), \
3346+
FN(ringbuf_output), \
3347+
FN(ringbuf_reserve), \
3348+
FN(ringbuf_submit), \
3349+
FN(ringbuf_discard), \
3350+
FN(ringbuf_query),
32923351

32933352
/* integer value in 'imm' field of BPF_CALL instruction selects which helper
32943353
* function eBPF program intends to call
@@ -3398,6 +3457,29 @@ enum {
33983457
BPF_F_GET_BRANCH_RECORDS_SIZE = (1ULL << 0),
33993458
};
34003459

3460+
/* BPF_FUNC_bpf_ringbuf_commit, BPF_FUNC_bpf_ringbuf_discard, and
3461+
* BPF_FUNC_bpf_ringbuf_output flags.
3462+
*/
3463+
enum {
3464+
BPF_RB_NO_WAKEUP = (1ULL << 0),
3465+
BPF_RB_FORCE_WAKEUP = (1ULL << 1),
3466+
};
3467+
3468+
/* BPF_FUNC_bpf_ringbuf_query flags */
3469+
enum {
3470+
BPF_RB_AVAIL_DATA = 0,
3471+
BPF_RB_RING_SIZE = 1,
3472+
BPF_RB_CONS_POS = 2,
3473+
BPF_RB_PROD_POS = 3,
3474+
};
3475+
3476+
/* BPF ring buffer constants */
3477+
enum {
3478+
BPF_RINGBUF_BUSY_BIT = (1U << 31),
3479+
BPF_RINGBUF_DISCARD_BIT = (1U << 30),
3480+
BPF_RINGBUF_HDR_SZ = 8,
3481+
};
3482+
34013483
/* Mode for BPF_FUNC_skb_adjust_room helper. */
34023484
enum bpf_adj_room_mode {
34033485
BPF_ADJ_ROOM_NET,

Diff for: kernel/bpf/Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ CFLAGS_core.o += $(call cc-disable-warning, override-init)
44

55
obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o bpf_iter.o map_iter.o task_iter.o
66
obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o
7-
obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o
7+
obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o
88
obj-$(CONFIG_BPF_SYSCALL) += disasm.o
99
obj-$(CONFIG_BPF_JIT) += trampoline.o
1010
obj-$(CONFIG_BPF_SYSCALL) += btf.o

Diff for: kernel/bpf/helpers.c

+10
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,16 @@ bpf_base_func_proto(enum bpf_func_id func_id)
635635
return &bpf_ktime_get_ns_proto;
636636
case BPF_FUNC_ktime_get_boot_ns:
637637
return &bpf_ktime_get_boot_ns_proto;
638+
case BPF_FUNC_ringbuf_output:
639+
return &bpf_ringbuf_output_proto;
640+
case BPF_FUNC_ringbuf_reserve:
641+
return &bpf_ringbuf_reserve_proto;
642+
case BPF_FUNC_ringbuf_submit:
643+
return &bpf_ringbuf_submit_proto;
644+
case BPF_FUNC_ringbuf_discard:
645+
return &bpf_ringbuf_discard_proto;
646+
case BPF_FUNC_ringbuf_query:
647+
return &bpf_ringbuf_query_proto;
638648
default:
639649
break;
640650
}

0 commit comments

Comments
 (0)