Re: [PATCH 0/6] tracing/ring-buffer: Fix wakeup of ring buffer waiters

From: Linus Torvalds
Date: Fri Mar 08 2024 - 15:39:40 EST


On Fri, 8 Mar 2024 at 10:38, Steven Rostedt <rostedt@xxxxxxxxxxx> wrote:
>
> A patch was sent to "fix" the wait_index variable that is used to help with
> waking of waiters on the ring buffer. The patch was rejected, but I started
> looking at associated code. Discussing it on IRC with Mathieu Desnoyers
> we discovered a design flaw.

Honestly, all of this seems excessively complicated.

And your new locking shouldn't be necessary if you just do things much
more simply.

Here's what I *think* you should do:

struct xyz {
...
atomic_t seq;
struct wait_queue_head seq_wait;
...
};

with the consumer doing something very simple like this:

int seq = atomic_read_acquire(&my->seq);
for (;;) {
.. consume outstanding events ..
seq = wait_for_seq_change(seq, my);
}

and the producer being similarly trivial, just having a
"add_seq_event()" at the end:

... add whatever event ..
add_seq_event(my);

And the helper functions for this are really darn simple:

static inline int wait_for_seq_change(int old, struct xyz *my)
{
int new;
wait_event(my->seq_wait,
(new = atomic_read_acquire(&my->seq)) != old);
return new;
}

static inline void add_seq_event(struct xyz *my)
{
atomic_fetch_inc_release(&my->seq);
wake_up(&my->seq_wait);
}

Note how you don't need any new locks, and note how "wait_event()"
will do all the required optimistic stuff for you (ie it will check
that "has seq changed" before even bothering to add itself to the wait
queue etc).

So the above is not only short and sweet, it generates fairly good
code too, and doesn't it look really simple and fairly understandable?

And - AS ALWAYS - the above isn't actually tested in any way, shape or form.

Linus