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 --- 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