[PATCH bpf-next v3 1/8] bpf: user_ringbuf: Handle position wrap
From: Tamir Duberstein
Date: Fri Nov 20 2026 - 15:33:45 EST
User ring buffer positions are unsigned long counters, but
__bpf_user_ringbuf_peek() widens them to u64 before comparing and
subtracting them. On 32-bit systems, producer_pos wrapping below
consumer_pos therefore appears to move backwards and permanently stalls
the ring.
Keep the positions word-sized and derive the available data with
word-sized subtraction so the arithmetic wraps with the counters. Treat
a zero span as empty and reuse the distance for the advertised-window
check. Validate sample sizes before rejecting a window larger than the
ring, preserving the documented -E2BIG result for oversized samples.
Fixes: 205715673844 ("bpf: Add bpf_user_ringbuf_drain() helper")
Reported-by: Sashiko <sashiko-bot@xxxxxxxxxx>
Closes: https://lore.kernel.org/bpf/20260614020552.022A11F000E9@xxxxxxxxxxxxxxx/
Signed-off-by: Tamir Duberstein <tamird@xxxxxxxxxx>
---
kernel/bpf/ringbuf.c | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
diff --git a/kernel/bpf/ringbuf.c b/kernel/bpf/ringbuf.c
index 447863ece26a..5494c0977153 100644
--- a/kernel/bpf/ringbuf.c
+++ b/kernel/bpf/ringbuf.c
@@ -747,9 +747,9 @@ const struct bpf_func_proto bpf_ringbuf_discard_dynptr_proto = {
static int __bpf_user_ringbuf_peek(struct bpf_ringbuf *rb, void **sample, u32 *size)
{
+ unsigned long avail, cons_pos, prod_pos;
int err;
u32 hdr_len, sample_len, total_len, flags, *hdr;
- u64 cons_pos, prod_pos;
/* Synchronizes with smp_store_release() in user-space producer. */
prod_pos = smp_load_acquire(&rb->producer_pos);
@@ -758,7 +758,8 @@ static int __bpf_user_ringbuf_peek(struct bpf_ringbuf *rb, void **sample, u32 *s
/* Synchronizes with smp_store_release() in __bpf_user_ringbuf_sample_release() */
cons_pos = smp_load_acquire(&rb->consumer_pos);
- if (cons_pos >= prod_pos)
+ avail = prod_pos - cons_pos;
+ if (!avail)
return -ENODATA;
hdr = (u32 *)((uintptr_t)rb->data + (uintptr_t)(cons_pos & rb->mask));
@@ -769,7 +770,7 @@ static int __bpf_user_ringbuf_peek(struct bpf_ringbuf *rb, void **sample, u32 *s
total_len = round_up(sample_len + BPF_RINGBUF_HDR_SZ, 8);
/* The sample must fit within the region advertised by the producer position. */
- if (total_len > prod_pos - cons_pos)
+ if (total_len > avail)
return -EINVAL;
/* The sample must fit within the data region of the ring buffer. */
@@ -781,6 +782,10 @@ static int __bpf_user_ringbuf_peek(struct bpf_ringbuf *rb, void **sample, u32 *s
if (err)
return -E2BIG;
+ /* The advertised window must also fit within the ring buffer. */
+ if (avail > ringbuf_total_data_sz(rb))
+ return -EINVAL;
+
if (flags & BPF_RINGBUF_DISCARD_BIT) {
/* If the discard bit is set, the sample should be skipped.
*
--
2.56.1