* [PATCH bpf-next v1 01/10] bpf: Order record data after the producer position in overwrite mode
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 02/10] bpf: Keep an overwritable ring buffer readable while it is overwritten Kumar Kartikeya Dwivedi
` (8 subsequent siblings)
9 siblings, 0 replies; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
In overwrite mode the producer can reuse the memory of a record while the
consumer is reading it. A consumer can only find out by reading
producer_pos again after it has read the record: if the producer is less
than a ring buffer size ahead of the record, the record was not
overwritten.
This only works if the consumer cannot see the data of a new record before
it sees the producer_pos update for that record. __bpf_ringbuf_reserve()
updates producer_pos with smp_store_release(), and the BPF program writes
the record data after it returns. smp_store_release() doesn't order the
stores that come after it, so on weakly ordered architectures like arm64
the consumer can read data of the new record, then read the old
producer_pos, and take partially overwritten data for a valid record.
Add smp_wmb() after the producer_pos update in overwrite mode. It is only
a compiler barrier on x86.
LKMM litmus test, where P0 is the producer and P1 the consumer:
C rb-overwrite-data-vs-prodpos
{}
P0(int *prod_pos, int *data)
{
smp_store_release(prod_pos, 1);
/* smp_wmb(); */
WRITE_ONCE(*data, 1);
}
P1(int *prod_pos, int *data)
{
int r0;
int r1;
r0 = READ_ONCE(*data);
smp_rmb();
r1 = smp_load_acquire(prod_pos);
}
exists (1:r0=1 /\ 1:r1=0)
The outcome is allowed without the smp_wmb() and forbidden with it.
Fixes: feeaf1346f80 ("bpf: Add overwrite mode for BPF ring buffer")
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
kernel/bpf/ringbuf.c | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/kernel/bpf/ringbuf.c b/kernel/bpf/ringbuf.c
index 447863ece26a..5806a5eb5d16 100644
--- a/kernel/bpf/ringbuf.c
+++ b/kernel/bpf/ringbuf.c
@@ -532,6 +532,16 @@ static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
/* pairs with consumer's smp_load_acquire() */
smp_store_release(&rb->producer_pos, new_prod_pos);
+ if (unlikely(rb->overwrite_mode)) {
+ /*
+ * The consumer reads a record and then checks producer_pos to
+ * see if the record was overwritten in the meantime. Make sure
+ * it can't see the record data that our caller is going to write
+ * before it sees the producer_pos update above.
+ */
+ smp_wmb();
+ }
+
raw_res_spin_unlock_irqrestore(&rb->spinlock, flags);
return (void *)hdr + BPF_RINGBUF_HDR_SZ;
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* [PATCH bpf-next v1 02/10] bpf: Keep an overwritable ring buffer readable while it is overwritten
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 01/10] bpf: Order record data after the producer position in overwrite mode Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 03/10] bpf, docs: Document the overwrite mode of BPF ring buffer Kumar Kartikeya Dwivedi
` (7 subsequent siblings)
9 siblings, 0 replies; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Andrii Nakryiko, Alexei Starovoitov,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
ringbuf_map_poll_kern() reports the ring as readable when
ringbuf_avail_data_sz() is not zero, which in overwrite mode is
over_pos = smp_load_acquire(&rb->overwrite_pos);
prod_pos = smp_load_acquire(&rb->producer_pos);
return min(prod_pos - cons_pos, prod_pos - over_pos);
__bpf_ringbuf_reserve() stores overwrite_pos before it publishes
producer_pos. When the new record overwrites every record in the ring, it
moves overwrite_pos up to the old producer_pos. A poll between the two
stores computes prod_pos - over_pos == 0 and finds the ring empty, although
the consumer is behind the producer.
A consumer that polls at that moment goes back to sleep on unread
records, and the commit of the new record does not wake it up, because
bpf_ringbuf_commit() only wakes up the consumer for a record that starts
at the offset of the consumer position in the ring. With a ring of 4096
bytes and records that take 2048:
consumer producers
consumed up to 0, epoll_wait()
reserve and commit R1 at 0;
consumer_pos is 0: wake up
reserve R2:
overwrite_pos = 2048
woken up, poll looks again:
over_pos 2048, prod_pos 2048,
nothing to read, sleep
producer_pos = 4096
commit R2, at 2048;
consumer_pos is 0: no wakeup
There is no wakeup for R2. The consumer sleeps until a record starts at
that offset again, which is the next one here.
There is something to read whenever the consumer position is behind the
producer position, in either mode. Compare those two and leave
overwrite_pos out of it. bpf_ringbuf_query(BPF_RB_AVAIL_DATA) is
unchanged.
The missed wakeup follows from the code and was not reproduced, but the
empty poll was. A user space loop that polls an overwritable ring, while a
program overwrites it with records of more than half its size, found the
ring empty in 25 to 59 of 1.1 million polls in three runs of half a
second on a 4-CPU VM, and in none with this change.
Fixes: feeaf1346f80 ("bpf: Add overwrite mode for BPF ring buffer")
Acked-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
kernel/bpf/ringbuf.c | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/kernel/bpf/ringbuf.c b/kernel/bpf/ringbuf.c
index 5806a5eb5d16..1334cfd90f2a 100644
--- a/kernel/bpf/ringbuf.c
+++ b/kernel/bpf/ringbuf.c
@@ -336,12 +336,18 @@ static u32 ringbuf_total_data_sz(const struct bpf_ringbuf *rb)
static __poll_t ringbuf_map_poll_kern(struct bpf_map *map, struct file *filp,
struct poll_table_struct *pts)
{
- struct bpf_ringbuf_map *rb_map;
+ struct bpf_ringbuf *rb;
- rb_map = container_of(map, struct bpf_ringbuf_map, map);
- poll_wait(filp, &rb_map->rb->waitq, pts);
+ rb = container_of(map, struct bpf_ringbuf_map, map)->rb;
+ poll_wait(filp, &rb->waitq, pts);
- if (ringbuf_avail_data_sz(rb_map->rb))
+ /*
+ * In overwrite mode ringbuf_avail_data_sz() can return 0 for a ring
+ * with unread records: a reservation can move overwrite_pos up to
+ * producer_pos before it updates producer_pos. Check if the consumer
+ * is behind the producer instead.
+ */
+ if (smp_load_acquire(&rb->producer_pos) != smp_load_acquire(&rb->consumer_pos))
return EPOLLIN | EPOLLRDNORM;
return 0;
}
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* [PATCH bpf-next v1 03/10] bpf, docs: Document the overwrite mode of BPF ring buffer
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 01/10] bpf: Order record data after the producer position in overwrite mode Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 02/10] bpf: Keep an overwritable ring buffer readable while it is overwritten Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:46 ` bot+bpf-ci
2026-11-23 21:13 ` [PATCH bpf-next v1 04/10] libbpf: Account for the overwrite position in ring__avail_data_size() Kumar Kartikeya Dwivedi
` (6 subsequent siblings)
9 siblings, 1 reply; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
Describe what BPF_F_RB_OVERWRITE does, where the overwrite position is in
the producer page, and how a consumer has to read records that the producer
can overwrite at any time. Consumers that don't use libbpf need this. Also
list BPF_RB_OVERWRITE_POS for bpf_ringbuf_query().
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
Documentation/bpf/ringbuf.rst | 44 +++++++++++++++++++++++++++++++++--
1 file changed, 42 insertions(+), 2 deletions(-)
diff --git a/Documentation/bpf/ringbuf.rst b/Documentation/bpf/ringbuf.rst
index a99cd05d79d4..9715d4335d5b 100644
--- a/Documentation/bpf/ringbuf.rst
+++ b/Documentation/bpf/ringbuf.rst
@@ -120,12 +120,14 @@ 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:
+buffer. Currently 5 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 position
- of consumer/producer, respectively.
+ of consumer/producer, respectively;
+- ``BPF_RB_OVERWRITE_POS`` returns the logical position of the oldest record
+ that is not overwritten yet (see `Overwrite mode`_).
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
@@ -204,3 +206,41 @@ 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.
+
+Overwrite mode
+--------------
+
+In a ring buffer created with the ``BPF_F_RB_OVERWRITE`` map flag, reservations
+don't fail when the ring buffer is full. The producer overwrites the oldest
+records instead, so the ring buffer always holds the most recent data.
+
+The read-only page mapped before the data area holds three ``unsigned long``
+counters in this order: producer position, pending position (used only by
+producers), and overwrite position. The overwrite position is the position of
+the oldest record that is not overwritten yet. The producer updates it before
+the producer position, and it is always less than a ring buffer size behind the
+producer position.
+
+The producer doesn't wait for the consumer, so a record can be overwritten
+while it is being read. The consumer has to read first and check afterwards:
+
+1. Read the overwrite position and then the producer position. Start at the
+ consumer position, or at the overwrite position if the producer position is
+ a ring buffer size or more ahead of the consumer position. If the start is
+ the producer position, there is nothing to read.
+2. Read the record header and do the check in step 4. Use the length and flags
+ of the header only if it passes.
+3. Read or copy the record data, without using it yet.
+4. Issue a read barrier and read the producer position again. If it is less
+ than a ring buffer size ahead of the record's position, everything read
+ from the record is valid. Otherwise the record may have been overwritten:
+ drop what was read and start again from step 1.
+
+Records are overwritten in order, so when several records are read in a row it
+is enough to do the check in step 4 for the first one, after reading the last
+one.
+
+Positions wrap around, so compare them by subtracting one from the other. The
+check in step 4 can't notice a producer position that wrapped all the way
+around since the consumer stored the position it starts from. With a 32-bit
+``unsigned long`` that takes only 4 GiB of records.
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* Re: [PATCH bpf-next v1 03/10] bpf, docs: Document the overwrite mode of BPF ring buffer
2026-11-23 21:13 ` [PATCH bpf-next v1 03/10] bpf, docs: Document the overwrite mode of BPF ring buffer Kumar Kartikeya Dwivedi
@ 2026-11-23 21:46 ` bot+bpf-ci
0 siblings, 0 replies; 15+ messages in thread
From: bot+bpf-ci @ 2026-11-23 21:46 UTC (permalink / raw)
To: memxor, bpf
Cc: xukuohai, tamird, ast, andrii, daniel, eddyz87, emil,
ihor.solodrai, kkd, kernel-team, ast, andrii, daniel, martin.lau,
eddyz87, yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 2770 bytes --]
> bpf, docs: Document the overwrite mode of BPF ring buffer
TL;DR:
- Docs claim overwrite-mode reservations never fail, but they may still fail
when the oldest uncommitted record would be overwritten
- Consumer procedure may lack read ordering on weak CPUs and busy/discard bit
handling
> diff --git a/Documentation/bpf/ringbuf.rst b/Documentation/bpf/ringbuf.rst
> --- a/Documentation/bpf/ringbuf.rst
> +++ b/Documentation/bpf/ringbuf.rst
[ ... ]
> +Overwrite mode
> +--------------
> +
> +In a ring buffer created with the ``BPF_F_RB_OVERWRITE`` map flag, reservations
> +don't fail when the ring buffer is full. The producer overwrites the oldest
> +records instead, so the ring buffer always holds the most recent data.
Is this strictly true? In bpf_ringbuf_has_space() the check
new_prod_pos - pend_pos > rb->mask
returns false before the overwrite_mode shortcut is reached, so a
reservation still fails (returns NULL) when the oldest not-yet-committed
record and the new record together span the whole ring.
Overwrite mode cannot overwrite a record that a producer is still working
on.
Could the text say that reservations don't fail merely because the consumer
is behind, but can still fail when the oldest uncommitted record would have
to be overwritten?
[ ... ]
> +1. Read the overwrite position and then the producer position. Start at the
> + consumer position, or at the overwrite position if the producer position is
> + a ring buffer size or more ahead of the consumer position. If the start is
> + the producer position, there is nothing to read.
> +2. Read the record header and do the check in step 4. Use the length and flags
> + of the header only if it passes.
Should step 1 say that these two loads must be ordered (acquire or a read
barrier)? On weakly ordered CPUs such as arm64 the two loads can be
reordered, which breaks the ordering the kernel relies on; the kernel's own
ringbuf_avail_data_sz() uses smp_load_acquire() for both. Only step 4
mentions a barrier.
Also, step 2 doesn't mention BPF_RINGBUF_BUSY_BIT or BPF_RINGBUF_DISCARD_BIT.
The record at the producer position is reserved but may still be busy, and
the length has to be masked before use, so a consumer following only this
section could treat a busy header as a valid length.
Finally, the batching paragraph needs the first record's length to find the
next record before the step 4 check has validated it. Doesn't that conflict
with step 2's "Use the length and flags of the header only if it passes"?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45270351590
^ permalink raw reply [flat|nested] 15+ messages in thread
* [PATCH bpf-next v1 04/10] libbpf: Account for the overwrite position in ring__avail_data_size()
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
` (2 preceding siblings ...)
2026-11-23 21:13 ` [PATCH bpf-next v1 03/10] bpf, docs: Document the overwrite mode of BPF ring buffer Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:22 ` sashiko-bot
2026-11-23 21:13 ` [PATCH bpf-next v1 05/10] libbpf: Add a record API for consuming BPF ring buffers Kumar Kartikeya Dwivedi
` (5 subsequent siblings)
9 siblings, 1 reply; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
In overwrite mode the kernel overwrites the oldest records when the ring
buffer is full, and keeps the position of the oldest record that is still
there in overwrite_pos. The records between consumer_pos and overwrite_pos
are gone, but ring__avail_data_size() still counts them.
Read overwrite_pos, which is the third unsigned long in the producer page,
and return min(producer_pos - consumer_pos, producer_pos - overwrite_pos),
like ringbuf_avail_data_sz() does in the kernel.
A 32-bit libbpf can't tell whether the kernel is 64-bit, in which case
overwrite_pos is at a different offset, so it keeps returning producer_pos -
consumer_pos.
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
tools/lib/bpf/ringbuf.c | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)
diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
index 78fcb3df243f..271c6b9b130d 100644
--- a/tools/lib/bpf/ringbuf.c
+++ b/tools/lib/bpf/ringbuf.c
@@ -28,6 +28,7 @@ struct ring {
void *data;
unsigned long *consumer_pos;
unsigned long *producer_pos;
+ unsigned long *overwrite_pos;
unsigned long mask;
int map_fd;
bool overwrite;
@@ -150,6 +151,13 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
}
r->producer_pos = tmp;
r->data = tmp + rb->page_size;
+ /*
+ * overwrite_pos comes after producer_pos and pending_pos. Its offset
+ * depends on the size of the kernel's unsigned long, which 32-bit libbpf
+ * can't know.
+ */
+ if (r->overwrite && sizeof(unsigned long) == sizeof(__u64))
+ r->overwrite_pos = r->producer_pos + 2;
e = &rb->events[rb->ring_cnt];
memset(e, 0, sizeof(*e));
@@ -426,11 +434,16 @@ unsigned long ring__producer_pos(const struct ring *r)
size_t ring__avail_data_size(const struct ring *r)
{
- unsigned long cons_pos, prod_pos;
+ unsigned long cons_pos, prod_pos, over_pos;
cons_pos = ring__consumer_pos(r);
prod_pos = ring__producer_pos(r);
- return prod_pos - cons_pos;
+ if (!r->overwrite_pos)
+ return prod_pos - cons_pos;
+
+ /* records before overwrite_pos are gone */
+ over_pos = smp_load_acquire(r->overwrite_pos);
+ return min(prod_pos - cons_pos, prod_pos - over_pos);
}
size_t ring__size(const struct ring *r)
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* Re: [PATCH bpf-next v1 04/10] libbpf: Account for the overwrite position in ring__avail_data_size()
2026-11-23 21:13 ` [PATCH bpf-next v1 04/10] libbpf: Account for the overwrite position in ring__avail_data_size() Kumar Kartikeya Dwivedi
@ 2026-11-23 21:22 ` sashiko-bot
0 siblings, 0 replies; 15+ messages in thread
From: sashiko-bot @ 2026-11-23 21:22 UTC (permalink / raw)
To: Kumar Kartikeya Dwivedi, bpf
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] libbpf: load ordering race and underflow in
ring__avail_data_size()
--
commit 2b238949efda4fe4f9b112e9f915c9221770464d
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>
libbpf: Account for the overwrite position in ring__avail_data_size()
This commit updates ring__avail_data_size() in 64-bit libbpf to read
overwrite_pos from the producer page on overwrite-mode ring buffers and
cap the available data size at producer_pos - overwrite_pos.
> diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
> index 78fcb3df243f9..271c6b9b130de 100644
> --- a/tools/lib/bpf/ringbuf.c
> +++ b/tools/lib/bpf/ringbuf.c
[ ... ]
> @@ -426,11 +434,16 @@ unsigned long ring__producer_pos(const struct ring *r)
>
> size_t ring__avail_data_size(const struct ring *r)
> {
> - unsigned long cons_pos, prod_pos;
> + unsigned long cons_pos, prod_pos, over_pos;
>
> cons_pos = ring__consumer_pos(r);
> prod_pos = ring__producer_pos(r);
> - return prod_pos - cons_pos;
> + if (!r->overwrite_pos)
> + return prod_pos - cons_pos;
> +
> + /* records before overwrite_pos are gone */
> + over_pos = smp_load_acquire(r->overwrite_pos);
> + return min(prod_pos - cons_pos, prod_pos - over_pos);
> }
[Severity: Medium]
Can prod_pos - over_pos underflow when producer_pos is loaded before
overwrite_pos?
CPU0 (userspace consumer) CPU1 (BPF producer)
ring__avail_data_size()
prod_pos = ring__producer_pos(r)
__bpf_ringbuf_reserve()
/* advances rb->overwrite_pos
* and rb->producer_pos
*/
over_pos = smp_load_acquire(r->overwrite_pos)
prod_pos - over_pos <-- underflows if over_pos > prod_pos
When multiple reservations advance overwrite_pos past the stale prod_pos
snapshot, prod_pos - over_pos wraps around unsigned long, causing min()
to fall back to prod_pos - cons_pos and include already overwritten
records. If a single reservation advances overwrite_pos up to the
sampled prod_pos, ring__avail_data_size() returns 0 for a full buffer.
In the kernel, ringbuf_avail_data_sz() loads overwrite_pos before
producer_pos so that prod_pos is at least as recent as over_pos:
kernel/bpf/ringbuf.c:ringbuf_avail_data_sz() {
...
if (unlikely(rb->overwrite_mode)) {
over_pos = smp_load_acquire(&rb->overwrite_pos);
prod_pos = smp_load_acquire(&rb->producer_pos);
return min(prod_pos - cons_pos, prod_pos - over_pos);
}
...
}
Loading r->overwrite_pos with smp_load_acquire() before calling
ring__producer_pos(r) avoids the underflow.
--
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795467315.git.memxor@gmail.com?part=4
^ permalink raw reply [flat|nested] 15+ messages in thread
* [PATCH bpf-next v1 05/10] libbpf: Add a record API for consuming BPF ring buffers
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
` (3 preceding siblings ...)
2026-11-23 21:13 ` [PATCH bpf-next v1 04/10] libbpf: Account for the overwrite position in ring__avail_data_size() Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 06/10] libbpf: Add ring_buffer__wait() Kumar Kartikeya Dwivedi
` (4 subsequent siblings)
9 siblings, 0 replies; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
Ring buffer records can only be consumed through a sample callback, e.g.
from ring_buffer__poll() or ring__consume(). Add an API that returns the
records to the caller one by one instead:
const struct ring_rec *ring__next(struct ring *r);
int ring__release(struct ring *r);
void ring__rewind(struct ring *r);
ring__next() returns the next record without consuming it, or NULL if
there is nothing to consume. errno is set on any error. ring__release()
consumes all records returned since the last release or rewind.
ring__rewind() goes back to the first record that was not released, so
that ring__next() returns the same records again.
const struct ring_rec *rec;
do {
while ((rec = ring__next(r)))
handle(rec->data, rec->len);
} while (ring__release(r) > 0);
/* wait for data, e.g. epoll on ring__map_fd(r) */
Records stay valid until they are released, so the caller can process a
number of them and update the consumer position once.
ring__next() invalidates and reuses the previous struct ring_rec, so if
the caller needs to access multiple records they need to copy them
separately. The struct is embedded in struct ring and followed by two
unsigned longs that are always zero. If a later libbpf adds fields to it,
an application built against that libbpf.h reads them as zero when it
runs with this libbpf.
ring__release() returns 1 if there are more records to consume. The kernel
wakes up the consumer only if a record is committed right at the consumer
position, so records committed before the release don't cause a wakeup
and the caller has to call ring__next() again instead of waiting. To not
miss such a record, ring__release() needs a full barrier between updating
the consumer position and checking for the record.
The new functions can only be used on a ring that has no callback, i.e.
NULL was passed as sample_cb to ring_buffer__new() or ring_buffer__add().
On a ring that has a callback, ring__next() and ring__release() fail with
EINVAL and ring__rewind() does nothing, just like the callback-based
functions already fail on a ring without one.
The position of the next record is cached in struct ring and not read from
the consumer page, so as before only one consumer can use a ring buffer.
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
tools/lib/bpf/libbpf.h | 63 ++++++++++++++++++++++++++-
tools/lib/bpf/libbpf.map | 3 ++
tools/lib/bpf/ringbuf.c | 93 +++++++++++++++++++++++++++++++++++++++-
3 files changed, 157 insertions(+), 2 deletions(-)
diff --git a/tools/lib/bpf/libbpf.h b/tools/lib/bpf/libbpf.h
index 49f1120f4021..efd796603fa3 100644
--- a/tools/lib/bpf/libbpf.h
+++ b/tools/lib/bpf/libbpf.h
@@ -1541,7 +1541,10 @@ struct ring_buffer;
struct ring;
struct user_ring_buffer;
-/* Callback-based consumption is unsupported for BPF_F_RB_OVERWRITE maps. */
+/*
+ * Callback-based consumption is unsupported for BPF_F_RB_OVERWRITE maps.
+ * The callback can be NULL for rings that are consumed with ring__next().
+ */
typedef int (*ring_buffer_sample_fn)(void *ctx, void *data, size_t size);
struct ring_buffer_opts {
@@ -1643,6 +1646,64 @@ LIBBPF_API int ring__consume(struct ring *r);
*/
LIBBPF_API int ring__consume_n(struct ring *r, size_t n);
+/*
+ * Record API: get records one by one with ring__next() instead of having them
+ * passed to a sample callback. It can only be used on rings that don't have a
+ * sample callback.
+ */
+
+/**
+ * struct ring_rec describes a record returned by **ring__next()**.
+ */
+struct ring_rec {
+ const void *data; /* record data */
+ unsigned long pos; /* position of the record in the ring buffer */
+ __u32 len; /* size of record data in bytes */
+};
+
+/**
+ * @brief **ring__next()** returns the next record in the ring buffer without
+ * consuming it.
+ *
+ * Record data stays valid until **ring__release()** is called, so multiple
+ * records can be processed and then consumed together:
+ *
+ * do {
+ * while ((rec = ring__next(r)))
+ * handle(rec->data, rec->len);
+ * } while (ring__release(r) > 0);
+ *
+ * Each call invalidates and reuses the previous struct ring_rec, so copy it if
+ * it is needed later.
+ *
+ * @param r A ringbuffer object.
+ * @return The next record, or NULL if there is nothing to consume. errno is
+ * set on any error.
+ */
+LIBBPF_API const struct ring_rec *ring__next(struct ring *r);
+
+/**
+ * @brief **ring__release()** consumes all records returned by **ring__next()**
+ * since the last **ring__release()** or **ring__rewind()**.
+ *
+ * Call it before waiting for new data. If it returns 1, call **ring__next()**
+ * again instead of waiting, as there may be no wakeup for records that were
+ * committed before the release.
+ *
+ * @param r A ringbuffer object.
+ * @return 1 if **ring__next()** has to be called again, 0 if the caller can
+ * wait for new data, or a negative error code on failure.
+ */
+LIBBPF_API int ring__release(struct ring *r);
+
+/**
+ * @brief **ring__rewind()** goes back to the first record that was not
+ * released, so that **ring__next()** returns the same records again.
+ *
+ * @param r A ringbuffer object.
+ */
+LIBBPF_API void ring__rewind(struct ring *r);
+
struct user_ring_buffer_opts {
size_t sz; /* size of this struct, for forward/backward compatibility */
};
diff --git a/tools/lib/bpf/libbpf.map b/tools/lib/bpf/libbpf.map
index a45666f546fa..e373257d32fe 100644
--- a/tools/lib/bpf/libbpf.map
+++ b/tools/lib/bpf/libbpf.map
@@ -479,4 +479,7 @@ LIBBPF_1.9.0 {
bpf_program__load;
bpf_program__load_strategy;
bpf_program__set_load_strategy;
+ ring__next;
+ ring__release;
+ ring__rewind;
} LIBBPF_1.8.0;
diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
index 271c6b9b130d..822557b7149b 100644
--- a/tools/lib/bpf/ringbuf.c
+++ b/tools/lib/bpf/ringbuf.c
@@ -30,6 +30,12 @@ struct ring {
unsigned long *producer_pos;
unsigned long *overwrite_pos;
unsigned long mask;
+ /* ring__next() state: position of the next record and cached producer_pos */
+ unsigned long next_pos;
+ unsigned long prod_pos;
+ struct ring_rec rec;
+ /* always zero, in case struct ring_rec needs new fields */
+ unsigned long rec_reserved[2];
int map_fd;
bool overwrite;
};
@@ -158,6 +164,8 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
*/
if (r->overwrite && sizeof(unsigned long) == sizeof(__u64))
r->overwrite_pos = r->producer_pos + 2;
+ r->next_pos = smp_load_acquire(r->consumer_pos);
+ r->prod_pos = r->next_pos;
e = &rb->events[rb->ring_cnt];
memset(e, 0, sizeof(*e));
@@ -420,7 +428,7 @@ struct ring *ring_buffer__ring(struct ring_buffer *rb, unsigned int idx)
unsigned long ring__consumer_pos(const struct ring *r)
{
- /* Synchronizes with smp_store_release() in ringbuf_process_ring(). */
+ /* Synchronizes with smp_store_release() in ringbuf_process_ring() and ring__release(). */
return smp_load_acquire(r->consumer_pos);
}
@@ -472,6 +480,89 @@ int ring__consume(struct ring *r)
return ring__consume_n(r, INT_MAX);
}
+/* ring__next() and friends can't be mixed with callbacks on the same ring */
+static int ringbuf_validate_rec_api(const struct ring *r)
+{
+ if (unlikely(r->sample_cb))
+ return -EINVAL;
+ if (unlikely(r->overwrite))
+ return -EOPNOTSUPP;
+ return 0;
+}
+
+const struct ring_rec *ring__next(struct ring *r)
+{
+ unsigned long pos, prod_pos;
+ __u32 *len_ptr, len, rec_sz;
+ int err;
+
+ err = ringbuf_validate_rec_api(r);
+ if (err)
+ return libbpf_err_ptr(err);
+
+ pos = r->next_pos;
+ prod_pos = r->prod_pos;
+ for (;;) {
+ if (pos == prod_pos) {
+ prod_pos = smp_load_acquire(r->producer_pos);
+ if (pos == prod_pos)
+ return NULL;
+ }
+
+ len_ptr = r->data + (pos & r->mask);
+ len = smp_load_acquire(len_ptr);
+ /* record is not committed yet */
+ if (len & BPF_RINGBUF_BUSY_BIT)
+ return NULL;
+
+ rec_sz = roundup_len(len);
+ r->next_pos = pos + rec_sz;
+ r->prod_pos = prod_pos;
+ if (!(len & BPF_RINGBUF_DISCARD_BIT)) {
+ r->rec.data = (void *)len_ptr + BPF_RINGBUF_HDR_SZ;
+ r->rec.pos = pos;
+ r->rec.len = len;
+ return &r->rec;
+ }
+ pos += rec_sz;
+ }
+}
+
+int ring__release(struct ring *r)
+{
+ unsigned long pos = r->next_pos;
+ __u32 len;
+ int err;
+
+ err = ringbuf_validate_rec_api(r);
+ if (err)
+ return libbpf_err(err);
+
+ smp_store_release(r->consumer_pos, pos);
+ /*
+ * bpf_ringbuf_commit() clears the busy bit of a record and then checks
+ * consumer_pos to see if it has to wake us up. We update consumer_pos
+ * and then check the record, so without a full barrier in between both
+ * sides can miss each other's update.
+ */
+ smp_mb();
+
+ r->prod_pos = smp_load_acquire(r->producer_pos);
+ if (pos == r->prod_pos)
+ return 0;
+ len = smp_load_acquire((__u32 *)(r->data + (pos & r->mask)));
+ /* we get a wakeup when a busy record is committed */
+ return !(len & BPF_RINGBUF_BUSY_BIT);
+}
+
+void ring__rewind(struct ring *r)
+{
+ if (ringbuf_validate_rec_api(r))
+ return;
+
+ r->next_pos = smp_load_acquire(r->consumer_pos);
+}
+
static void user_ringbuf_unmap_ring(struct user_ring_buffer *rb)
{
if (rb->consumer_pos) {
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* [PATCH bpf-next v1 06/10] libbpf: Add ring_buffer__wait()
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
` (4 preceding siblings ...)
2026-11-23 21:13 ` [PATCH bpf-next v1 05/10] libbpf: Add a record API for consuming BPF ring buffers Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 07/10] libbpf: Support overwritable ring buffers in the record API Kumar Kartikeya Dwivedi
` (3 subsequent siblings)
9 siblings, 0 replies; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Andrii Nakryiko, Alexei Starovoitov,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
ring_buffer__poll() waits for data and then consumes it through the sample
callbacks, so it fails when a ring has no callback. Rings that are
consumed with ring__next() don't have one, so the only way to wait for
them is epoll_wait() on ring_buffer__epoll_fd().
Add ring_buffer__wait(), which only does the epoll_wait() and returns the
number of rings that have data. It works for rings with and without
callbacks: the caller consumes the data afterwards, with ring__consume()
or ring__next() on each ring.
rb = ring_buffer__new(map_fd, NULL, NULL, NULL);
r = ring_buffer__ring(rb, 0);
while (ring_buffer__wait(rb, -1) >= 0) {
do {
while ((rec = ring__next(r)))
handle(rec->data, rec->len);
} while (ring__release(r) > 0);
}
Suggested-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
tools/lib/bpf/libbpf.h | 15 +++++++++++++++
tools/lib/bpf/libbpf.map | 1 +
tools/lib/bpf/ringbuf.c | 12 ++++++++++++
3 files changed, 28 insertions(+)
diff --git a/tools/lib/bpf/libbpf.h b/tools/lib/bpf/libbpf.h
index efd796603fa3..91d25bed5a04 100644
--- a/tools/lib/bpf/libbpf.h
+++ b/tools/lib/bpf/libbpf.h
@@ -1560,6 +1560,21 @@ LIBBPF_API void ring_buffer__free(struct ring_buffer *rb);
LIBBPF_API int ring_buffer__add(struct ring_buffer *rb, int map_fd,
ring_buffer_sample_fn sample_cb, void *ctx);
LIBBPF_API int ring_buffer__poll(struct ring_buffer *rb, int timeout_ms);
+
+/**
+ * @brief **ring_buffer__wait()** waits until at least one of the rings has
+ * data, without consuming it.
+ *
+ * Unlike **ring_buffer__poll()** it doesn't call sample callbacks, so it also
+ * works for rings that are consumed with **ring__next()**.
+ *
+ * @param rb A ringbuffer manager object.
+ * @param timeout_ms Maximum time to wait in milliseconds, 0 to not wait at
+ * all, -1 to wait indefinitely.
+ * @return The number of rings that have data, 0 if the timeout expired, or a
+ * negative error code on failure.
+ */
+LIBBPF_API int ring_buffer__wait(struct ring_buffer *rb, int timeout_ms);
LIBBPF_API int ring_buffer__consume(struct ring_buffer *rb);
LIBBPF_API int ring_buffer__consume_n(struct ring_buffer *rb, size_t n);
LIBBPF_API int ring_buffer__epoll_fd(const struct ring_buffer *rb);
diff --git a/tools/lib/bpf/libbpf.map b/tools/lib/bpf/libbpf.map
index e373257d32fe..943f6f3f0639 100644
--- a/tools/lib/bpf/libbpf.map
+++ b/tools/lib/bpf/libbpf.map
@@ -482,4 +482,5 @@ LIBBPF_1.9.0 {
ring__next;
ring__release;
ring__rewind;
+ ring_buffer__wait;
} LIBBPF_1.8.0;
diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
index 822557b7149b..12d586afed1d 100644
--- a/tools/lib/bpf/ringbuf.c
+++ b/tools/lib/bpf/ringbuf.c
@@ -412,6 +412,18 @@ int ring_buffer__poll(struct ring_buffer *rb, int timeout_ms)
return res;
}
+/* Wait for data in the ring(s) without consuming it */
+int ring_buffer__wait(struct ring_buffer *rb, int timeout_ms)
+{
+ int cnt;
+
+ cnt = epoll_wait(rb->epoll_fd, rb->events, rb->ring_cnt, timeout_ms);
+ if (cnt < 0)
+ return libbpf_err(-errno);
+
+ return cnt;
+}
+
/* Get an fd that can be used to sleep until data is available in the ring(s) */
int ring_buffer__epoll_fd(const struct ring_buffer *rb)
{
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* [PATCH bpf-next v1 07/10] libbpf: Support overwritable ring buffers in the record API
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
` (5 preceding siblings ...)
2026-11-23 21:13 ` [PATCH bpf-next v1 06/10] libbpf: Add ring_buffer__wait() Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:28 ` sashiko-bot
2026-11-23 21:13 ` [PATCH bpf-next v1 08/10] libbpf: Split ring setup out of ring_buffer__add() Kumar Kartikeya Dwivedi
` (2 subsequent siblings)
9 siblings, 1 reply; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
In an overwritable ring buffer (BPF_F_RB_OVERWRITE) the kernel doesn't
wait for the consumer and overwrites the oldest records when the ring
buffer is full. A record returned by ring__next() can be overwritten while
the caller is reading it, which is why such ring buffers can't be consumed
through callbacks.
Add ring__invalidated(), which returns true if any of the records returned
by ring__next() since the last ring__release() or ring__rewind() may have
been overwritten. The caller has to copy record data first, and use the
copy only if ring__invalidated() returns false afterwards:
do {
while ((rec = ring__next(r))) {
memcpy(copy, rec->data, rec->len);
if (ring__invalidated(r))
break;
handle(copy, rec->len);
}
} while (ring__release(r) > 0);
It can also be called once for a number of records, e.g. to dump the ring
buffer without consuming anything:
n = 0;
while ((rec = ring__next(r))) {
memcpy(copies[n], rec->data, rec->len);
lens[n++] = rec->len;
}
if (!ring__invalidated(r))
dump(copies, lens, n);
ring__rewind(r);
Records are overwritten in order, so ring__invalidated() only has to check
that the producer is less than a ring buffer size ahead of the first record
returned since the last release or rewind. For regular ring buffers it
always returns false.
Overwritable ring buffers get their own implementation of ring__next(),
ringbuf_overwrite_next(), so that the regular one stays as it is.
ringbuf_overwrite_next() does the same check for every record header
before using it, so pos and len of a returned record are always valid and
only record data needs ring__invalidated(). If the check fails, it
continues from the kernel's overwrite position. There is no limit on how
often that can repeat: a producer that keeps overwriting records before
they can be read is not expected in practice.
Overwritable ring buffers are not supported by 32-bit libbpf, where
ring__next() fails with EOPNOTSUPP. It doesn't know where the overwrite
position is, and 32-bit positions wrap after 4 GiB of records, which the
check can't notice.
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
tools/lib/bpf/libbpf.h | 32 ++++++++++++++
tools/lib/bpf/libbpf.map | 1 +
tools/lib/bpf/ringbuf.c | 94 ++++++++++++++++++++++++++++++++++++++--
3 files changed, 123 insertions(+), 4 deletions(-)
diff --git a/tools/lib/bpf/libbpf.h b/tools/lib/bpf/libbpf.h
index 91d25bed5a04..24a70bf3f782 100644
--- a/tools/lib/bpf/libbpf.h
+++ b/tools/lib/bpf/libbpf.h
@@ -1691,6 +1691,10 @@ struct ring_rec {
* Each call invalidates and reuses the previous struct ring_rec, so copy it if
* it is needed later.
*
+ * In an overwritable ring buffer (BPF_F_RB_OVERWRITE) record data can be
+ * overwritten at any time, see **ring__invalidated()**. Such ring buffers are
+ * not supported by 32-bit libbpf: **ring__next()** fails with EOPNOTSUPP.
+ *
* @param r A ringbuffer object.
* @return The next record, or NULL if there is nothing to consume. errno is
* set on any error.
@@ -1719,6 +1723,34 @@ LIBBPF_API int ring__release(struct ring *r);
*/
LIBBPF_API void ring__rewind(struct ring *r);
+/**
+ * @brief **ring__invalidated()** checks if any of the records returned by
+ * **ring__next()** since the last **ring__release()** or **ring__rewind()**
+ * may have been overwritten.
+ *
+ * The kernel can overwrite records of an overwritable ring buffer
+ * (BPF_F_RB_OVERWRITE) while they are being read. Copy record data first, and
+ * use the copy only if this function returns false afterwards:
+ *
+ * do {
+ * while ((rec = ring__next(r))) {
+ * memcpy(copy, rec->data, rec->len);
+ * if (ring__invalidated(r))
+ * break;
+ * handle(copy, rec->len);
+ * }
+ * } while (ring__release(r) > 0);
+ *
+ * Once it returns true, it keeps returning true until **ring__release()** or
+ * **ring__rewind()** is called. *pos* and *len* of a returned record are
+ * always valid and don't need this check.
+ *
+ * @param r A ringbuffer object.
+ * @return true if records may have been overwritten, false if not. Always
+ * false for a ring buffer that is not overwritable.
+ */
+LIBBPF_API bool ring__invalidated(const struct ring *r);
+
struct user_ring_buffer_opts {
size_t sz; /* size of this struct, for forward/backward compatibility */
};
diff --git a/tools/lib/bpf/libbpf.map b/tools/lib/bpf/libbpf.map
index 943f6f3f0639..6a953f123138 100644
--- a/tools/lib/bpf/libbpf.map
+++ b/tools/lib/bpf/libbpf.map
@@ -479,6 +479,7 @@ LIBBPF_1.9.0 {
bpf_program__load;
bpf_program__load_strategy;
bpf_program__set_load_strategy;
+ ring__invalidated;
ring__next;
ring__release;
ring__rewind;
diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
index 12d586afed1d..b4e9e27951eb 100644
--- a/tools/lib/bpf/ringbuf.c
+++ b/tools/lib/bpf/ringbuf.c
@@ -36,6 +36,9 @@ struct ring {
struct ring_rec rec;
/* always zero, in case struct ring_rec needs new fields */
unsigned long rec_reserved[2];
+ /* overwrite mode: first record returned since the last release or rewind */
+ unsigned long batch_pos;
+ bool has_batch;
int map_fd;
bool overwrite;
};
@@ -497,11 +500,72 @@ static int ringbuf_validate_rec_api(const struct ring *r)
{
if (unlikely(r->sample_cb))
return -EINVAL;
- if (unlikely(r->overwrite))
+ /* 32-bit: no overwrite_pos, and positions wrap after 4 GiB of records */
+ if (unlikely(r->overwrite && !r->overwrite_pos))
return -EOPNOTSUPP;
return 0;
}
+/*
+ * Overwrite mode: check that whatever was read at pos, and at later positions,
+ * was not overwritten while we were reading it. The producer can overwrite pos
+ * once it is a ring size ahead of pos.
+ */
+static bool ringbuf_pos_valid(const struct ring *r, unsigned long pos, unsigned long *prod_pos)
+{
+ /* pairs with smp_wmb() after the producer_pos update in the kernel */
+ smp_rmb();
+ *prod_pos = smp_load_acquire(r->producer_pos);
+ return *prod_pos - pos <= r->mask;
+}
+
+/* ring__next() for overwritable ring buffers */
+static const struct ring_rec *ringbuf_overwrite_next(struct ring *r)
+{
+ unsigned long pos = r->next_pos, prod_pos;
+ __u32 *len_ptr, len;
+
+ prod_pos = smp_load_acquire(r->producer_pos);
+ for (;;) {
+ if (prod_pos - pos > r->mask) {
+ /*
+ * The producer lapped us, continue from the oldest record.
+ * overwrite_pos is never ahead of a producer_pos that is
+ * loaded after it.
+ */
+ pos = smp_load_acquire(r->overwrite_pos);
+ prod_pos = smp_load_acquire(r->producer_pos);
+ continue;
+ }
+ r->next_pos = pos;
+ if (pos == prod_pos)
+ return NULL;
+
+ len_ptr = r->data + (pos & r->mask);
+ len = smp_load_acquire(len_ptr);
+ /* if the producer lapped us, this is not a record header */
+ if (!ringbuf_pos_valid(r, pos, &prod_pos))
+ continue;
+ /* record is not committed yet */
+ if (len & BPF_RINGBUF_BUSY_BIT)
+ return NULL;
+
+ r->next_pos = pos + roundup_len(len);
+ if (len & BPF_RINGBUF_DISCARD_BIT) {
+ pos = r->next_pos;
+ continue;
+ }
+ if (!r->has_batch) {
+ r->batch_pos = pos;
+ r->has_batch = true;
+ }
+ r->rec.data = (void *)len_ptr + BPF_RINGBUF_HDR_SZ;
+ r->rec.pos = pos;
+ r->rec.len = len;
+ return &r->rec;
+ }
+}
+
const struct ring_rec *ring__next(struct ring *r)
{
unsigned long pos, prod_pos;
@@ -512,6 +576,9 @@ const struct ring_rec *ring__next(struct ring *r)
if (err)
return libbpf_err_ptr(err);
+ if (r->overwrite)
+ return ringbuf_overwrite_next(r);
+
pos = r->next_pos;
prod_pos = r->prod_pos;
for (;;) {
@@ -540,9 +607,20 @@ const struct ring_rec *ring__next(struct ring *r)
}
}
+bool ring__invalidated(const struct ring *r)
+{
+ unsigned long prod_pos;
+
+ if (!r->has_batch)
+ return false;
+
+ /* records are overwritten in order, so it is enough to check the first one */
+ return !ringbuf_pos_valid(r, r->batch_pos, &prod_pos);
+}
+
int ring__release(struct ring *r)
{
- unsigned long pos = r->next_pos;
+ unsigned long pos = r->next_pos, prod_pos;
__u32 len;
int err;
@@ -550,6 +628,7 @@ int ring__release(struct ring *r)
if (err)
return libbpf_err(err);
+ r->has_batch = false;
smp_store_release(r->consumer_pos, pos);
/*
* bpf_ringbuf_commit() clears the busy bit of a record and then checks
@@ -563,8 +642,14 @@ int ring__release(struct ring *r)
if (pos == r->prod_pos)
return 0;
len = smp_load_acquire((__u32 *)(r->data + (pos & r->mask)));
- /* we get a wakeup when a busy record is committed */
- return !(len & BPF_RINGBUF_BUSY_BIT);
+ if (!(len & BPF_RINGBUF_BUSY_BIT))
+ return 1;
+ /*
+ * A busy record wakes us up when it is committed, so return 0. In
+ * overwrite mode return 1 if the producer lapped us, as len was not
+ * read from a record header then.
+ */
+ return r->overwrite && !ringbuf_pos_valid(r, pos, &prod_pos);
}
void ring__rewind(struct ring *r)
@@ -573,6 +658,7 @@ void ring__rewind(struct ring *r)
return;
r->next_pos = smp_load_acquire(r->consumer_pos);
+ r->has_batch = false;
}
static void user_ringbuf_unmap_ring(struct user_ring_buffer *rb)
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* Re: [PATCH bpf-next v1 07/10] libbpf: Support overwritable ring buffers in the record API
2026-11-23 21:13 ` [PATCH bpf-next v1 07/10] libbpf: Support overwritable ring buffers in the record API Kumar Kartikeya Dwivedi
@ 2026-11-23 21:28 ` sashiko-bot
0 siblings, 0 replies; 15+ messages in thread
From: sashiko-bot @ 2026-11-23 21:28 UTC (permalink / raw)
To: Kumar Kartikeya Dwivedi, bpf
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] libbpf: silent loss of valid records via batch_pos in
ring__invalidated()
--
commit d2233d2ea9e5d957fed51c54cbd2073eb0c4fc69
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>
libbpf: Support overwritable ring buffers in the record API
This commit adds support for overwritable BPF ring buffers
(BPF_F_RB_OVERWRITE) to the libbpf record API and introduces
ring__invalidated() to detect whether records returned since the last
release or rewind were overwritten.
> diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
> index 12d586afed1dd..b4e9e27951eb8 100644
> --- a/tools/lib/bpf/ringbuf.c
> +++ b/tools/lib/bpf/ringbuf.c
[ ... ]
> @@ -497,11 +500,72 @@ static int ringbuf_validate_rec_api(const struct ring *r)
> {
> if (unlikely(r->sample_cb))
> return -EINVAL;
> - if (unlikely(r->overwrite))
> + /* 32-bit: no overwrite_pos, and positions wrap after 4 GiB of records */
> + if (unlikely(r->overwrite && !r->overwrite_pos))
> return -EOPNOTSUPP;
> return 0;
> }
>
> +/*
> + * Overwrite mode: check that whatever was read at pos, and at later positions,
> + * was not overwritten while we were reading it. The producer can overwrite pos
> + * once it is a ring size ahead of pos.
> + */
> +static bool ringbuf_pos_valid(const struct ring *r, unsigned long pos, unsigned long *prod_pos)
> +{
> + /* pairs with smp_wmb() after the producer_pos update in the kernel */
> + smp_rmb();
> + *prod_pos = smp_load_acquire(r->producer_pos);
> + return *prod_pos - pos <= r->mask;
> +}
> +
> +/* ring__next() for overwritable ring buffers */
> +static const struct ring_rec *ringbuf_overwrite_next(struct ring *r)
> +{
> + unsigned long pos = r->next_pos, prod_pos;
> + __u32 *len_ptr, len;
> +
> + prod_pos = smp_load_acquire(r->producer_pos);
> + for (;;) {
> + if (prod_pos - pos > r->mask) {
> + /*
> + * The producer lapped us, continue from the oldest record.
> + * overwrite_pos is never ahead of a producer_pos that is
> + * loaded after it.
> + */
> + pos = smp_load_acquire(r->overwrite_pos);
> + prod_pos = smp_load_acquire(r->producer_pos);
> + continue;
> + }
> + r->next_pos = pos;
> + if (pos == prod_pos)
> + return NULL;
> +
> + len_ptr = r->data + (pos & r->mask);
> + len = smp_load_acquire(len_ptr);
> + /* if the producer lapped us, this is not a record header */
> + if (!ringbuf_pos_valid(r, pos, &prod_pos))
> + continue;
> + /* record is not committed yet */
> + if (len & BPF_RINGBUF_BUSY_BIT)
> + return NULL;
> +
> + r->next_pos = pos + roundup_len(len);
> + if (len & BPF_RINGBUF_DISCARD_BIT) {
> + pos = r->next_pos;
> + continue;
> + }
> + if (!r->has_batch) {
> + r->batch_pos = pos;
> + r->has_batch = true;
> + }
> + r->rec.data = (void *)len_ptr + BPF_RINGBUF_HDR_SZ;
> + r->rec.pos = pos;
> + r->rec.len = len;
> + return &r->rec;
> + }
> +}
[ ... ]
> @@ -540,9 +607,20 @@ const struct ring_rec *ring__next(struct ring *r)
> }
> }
>
> +bool ring__invalidated(const struct ring *r)
> +{
> + unsigned long prod_pos;
> +
> + if (!r->has_batch)
> + return false;
> +
> + /* records are overwritten in order, so it is enough to check the first one */
> + return !ringbuf_pos_valid(r, r->batch_pos, &prod_pos);
> +}
> +
> int ring__release(struct ring *r)
> {
> - unsigned long pos = r->next_pos;
> + unsigned long pos = r->next_pos, prod_pos;
> __u32 len;
> int err;
>
> err = ringbuf_validate_rec_api(r);
> if (err)
> return libbpf_err(err);
>
> + r->has_batch = false;
> smp_store_release(r->consumer_pos, pos);
[Severity: Medium]
Can checking r->batch_pos in ring__invalidated() cause the documented
consumption loop to drop valid records that were never overwritten?
In the per-record loop:
do {
while ((rec = ring__next(r))) {
memcpy(copy, rec->data, rec->len);
if (ring__invalidated(r))
break;
handle(copy, rec->len);
}
} while (ring__release(r) > 0);
r->batch_pos is only set on the first record returned after
ring__release() or ring__rewind(), while r->next_pos advances past every
record returned by ring__next().
If the inner loop processes record A at r->batch_pos and then reads a
later record B, the producer can overwrite record A without reaching
record B. ring__invalidated() still checks r->batch_pos, so it returns
true for record B even though B's data copy is valid. The caller then
breaks out of the inner loop without handling B, and ring__release()
advances r->consumer_pos to r->next_pos (past B), permanently skipping
record B.
Similarly, if the producer laps pos on a later iteration of the same
batch (when r->has_batch is already true), ringbuf_overwrite_next() jumps
to r->overwrite_pos, advances r->next_pos past the oldest valid record
there, and returns it with r->batch_pos still pointing to the lapped start
of the batch. ring__invalidated() is then guaranteed to return true, so
ring__release() drops that record too (and in the ring__rewind() dump
pattern, jumping to r->overwrite_pos mid-batch keeps returning records for
a batch that is already invalidated).
--
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795467315.git.memxor@gmail.com?part=7
^ permalink raw reply [flat|nested] 15+ messages in thread
* [PATCH bpf-next v1 08/10] libbpf: Split ring setup out of ring_buffer__add()
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
` (6 preceding siblings ...)
2026-11-23 21:13 ` [PATCH bpf-next v1 07/10] libbpf: Support overwritable ring buffers in the record API Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 09/10] libbpf: Add ring__new() and ring__free() Kumar Kartikeya Dwivedi
2026-11-23 21:13 ` [PATCH bpf-next v1 10/10] selftests/bpf: Add tests for the ring buffer record API Kumar Kartikeya Dwivedi
9 siblings, 0 replies; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
Move the part of ring_buffer__add() that validates and mmap()s the ring
buffer map into ringbuf_map_ring(), and keep the page size in struct ring
instead of taking it from the ring_buffer manager. This way a ring can be
set up and freed without a manager.
No functional changes intended.
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
tools/lib/bpf/ringbuf.c | 88 ++++++++++++++++++++++++-----------------
1 file changed, 51 insertions(+), 37 deletions(-)
diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
index b4e9e27951eb..90ed354118de 100644
--- a/tools/lib/bpf/ringbuf.c
+++ b/tools/lib/bpf/ringbuf.c
@@ -39,6 +39,7 @@ struct ring {
/* overwrite mode: first record returned since the last release or rewind */
unsigned long batch_pos;
bool has_batch;
+ size_t page_size;
int map_fd;
bool overwrite;
};
@@ -68,28 +69,24 @@ struct ringbuf_hdr {
__u32 pad;
};
-static void ringbuf_free_ring(struct ring_buffer *rb, struct ring *r)
+static void ringbuf_free_ring(struct ring *r)
{
if (r->consumer_pos) {
- munmap(r->consumer_pos, rb->page_size);
+ munmap(r->consumer_pos, r->page_size);
r->consumer_pos = NULL;
}
if (r->producer_pos) {
- munmap(r->producer_pos, rb->page_size + 2 * (r->mask + 1));
+ munmap(r->producer_pos, r->page_size + 2 * (r->mask + 1));
r->producer_pos = NULL;
}
free(r);
}
-/* Add extra RINGBUF maps to this ring buffer manager */
-int ring_buffer__add(struct ring_buffer *rb, int map_fd,
- ring_buffer_sample_fn sample_cb, void *ctx)
+static int ringbuf_map_ring(struct ring *r, int map_fd)
{
struct bpf_map_info info;
__u32 len = sizeof(info);
- struct epoll_event *e;
- struct ring *r;
__u64 mmap_sz;
void *tmp;
int err;
@@ -101,43 +98,26 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
err = -errno;
pr_warn("ringbuf: failed to get map info for fd=%d: %s\n",
map_fd, errstr(err));
- return libbpf_err(err);
+ return err;
}
if (info.type != BPF_MAP_TYPE_RINGBUF) {
pr_warn("ringbuf: map fd=%d is not BPF_MAP_TYPE_RINGBUF\n",
map_fd);
- return libbpf_err(-EINVAL);
+ return -EINVAL;
}
- tmp = libbpf_reallocarray(rb->rings, rb->ring_cnt + 1, sizeof(*rb->rings));
- if (!tmp)
- return libbpf_err(-ENOMEM);
- rb->rings = tmp;
-
- tmp = libbpf_reallocarray(rb->events, rb->ring_cnt + 1, sizeof(*rb->events));
- if (!tmp)
- return libbpf_err(-ENOMEM);
- rb->events = tmp;
-
- r = calloc(1, sizeof(*r));
- if (!r)
- return libbpf_err(-ENOMEM);
- rb->rings[rb->ring_cnt] = r;
-
r->map_fd = map_fd;
- r->sample_cb = sample_cb;
- r->ctx = ctx;
r->mask = info.max_entries - 1;
r->overwrite = info.map_flags & BPF_F_RB_OVERWRITE;
/* Map writable consumer page */
- tmp = mmap(NULL, rb->page_size, PROT_READ | PROT_WRITE, MAP_SHARED, map_fd, 0);
+ tmp = mmap(NULL, r->page_size, PROT_READ | PROT_WRITE, MAP_SHARED, map_fd, 0);
if (tmp == MAP_FAILED) {
err = -errno;
pr_warn("ringbuf: failed to mmap consumer page for map fd=%d: %s\n",
map_fd, errstr(err));
- goto err_out;
+ return err;
}
r->consumer_pos = tmp;
@@ -145,21 +125,20 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
* data size to allow simple reading of samples that wrap around the
* end of a ring buffer. See kernel implementation for details.
*/
- mmap_sz = rb->page_size + 2 * (__u64)info.max_entries;
+ mmap_sz = r->page_size + 2 * (__u64)info.max_entries;
if (mmap_sz != (__u64)(size_t)mmap_sz) {
- err = -E2BIG;
pr_warn("ringbuf: ring buffer size (%u) is too big\n", info.max_entries);
- goto err_out;
+ return -E2BIG;
}
- tmp = mmap(NULL, (size_t)mmap_sz, PROT_READ, MAP_SHARED, map_fd, rb->page_size);
+ tmp = mmap(NULL, (size_t)mmap_sz, PROT_READ, MAP_SHARED, map_fd, r->page_size);
if (tmp == MAP_FAILED) {
err = -errno;
pr_warn("ringbuf: failed to mmap data pages for map fd=%d: %s\n",
map_fd, errstr(err));
- goto err_out;
+ return err;
}
r->producer_pos = tmp;
- r->data = tmp + rb->page_size;
+ r->data = tmp + r->page_size;
/*
* overwrite_pos comes after producer_pos and pending_pos. Its offset
* depends on the size of the kernel's unsigned long, which 32-bit libbpf
@@ -170,6 +149,41 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
r->next_pos = smp_load_acquire(r->consumer_pos);
r->prod_pos = r->next_pos;
+ return 0;
+}
+
+/* Add extra RINGBUF maps to this ring buffer manager */
+int ring_buffer__add(struct ring_buffer *rb, int map_fd,
+ ring_buffer_sample_fn sample_cb, void *ctx)
+{
+ struct epoll_event *e;
+ struct ring *r;
+ void *tmp;
+ int err;
+
+ tmp = libbpf_reallocarray(rb->rings, rb->ring_cnt + 1, sizeof(*rb->rings));
+ if (!tmp)
+ return libbpf_err(-ENOMEM);
+ rb->rings = tmp;
+
+ tmp = libbpf_reallocarray(rb->events, rb->ring_cnt + 1, sizeof(*rb->events));
+ if (!tmp)
+ return libbpf_err(-ENOMEM);
+ rb->events = tmp;
+
+ r = calloc(1, sizeof(*r));
+ if (!r)
+ return libbpf_err(-ENOMEM);
+ rb->rings[rb->ring_cnt] = r;
+
+ r->page_size = rb->page_size;
+ r->sample_cb = sample_cb;
+ r->ctx = ctx;
+
+ err = ringbuf_map_ring(r, map_fd);
+ if (err)
+ goto err_out;
+
e = &rb->events[rb->ring_cnt];
memset(e, 0, sizeof(*e));
@@ -186,7 +200,7 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
return 0;
err_out:
- ringbuf_free_ring(rb, r);
+ ringbuf_free_ring(r);
return libbpf_err(err);
}
@@ -198,7 +212,7 @@ void ring_buffer__free(struct ring_buffer *rb)
return;
for (i = 0; i < rb->ring_cnt; ++i)
- ringbuf_free_ring(rb, rb->rings[i]);
+ ringbuf_free_ring(rb->rings[i]);
if (rb->epoll_fd >= 0)
close(rb->epoll_fd);
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* [PATCH bpf-next v1 09/10] libbpf: Add ring__new() and ring__free()
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
` (7 preceding siblings ...)
2026-11-23 21:13 ` [PATCH bpf-next v1 08/10] libbpf: Split ring setup out of ring_buffer__add() Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
2026-11-23 21:20 ` sashiko-bot
2026-11-23 21:13 ` [PATCH bpf-next v1 10/10] selftests/bpf: Add tests for the ring buffer record API Kumar Kartikeya Dwivedi
9 siblings, 1 reply; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
A struct ring can only be obtained from a ring_buffer manager, which
creates an epoll instance and owns all its rings. An application that
consumes a single ring buffer with ring__next() and polls the map fd in
its own event loop doesn't need the manager.
Add ring__new() to create a struct ring directly from a ring buffer map
fd, and ring__free() to free it:
r = ring__new(map_fd, NULL);
epoll_ctl(epfd, EPOLL_CTL_ADD, ring__map_fd(r), &ev);
for (;;) {
epoll_wait(epfd, &ev, 1, -1);
do {
while ((rec = ring__next(r)))
handle(rec->data, rec->len);
} while (ring__release(r) > 0);
}
ring__free(r);
Rings that belong to a ring_buffer manager are still freed by
ring_buffer__free() and must not be passed to ring__free(). It is an easy
mistake to make and hard to debug, so ring__free() prints a warning and
does nothing for such a ring.
ring__new() takes an opts struct for future extensions, like
ring_buffer__new() and user_ring_buffer__new().
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
tools/lib/bpf/libbpf.h | 29 +++++++++++++++++++++++++++++
tools/lib/bpf/libbpf.map | 2 ++
tools/lib/bpf/ringbuf.c | 40 ++++++++++++++++++++++++++++++++++++++++
3 files changed, 71 insertions(+)
diff --git a/tools/lib/bpf/libbpf.h b/tools/lib/bpf/libbpf.h
index 24a70bf3f782..038502f27014 100644
--- a/tools/lib/bpf/libbpf.h
+++ b/tools/lib/bpf/libbpf.h
@@ -1593,6 +1593,35 @@ LIBBPF_API int ring_buffer__epoll_fd(const struct ring_buffer *rb);
LIBBPF_API struct ring *ring_buffer__ring(struct ring_buffer *rb,
unsigned int idx);
+struct ring_opts {
+ size_t sz;
+ size_t :0;
+};
+#define ring_opts__last_field sz
+
+/**
+ * @brief **ring__new()** creates a ringbuffer object for a single
+ * BPF_MAP_TYPE_RINGBUF map, without a ringbuffer manager.
+ *
+ * The ring has no sample callback, so it can only be consumed with
+ * **ring__next()**. Free it with **ring__free()**. To wait for data, poll
+ * *map_fd*.
+ *
+ * @param map_fd File descriptor of a BPF_MAP_TYPE_RINGBUF map.
+ * @param opts Options, can be NULL.
+ * @return A ringbuffer object on success; NULL and errno set on error.
+ */
+LIBBPF_API struct ring *ring__new(int map_fd, const struct ring_opts *opts);
+
+/**
+ * @brief **ring__free()** frees a ringbuffer object created with
+ * **ring__new()**. Rings returned by **ring_buffer__ring()** are freed by
+ * **ring_buffer__free()** and must not be passed to this function.
+ *
+ * @param r A ringbuffer object, can be NULL.
+ */
+LIBBPF_API void ring__free(struct ring *r);
+
/**
* @brief **ring__consumer_pos()** returns the current consumer position in the
* given ringbuffer.
diff --git a/tools/lib/bpf/libbpf.map b/tools/lib/bpf/libbpf.map
index 6a953f123138..16e15f79af54 100644
--- a/tools/lib/bpf/libbpf.map
+++ b/tools/lib/bpf/libbpf.map
@@ -479,7 +479,9 @@ LIBBPF_1.9.0 {
bpf_program__load;
bpf_program__load_strategy;
bpf_program__set_load_strategy;
+ ring__free;
ring__invalidated;
+ ring__new;
ring__next;
ring__release;
ring__rewind;
diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
index 90ed354118de..e794448dcb89 100644
--- a/tools/lib/bpf/ringbuf.c
+++ b/tools/lib/bpf/ringbuf.c
@@ -42,6 +42,8 @@ struct ring {
size_t page_size;
int map_fd;
bool overwrite;
+ /* created by ring__new(), not owned by a ring_buffer */
+ bool standalone;
};
struct ring_buffer {
@@ -204,6 +206,44 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
return libbpf_err(err);
}
+struct ring *ring__new(int map_fd, const struct ring_opts *opts)
+{
+ struct ring *r;
+ int err;
+
+ if (!OPTS_VALID(opts, ring_opts))
+ return errno = EINVAL, NULL;
+
+ r = calloc(1, sizeof(*r));
+ if (!r)
+ return errno = ENOMEM, NULL;
+
+ r->page_size = getpagesize();
+ r->standalone = true;
+
+ err = ringbuf_map_ring(r, map_fd);
+ if (err) {
+ ringbuf_free_ring(r);
+ return errno = -err, NULL;
+ }
+
+ return r;
+}
+
+void ring__free(struct ring *r)
+{
+ if (!r)
+ return;
+
+ if (!r->standalone) {
+ pr_warn("ringbuf: ring__free() called for a ring owned by ring_buffer, map fd=%d\n",
+ r->map_fd);
+ return;
+ }
+
+ ringbuf_free_ring(r);
+}
+
void ring_buffer__free(struct ring_buffer *rb)
{
int i;
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread* Re: [PATCH bpf-next v1 09/10] libbpf: Add ring__new() and ring__free()
2026-11-23 21:13 ` [PATCH bpf-next v1 09/10] libbpf: Add ring__new() and ring__free() Kumar Kartikeya Dwivedi
@ 2026-11-23 21:20 ` sashiko-bot
0 siblings, 0 replies; 15+ messages in thread
From: sashiko-bot @ 2026-11-23 21:20 UTC (permalink / raw)
To: Kumar Kartikeya Dwivedi, bpf
Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] libbpf: ring__new() bypasses libbpf_err_ptr() on error return
paths
--
commit 3d8ab4da44ad53020ae84560a8e42655f36bab40
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>
libbpf: Add ring__new() and ring__free()
This commit adds ring__new() and ring__free() to allow creating and freeing a
standalone struct ring directly from a ring buffer map fd without a
ring_buffer manager.
> diff --git a/tools/lib/bpf/ringbuf.c b/tools/lib/bpf/ringbuf.c
> index 90ed354118de3..e794448dcb891 100644
> --- a/tools/lib/bpf/ringbuf.c
> +++ b/tools/lib/bpf/ringbuf.c
[ ... ]
> @@ -204,6 +206,44 @@ int ring_buffer__add(struct ring_buffer *rb, int map_fd,
> return libbpf_err(err);
> }
>
> +struct ring *ring__new(int map_fd, const struct ring_opts *opts)
> +{
> + struct ring *r;
> + int err;
> +
> + if (!OPTS_VALID(opts, ring_opts))
> + return errno = EINVAL, NULL;
> +
> + r = calloc(1, sizeof(*r));
> + if (!r)
> + return errno = ENOMEM, NULL;
> +
> + r->page_size = getpagesize();
> + r->standalone = true;
> +
> + err = ringbuf_map_ring(r, map_fd);
> + if (err) {
> + ringbuf_free_ring(r);
> + return errno = -err, NULL;
> + }
> +
> + return r;
> +}
[Severity: Medium]
Should ring__new() wrap its error returns with libbpf_err_ptr() (-EINVAL,
-ENOMEM, and err) instead of setting errno and returning NULL directly, matching
other public pointer-returning libbpf APIs?
--
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795467315.git.memxor@gmail.com?part=9
^ permalink raw reply [flat|nested] 15+ messages in thread
* [PATCH bpf-next v1 10/10] selftests/bpf: Add tests for the ring buffer record API
2026-11-23 21:13 [PATCH bpf-next v1 00/10] Ring Buffer Iterator API Kumar Kartikeya Dwivedi
` (8 preceding siblings ...)
2026-11-23 21:13 ` [PATCH bpf-next v1 09/10] libbpf: Add ring__new() and ring__free() Kumar Kartikeya Dwivedi
@ 2026-11-23 21:13 ` Kumar Kartikeya Dwivedi
9 siblings, 0 replies; 15+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-11-23 21:13 UTC (permalink / raw)
To: bpf
Cc: Xu Kuohai, Tamir Duberstein, Alexei Starovoitov, Andrii Nakryiko,
Daniel Borkmann, Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai,
kkd, kernel-team
Add tests for ring__next(), ring__release(), ring__rewind(),
ring__invalidated(), ring__new(), ring__free() and ring_buffer__wait().
Records are produced by a syscall program run with
bpf_prog_test_run_opts(), and every 8-byte word of a record holds its
sequence number, so that the tests can check all of the data they read.
- basic: records of different sizes, release after all and after only
some of the available records were returned.
- rewind_discard: rewind, discarded records.
- manager: ring_buffer__wait() with rings with and without a callback,
ring__next() on a ring with a callback, ring__free() on a ring owned by
the manager.
- standalone: ring__new() and ring__free(), edge-triggered epoll on the
map fd.
- overwrite_basic: only the most recent records are returned from an
overwritable ring buffer. The API doesn't report overwritten bytes; the
test computes them from the positions of consecutive records.
- overwrite_batch: ring__invalidated() covers the records returned since
the last release or rewind.
- overwrite_race: consume while a thread keeps producing for 1.5 seconds.
Every record that passes ring__invalidated() must have valid data and
sequence numbers must only increase.
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
.../selftests/bpf/prog_tests/ringbuf_iter.c | 586 ++++++++++++++++++
.../selftests/bpf/progs/test_ringbuf_iter.c | 66 ++
2 files changed, 652 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/ringbuf_iter.c
create mode 100644 tools/testing/selftests/bpf/progs/test_ringbuf_iter.c
diff --git a/tools/testing/selftests/bpf/prog_tests/ringbuf_iter.c b/tools/testing/selftests/bpf/prog_tests/ringbuf_iter.c
new file mode 100644
index 000000000000..d416bb19d101
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/ringbuf_iter.c
@@ -0,0 +1,586 @@
+// SPDX-License-Identifier: GPL-2.0
+#define _GNU_SOURCE
+#include <test_progs.h>
+#include <sys/epoll.h>
+#include <pthread.h>
+#include "test_ringbuf_iter.skel.h"
+
+/* Mirrors the context of the producer programs. */
+struct produce_args {
+ __u64 seq;
+ __u32 count;
+ __u32 size;
+ __u32 discard_mod;
+ __u32 flags;
+ __u32 produced;
+};
+
+static int page_size;
+
+static int produce(int prog_fd, struct produce_args *args)
+{
+ /* Syscall programs copy the context back into ctx_in. */
+ LIBBPF_OPTS(bpf_test_run_opts, opts,
+ .ctx_in = args,
+ .ctx_size_in = sizeof(*args),
+ );
+ int err;
+
+ args->produced = 0;
+ err = bpf_prog_test_run_opts(prog_fd, &opts);
+ if (!ASSERT_OK(err, "produce_run") || !ASSERT_OK(opts.retval, "produce_retval") ||
+ !ASSERT_EQ(args->produced, args->count, "produced"))
+ return -1;
+ return 0;
+}
+
+/*
+ * Produce `count` records of `size` bytes. Every 8-byte word of a record holds
+ * its sequence number, and sequence numbers start at `seq`.
+ */
+static int produce_n(int prog_fd, __u64 seq, __u32 count, __u32 size)
+{
+ struct produce_args args = { .seq = seq, .count = count, .size = size };
+
+ return produce(prog_fd, &args);
+}
+
+/* Check that every 8-byte word of a record holds `seq`. */
+static bool record_ok(const void *data, __u32 len, __u64 seq)
+{
+ const __u64 *w = data;
+ __u32 i;
+
+ if (len % 8)
+ return false;
+ for (i = 0; i < len / 8; i++) {
+ if (w[i] != seq)
+ return false;
+ }
+ return true;
+}
+
+/* ASSERT_OK_PTR() passes for NULL when errno is 0, and an empty ring doesn't set errno */
+static const struct ring_rec *next_rec(struct ring *r, const char *name)
+{
+ const struct ring_rec *rec = ring__next(r);
+
+ ASSERT_TRUE(rec != NULL, name);
+ return rec;
+}
+
+static int count_cb(void *ctx, void *data, size_t len)
+{
+ (*(int *)ctx)++;
+ return 0;
+}
+
+static struct test_ringbuf_iter *open_load(size_t normal_sz, size_t overwrite_sz)
+{
+ struct test_ringbuf_iter *skel;
+ int err;
+
+ skel = test_ringbuf_iter__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open"))
+ return NULL;
+ bpf_map__set_max_entries(skel->maps.ringbuf, normal_sz);
+ bpf_map__set_max_entries(skel->maps.ringbuf_ow, overwrite_sz);
+ err = test_ringbuf_iter__load(skel);
+ if (!ASSERT_OK(err, "skel_load")) {
+ test_ringbuf_iter__destroy(skel);
+ return NULL;
+ }
+ return skel;
+}
+
+static void subtest_basic(void)
+{
+ struct test_ringbuf_iter *skel;
+ const struct ring_rec *rec;
+ struct ring_rec first = {};
+ struct ring_buffer *rb;
+ unsigned long cons;
+ struct ring *r;
+ int prog_fd, i;
+
+ skel = open_load(4 * page_size, page_size);
+ if (!skel)
+ return;
+ prog_fd = bpf_program__fd(skel->progs.produce_normal);
+
+ rb = ring_buffer__new(bpf_map__fd(skel->maps.ringbuf), NULL, NULL, NULL);
+ if (!ASSERT_OK_PTR(rb, "ring_buffer__new"))
+ goto out;
+ r = ring_buffer__ring(rb, 0);
+
+ /* Nothing to consume in an empty ring, and that is not an error. */
+ errno = 0;
+ ASSERT_NULL(ring__next(r), "next_empty");
+ ASSERT_EQ(errno, 0, "next_empty_errno");
+ ASSERT_EQ(ring__release(r), 0, "release_empty");
+
+ /* Records of different sizes, including empty ones. */
+ if (produce_n(prog_fd, 0, 10, 8) || produce_n(prog_fd, 10, 10, 0) ||
+ produce_n(prog_fd, 20, 10, 120) || produce_n(prog_fd, 30, 10, 256))
+ goto out_rb;
+
+ cons = ring__consumer_pos(r);
+ for (i = 0; i < 40; i++) {
+ rec = next_rec(r, "next");
+ if (!rec)
+ goto out_rb;
+ ASSERT_EQ(rec->len, i < 10 ? 8 : i < 20 ? 0 : i < 30 ? 120 : 256, "rec_len");
+ ASSERT_TRUE(record_ok(rec->data, rec->len, i), "rec_data");
+ if (i == 0)
+ first = *rec;
+ }
+ ASSERT_NULL(ring__next(r), "next_drained");
+ /* Records are not consumed until they are released, and stay valid until then. */
+ ASSERT_EQ(ring__consumer_pos(r), cons, "cons_unchanged");
+ ASSERT_EQ(first.pos, cons, "first_rec_pos");
+ ASSERT_TRUE(record_ok(first.data, first.len, 0), "first_rec_data");
+ /* Records of a regular ring are never overwritten. */
+ ASSERT_FALSE(ring__invalidated(r), "invalidated");
+
+ ASSERT_EQ(ring__release(r), 0, "release");
+ ASSERT_EQ(ring__consumer_pos(r), ring__producer_pos(r), "cons_caught_up");
+
+ /* ring__release() consumes only the returned records, and tells if there are more. */
+ if (produce_n(prog_fd, 40, 2, 16))
+ goto out_rb;
+ rec = next_rec(r, "next_partial");
+ if (!rec)
+ goto out_rb;
+ ASSERT_EQ(ring__release(r), 1, "release_partial");
+ ASSERT_EQ(ring__consumer_pos(r), rec->pos + BPF_RINGBUF_HDR_SZ + 16, "cons_partial");
+ rec = next_rec(r, "next_rest");
+ if (rec)
+ ASSERT_TRUE(record_ok(rec->data, rec->len, 41), "rest_data");
+ ASSERT_NULL(ring__next(r), "next_rest_end");
+ ASSERT_EQ(ring__release(r), 0, "release_rest");
+
+out_rb:
+ ring_buffer__free(rb);
+out:
+ test_ringbuf_iter__destroy(skel);
+}
+
+static void subtest_rewind_discard(void)
+{
+ struct produce_args args = { .seq = 0, .count = 20, .size = 32, .discard_mod = 4 };
+ struct test_ringbuf_iter *skel;
+ const struct ring_rec *rec;
+ struct ring_buffer *rb;
+ struct ring *r;
+ int prog_fd, i;
+ __u64 seq;
+
+ skel = open_load(4 * page_size, page_size);
+ if (!skel)
+ return;
+ prog_fd = bpf_program__fd(skel->progs.produce_normal);
+
+ rb = ring_buffer__new(bpf_map__fd(skel->maps.ringbuf), NULL, NULL, NULL);
+ if (!ASSERT_OK_PTR(rb, "ring_buffer__new"))
+ goto out;
+ r = ring_buffer__ring(rb, 0);
+
+ /* Every 4th record is discarded: seq 0, 4, 8, 12, 16 never show up. */
+ if (produce(prog_fd, &args))
+ goto out_rb;
+
+ /* Rewind after three records, and get all records from the first one again. */
+ for (i = 0; i < 3; i++)
+ ASSERT_TRUE(ring__next(r) != NULL, "next_before_rewind");
+ ring__rewind(r);
+ for (seq = 1; seq < 20; seq++) {
+ if (seq % 4 == 0)
+ continue;
+ rec = next_rec(r, "next");
+ if (!rec)
+ goto out_rb;
+ ASSERT_TRUE(record_ok(rec->data, rec->len, seq), "rec_data");
+ }
+ ASSERT_NULL(ring__next(r), "next_end");
+ ASSERT_EQ(ring__release(r), 0, "release");
+ ASSERT_EQ(ring__consumer_pos(r), ring__producer_pos(r), "cons_caught_up");
+
+ /* A discarded record at the end is skipped and consumed as well. */
+ args.seq = 20;
+ args.count = 1;
+ args.discard_mod = 1;
+ if (produce(prog_fd, &args))
+ goto out_rb;
+ ASSERT_NULL(ring__next(r), "next_only_discarded");
+ ASSERT_EQ(ring__release(r), 0, "release_discarded");
+ ASSERT_EQ(ring__consumer_pos(r), ring__producer_pos(r), "cons_past_discarded");
+
+out_rb:
+ ring_buffer__free(rb);
+out:
+ test_ringbuf_iter__destroy(skel);
+}
+
+/* Wait with ring_buffer__wait() and consume with ring__next(). */
+static void subtest_manager(void)
+{
+ struct test_ringbuf_iter *skel;
+ struct ring_buffer *rb;
+ struct ring *r_cb, *r_ow;
+ int normal_fd, ow_fd, cb_cnt = 0;
+
+ skel = open_load(page_size, page_size);
+ if (!skel)
+ return;
+ normal_fd = bpf_program__fd(skel->progs.produce_normal);
+ ow_fd = bpf_program__fd(skel->progs.produce_overwrite);
+
+ /* The regular ring has a callback, the overwritable one doesn't. */
+ rb = ring_buffer__new(bpf_map__fd(skel->maps.ringbuf), count_cb, &cb_cnt, NULL);
+ if (!ASSERT_OK_PTR(rb, "ring_buffer__new"))
+ goto out;
+ if (!ASSERT_OK(ring_buffer__add(rb, bpf_map__fd(skel->maps.ringbuf_ow), NULL, NULL),
+ "ring_buffer__add"))
+ goto out_rb;
+ r_cb = ring_buffer__ring(rb, 0);
+ r_ow = ring_buffer__ring(rb, 1);
+
+ /* A ring with a callback can't be used with ring__next(). */
+ errno = 0;
+ ASSERT_NULL(ring__next(r_cb), "next_cb_ring");
+ ASSERT_EQ(errno, EINVAL, "next_cb_ring_errno");
+ ASSERT_EQ(ring__release(r_cb), -EINVAL, "release_cb_ring");
+
+ /* ring__free() only warns for a ring that is owned by a manager; r_ow is used below. */
+ ring__free(r_ow);
+
+ /* ring_buffer__wait() returns the number of rings with data and consumes nothing. */
+ ASSERT_EQ(ring_buffer__wait(rb, 0), 0, "wait_empty");
+ if (produce_n(ow_fd, 0, 2, 16))
+ goto out_rb;
+ ASSERT_EQ(ring_buffer__wait(rb, 1000), 1, "wait_one");
+ if (produce_n(normal_fd, 0, 3, 16))
+ goto out_rb;
+ ASSERT_EQ(ring_buffer__wait(rb, 1000), 2, "wait_both");
+ ASSERT_EQ(cb_cnt, 0, "wait_cb_not_called");
+
+ /* The data is consumed afterwards, through the callback or with ring__next(). */
+ ASSERT_EQ(ring__consume(r_cb), 3, "consume");
+ ASSERT_EQ(cb_cnt, 3, "consume_cb");
+ ASSERT_TRUE(ring__next(r_ow) != NULL, "next1");
+ ASSERT_TRUE(ring__next(r_ow) != NULL, "next2");
+ ASSERT_NULL(ring__next(r_ow), "next_end");
+ /* A ring has data until its records are released. */
+ ASSERT_EQ(ring_buffer__wait(rb, 0), 1, "wait_unreleased");
+ ASSERT_EQ(ring__release(r_ow), 0, "release");
+ ASSERT_EQ(ring_buffer__wait(rb, 0), 0, "wait_released");
+
+out_rb:
+ ring_buffer__free(rb);
+out:
+ test_ringbuf_iter__destroy(skel);
+}
+
+static void subtest_standalone(void)
+{
+ struct epoll_event ev = { .events = EPOLLIN | EPOLLET };
+ struct test_ringbuf_iter *skel;
+ const struct ring_rec *rec;
+ int prog_fd, epfd, arr_fd;
+ struct ring *r, *bad;
+ __u64 seq = 0;
+
+ skel = open_load(page_size, page_size);
+ if (!skel)
+ return;
+ prog_fd = bpf_program__fd(skel->progs.produce_normal);
+
+ /* ring__new() only takes ring buffer maps. */
+ arr_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, 4, 4, 1, NULL);
+ if (!ASSERT_OK_FD(arr_fd, "array_create"))
+ goto out;
+ bad = ring__new(arr_fd, NULL);
+ ASSERT_ERR_PTR(bad, "ring__new_array");
+ ASSERT_EQ(errno, EINVAL, "ring__new_array_errno");
+ close(arr_fd);
+
+ r = ring__new(bpf_map__fd(skel->maps.ringbuf), NULL);
+ if (!ASSERT_OK_PTR(r, "ring__new"))
+ goto out;
+
+ /* Wait with edge-triggered epoll on the map fd. */
+ epfd = epoll_create1(EPOLL_CLOEXEC);
+ if (!ASSERT_OK_FD(epfd, "epoll_create1"))
+ goto out_ring;
+ if (!ASSERT_OK(epoll_ctl(epfd, EPOLL_CTL_ADD, ring__map_fd(r), &ev), "epoll_ctl"))
+ goto out_epoll;
+
+ if (produce_n(prog_fd, 0, 5, 16))
+ goto out_epoll;
+ ASSERT_EQ(epoll_wait(epfd, &ev, 1, 1000), 1, "epoll_ready");
+ do {
+ while ((rec = ring__next(r)))
+ ASSERT_TRUE(record_ok(rec->data, rec->len, seq++), "rec_data");
+ } while (ring__release(r) > 0);
+ ASSERT_EQ(ring__consumer_pos(r), ring__producer_pos(r), "cons_caught_up");
+
+ /* The records were released, so the next record wakes us up again. */
+ if (produce_n(prog_fd, 5, 1, 16))
+ goto out_epoll;
+ ASSERT_EQ(epoll_wait(epfd, &ev, 1, 1000), 1, "epoll_ready_again");
+
+out_epoll:
+ close(epfd);
+out_ring:
+ ring__free(r);
+out:
+ test_ringbuf_iter__destroy(skel);
+}
+
+/* Only the most recent records are left in an overwritable ring. */
+static void subtest_overwrite_basic(void)
+{
+ __u32 size = 120, rec_sz = size + BPF_RINGBUF_HDR_SZ, per_ring = page_size / rec_sz;
+ struct test_ringbuf_iter *skel;
+ unsigned long next_pos, lost;
+ const struct ring_rec *rec;
+ struct ring *r;
+ int prog_fd, n = 0;
+ __u64 seq = 0;
+
+ skel = open_load(page_size, page_size);
+ if (!skel)
+ return;
+ prog_fd = bpf_program__fd(skel->progs.produce_overwrite);
+ r = ring__new(bpf_map__fd(skel->maps.ringbuf_ow), NULL);
+ if (!ASSERT_OK_PTR(r, "ring__new"))
+ goto out;
+
+ /* Fill the ring 3 times over. */
+ if (produce_n(prog_fd, 0, 3 * per_ring, size))
+ goto out_ring;
+ ASSERT_LE(ring__avail_data_size(r), page_size, "avail_data_size");
+
+ next_pos = ring__consumer_pos(r);
+ while ((rec = ring__next(r))) {
+ /*
+ * The API doesn't report how many bytes were overwritten before a
+ * record. It is the distance from the end of the previous record.
+ */
+ lost = rec->pos - next_pos;
+ next_pos = rec->pos + rec_sz;
+ /* All records before the first one that is left were overwritten. */
+ if (n++ == 0)
+ seq = lost / rec_sz;
+ else
+ ASSERT_EQ(lost, 0, "lost_bytes");
+ ASSERT_TRUE(record_ok(rec->data, rec->len, seq++), "rec_data");
+ }
+ /* The ring holds at most per_ring records, and the last one is the newest. */
+ ASSERT_GT(n, 0, "records");
+ ASSERT_LE(n, per_ring, "records_in_ring");
+ ASSERT_EQ(seq, 3 * per_ring, "newest_record");
+ ASSERT_FALSE(ring__invalidated(r), "invalidated");
+ ASSERT_EQ(ring__release(r), 0, "release");
+ ASSERT_EQ(ring__consumer_pos(r), ring__producer_pos(r), "cons_caught_up");
+
+out_ring:
+ ring__free(r);
+out:
+ test_ringbuf_iter__destroy(skel);
+}
+
+/*
+ * ring__invalidated() covers all records returned since the last release or
+ * rewind. Records take 64 bytes. The kernel keeps less than a ring size of
+ * records, so the ring is full with per_ring of them, and every new record
+ * overwrites the oldest one.
+ */
+static void subtest_overwrite_batch(void)
+{
+ __u32 size = 56, rec_sz = size + BPF_RINGBUF_HDR_SZ, per_ring = page_size / rec_sz - 1;
+ struct test_ringbuf_iter *skel;
+ const struct ring_rec *rec;
+ __u64 seq, next_seq;
+ struct ring *r;
+ int prog_fd, i;
+
+ skel = open_load(page_size, page_size);
+ if (!skel)
+ return;
+ prog_fd = bpf_program__fd(skel->progs.produce_overwrite);
+ r = ring__new(bpf_map__fd(skel->maps.ringbuf_ow), NULL);
+ if (!ASSERT_OK_PTR(r, "ring__new"))
+ goto out;
+
+ if (produce_n(prog_fd, 0, per_ring, size))
+ goto out_ring;
+ seq = per_ring;
+
+ /* No records were returned yet. */
+ ASSERT_FALSE(ring__invalidated(r), "invalidated_nothing");
+
+ for (i = 0; i < 4; i++)
+ ASSERT_TRUE(ring__next(r) != NULL, "batch1_next");
+ ASSERT_FALSE(ring__invalidated(r), "batch1_invalidated");
+
+ /* Records 0 and 1 get overwritten. Getting more records doesn't change the result. */
+ if (produce_n(prog_fd, seq, 2, size))
+ goto out_ring;
+ seq += 2;
+ ASSERT_TRUE(ring__invalidated(r), "batch1_overwritten");
+ for (i = 4; i < 8; i++)
+ ASSERT_TRUE(ring__next(r) != NULL, "batch1_next_more");
+ ASSERT_TRUE(ring__invalidated(r), "batch1_still_overwritten");
+
+ /* Records returned before a release are not checked anymore. */
+ ASSERT_EQ(ring__release(r), 1, "release");
+ ASSERT_FALSE(ring__invalidated(r), "invalidated_after_release");
+ for (i = 8; i < 10; i++)
+ ASSERT_TRUE(ring__next(r) != NULL, "batch2_next");
+ ASSERT_FALSE(ring__invalidated(r), "batch2_invalidated");
+
+ /* Records 2 to 10 get overwritten, which includes the two returned last. */
+ if (produce_n(prog_fd, seq, 9, size))
+ goto out_ring;
+ seq += 9;
+ ASSERT_TRUE(ring__invalidated(r), "batch2_overwritten");
+
+ /* After a rewind ring__next() continues from the oldest record that is left. */
+ ring__rewind(r);
+ ASSERT_FALSE(ring__invalidated(r), "invalidated_after_rewind");
+ next_seq = 11;
+ while ((rec = ring__next(r))) {
+ ASSERT_EQ(rec->pos, next_seq * rec_sz, "batch3_pos");
+ ASSERT_TRUE(record_ok(rec->data, rec->len, next_seq), "batch3_data");
+ next_seq++;
+ }
+ ASSERT_EQ(next_seq, seq, "batch3_all_records");
+ ASSERT_FALSE(ring__invalidated(r), "batch3_invalidated");
+ ASSERT_EQ(ring__release(r), 0, "release_end");
+
+out_ring:
+ ring__free(r);
+out:
+ test_ringbuf_iter__destroy(skel);
+}
+
+struct race_ctx {
+ int prog_fd;
+ volatile bool stop;
+};
+
+static void *race_producer(void *arg)
+{
+ static const __u32 sizes[] = { 8, 24, 64, 120, 256, 16 };
+ struct race_ctx *ctx = arg;
+ struct produce_args args = { .count = 16, .flags = BPF_RB_NO_WAKEUP };
+ LIBBPF_OPTS(bpf_test_run_opts, opts,
+ .ctx_in = &args,
+ .ctx_size_in = sizeof(args),
+ );
+ int i = 0;
+
+ while (!ctx->stop) {
+ args.size = sizes[i++ % ARRAY_SIZE(sizes)];
+ if (bpf_prog_test_run_opts(ctx->prog_fd, &opts))
+ break;
+ }
+ return NULL;
+}
+
+#define RACE_BATCH 8
+#define RACE_MAX_LEN 256
+
+/*
+ * Consume an overwritable ring while a thread keeps producing into it. Records
+ * that were not overwritten must have valid data and increasing sequence
+ * numbers. The length of a record must be valid even if it was overwritten.
+ *
+ * The checks run for every record, so they don't use ASSERT_*(), which logs
+ * every pass.
+ */
+static void subtest_overwrite_race(void)
+{
+ __u64 copy[RACE_BATCH][RACE_MAX_LEN / 8];
+ __u64 end, pause, iter, seq, next_seq = 0;
+ struct test_ringbuf_iter *skel;
+ const struct ring_rec *rec;
+ struct race_ctx ctx = {};
+ __u32 len[RACE_BATCH];
+ pthread_t thread;
+ struct ring *r;
+ int i, n;
+
+ skel = open_load(page_size, page_size);
+ if (!skel)
+ return;
+ ctx.prog_fd = bpf_program__fd(skel->progs.produce_overwrite);
+ r = ring__new(bpf_map__fd(skel->maps.ringbuf_ow), NULL);
+ if (!ASSERT_OK_PTR(r, "ring__new"))
+ goto out;
+
+ if (!ASSERT_OK(pthread_create(&thread, NULL, race_producer, &ctx), "pthread_create"))
+ goto out_ring;
+
+ end = get_time_ns() + 1500000000ULL;
+ for (iter = 0; get_time_ns() < end; iter++) {
+ /* Copy a batch of records, then check that none of them was overwritten. */
+ for (n = 0; n < RACE_BATCH && (rec = ring__next(r)); n++) {
+ if (rec->len < 8 || rec->len > RACE_MAX_LEN || rec->len % 8) {
+ PRINT_FAIL("record at %lu has length %u\n", rec->pos, rec->len);
+ goto out_thread;
+ }
+ memcpy(copy[n], rec->data, rec->len);
+ len[n] = rec->len;
+ }
+ /* Sometimes wait before the check, so that the producer laps us. */
+ if (iter % 32 == 0) {
+ pause = get_time_ns() + 50000;
+ while (get_time_ns() < pause)
+ ;
+ }
+ if (ring__invalidated(r))
+ n = 0;
+ for (i = 0; i < n; i++) {
+ seq = copy[i][0];
+ if (!record_ok(copy[i], len[i], seq) || seq < next_seq) {
+ PRINT_FAIL("bad record %llu, expected %llu or more\n",
+ seq, next_seq);
+ goto out_thread;
+ }
+ next_seq = seq + 1;
+ }
+ ring__release(r);
+ }
+
+out_thread:
+ ctx.stop = true;
+ pthread_join(thread, NULL);
+ ASSERT_GT(next_seq, 0, "valid_records");
+
+out_ring:
+ ring__free(r);
+out:
+ test_ringbuf_iter__destroy(skel);
+}
+
+void test_ringbuf_iter(void)
+{
+ page_size = getpagesize();
+
+ if (test__start_subtest("basic"))
+ subtest_basic();
+ if (test__start_subtest("rewind_discard"))
+ subtest_rewind_discard();
+ if (test__start_subtest("manager"))
+ subtest_manager();
+ if (test__start_subtest("standalone"))
+ subtest_standalone();
+ if (test__start_subtest("overwrite_basic"))
+ subtest_overwrite_basic();
+ if (test__start_subtest("overwrite_batch"))
+ subtest_overwrite_batch();
+ if (test__start_subtest("overwrite_race"))
+ subtest_overwrite_race();
+}
diff --git a/tools/testing/selftests/bpf/progs/test_ringbuf_iter.c b/tools/testing/selftests/bpf/progs/test_ringbuf_iter.c
new file mode 100644
index 000000000000..10c146ec6a70
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/test_ringbuf_iter.c
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+
+char _license[] SEC("license") = "GPL";
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+} ringbuf SEC(".maps");
+
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(map_flags, BPF_F_RB_OVERWRITE);
+} ringbuf_ow SEC(".maps");
+
+/*
+ * Context of the producer programs, which are run with
+ * bpf_prog_test_run_opts(). Every 8-byte word of a record holds its sequence
+ * number, so that the consumer can check all of its data.
+ */
+struct produce_args {
+ __u64 seq; /* in: first sequence number, out: next one */
+ __u32 count; /* records to produce */
+ __u32 size; /* record size in bytes */
+ __u32 discard_mod; /* discard records whose seq is a multiple of this, 0: none */
+ __u32 flags; /* submit/discard flags, e.g. BPF_RB_NO_WAKEUP */
+ __u32 produced; /* out: records produced */
+};
+
+static __always_inline int produce(void *map, struct produce_args *args)
+{
+ __u32 size = args->size, words = size / 8;
+ __u64 seq = args->seq;
+ struct bpf_dynptr ptr;
+ int i, j;
+
+ bpf_for(i, 0, args->count) {
+ if (bpf_ringbuf_reserve_dynptr(map, size, 0, &ptr)) {
+ bpf_ringbuf_discard_dynptr(&ptr, 0);
+ continue;
+ }
+ bpf_for(j, 0, words)
+ bpf_dynptr_write(&ptr, j * 8, &seq, 8, 0);
+ if (args->discard_mod && seq % args->discard_mod == 0)
+ bpf_ringbuf_discard_dynptr(&ptr, args->flags);
+ else
+ bpf_ringbuf_submit_dynptr(&ptr, args->flags);
+ args->produced++;
+ seq++;
+ }
+ args->seq = seq;
+ return 0;
+}
+
+SEC("syscall")
+int produce_normal(struct produce_args *args)
+{
+ return produce(&ringbuf, args);
+}
+
+SEC("syscall")
+int produce_overwrite(struct produce_args *args)
+{
+ return produce(&ringbuf_ow, args);
+}
--
2.53.1-Meta
^ permalink raw reply related [flat|nested] 15+ messages in thread