Skip to content

Commit 13e8125

Browse files
Andrea Righianakryiko
authored andcommitted
libbpf: ringbuf: Allow to consume up to a certain amount of items
In some cases, instead of always consuming all items from ring buffers in a greedy way, we may want to consume up to a certain amount of items, for example when we need to copy items from the BPF ring buffer to a limited user buffer. This change allows to set an upper limit to the amount of items consumed from one or more ring buffers. Signed-off-by: Andrea Righi <[email protected]> Signed-off-by: Andrii Nakryiko <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
1 parent 5bd2ed6 commit 13e8125

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

tools/lib/bpf/ringbuf.c

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ static inline int roundup_len(__u32 len)
231231
return (len + 7) / 8 * 8;
232232
}
233233

234-
static int64_t ringbuf_process_ring(struct ring *r)
234+
static int64_t ringbuf_process_ring(struct ring *r, size_t n)
235235
{
236236
int *len_ptr, len, err;
237237
/* 64-bit to avoid overflow in case of extreme application behavior */
@@ -268,6 +268,9 @@ static int64_t ringbuf_process_ring(struct ring *r)
268268
}
269269

270270
smp_store_release(r->consumer_pos, cons_pos);
271+
272+
if (cnt >= n)
273+
goto done;
271274
}
272275
} while (got_new_data);
273276
done:
@@ -287,13 +290,15 @@ int ring_buffer__consume(struct ring_buffer *rb)
287290
for (i = 0; i < rb->ring_cnt; i++) {
288291
struct ring *ring = rb->rings[i];
289292

290-
err = ringbuf_process_ring(ring);
293+
err = ringbuf_process_ring(ring, INT_MAX);
291294
if (err < 0)
292295
return libbpf_err(err);
293296
res += err;
297+
if (res > INT_MAX) {
298+
res = INT_MAX;
299+
break;
300+
}
294301
}
295-
if (res > INT_MAX)
296-
return INT_MAX;
297302
return res;
298303
}
299304

@@ -314,13 +319,13 @@ int ring_buffer__poll(struct ring_buffer *rb, int timeout_ms)
314319
__u32 ring_id = rb->events[i].data.fd;
315320
struct ring *ring = rb->rings[ring_id];
316321

317-
err = ringbuf_process_ring(ring);
322+
err = ringbuf_process_ring(ring, INT_MAX);
318323
if (err < 0)
319324
return libbpf_err(err);
320325
res += err;
321326
}
322327
if (res > INT_MAX)
323-
return INT_MAX;
328+
res = INT_MAX;
324329
return res;
325330
}
326331

@@ -375,7 +380,7 @@ int ring__consume(struct ring *r)
375380
{
376381
int64_t res;
377382

378-
res = ringbuf_process_ring(r);
383+
res = ringbuf_process_ring(r, INT_MAX);
379384
if (res < 0)
380385
return libbpf_err(res);
381386

0 commit comments

Comments
 (0)