Linux Trace Kernel
 help / color / mirror / Atom feed
* [PATCH] tracing: Fix simple_ring_buffer writer moving onto the reader page
@ 2026-12-04 16:46 Andrea Parri
  2026-12-04 17:56 ` Vincent Donnefort
  0 siblings, 1 reply; 3+ messages in thread
From: Andrea Parri @ 2026-12-04 16:46 UTC (permalink / raw)
  To: Steven Rostedt, Vincent Donnefort, Masami Hiramatsu
  Cc: Mathieu Desnoyers, linux-kernel, linux-trace-kernel, kvmarm

simple_rb_move_tail() loads the page after the tail and, if it is the
head, moves the HEAD flag past it with a cmpxchg() on tail->link.next.
simple_ring_buffer_swap_reader_page() can swap the head out in between,
so the cmpxchg() fails and the writer moves onto the page it loaded,
now the reader page:

  CPU 1 (writer)                    CPU 0 (reader)
  simple_rb_move_tail()             simple_ring_buffer_swap_reader_page()
    new_tail = B  (A->next == B|HEAD)
                                      cmpxchg(A->next, B|HEAD, R)
                                      reader_page = B
    cmpxchg(A->next) fails
    simple_bpage_reset(B)
    tail_page = B

The writer then overwrites the page the reader is consuming.  Once that
page is full, the writer moves on to the new head through a link that
does not carry the HEAD flag, and overwrites unread pages without adding
them to overrun.

The reader gets no "[LOST n EVENTS]" notice for these events, and the
unread count, entries - (overrun + read), no longer drops to zero.  Once
the buffer is drained, ring_buffer_wait() returns without sleeping and
no event is found, so a trace_pipe reader spins in trace_pipe_read() and
cannot be killed.  SysRq-L with the remote_test module:

  NMI backtrace for cpu 0
  CPU: 0 UID: 0 PID: 87 Comm: srbrace Not tainted 7.4.0-rc5 #1 PREEMPT(lazy)
  RIP: 0010:rb_buffer_peek+0x37/0x170
  Call Trace:
   <TASK>
   ring_buffer_peek+0x84/0x160
   trace_remote_iter_read_event+0x14d/0x180
   trace_pipe_read+0xb1/0xf0
   vfs_read+0xb4/0x370
   ksys_read+0x68/0xe0
   do_syscall_64+0xdf/0x4c0
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The arm64 pKVM hypervisor runs the same writer at EL2 with
NVHE_EL2_TRACING.  Its tracing_reserve_entry() does not take the
trace_buffer lock that __tracing_swap_reader() holds, so hypervisor
tracing should hit the same race.  This was only tested with remote_test.

Read tail->link.next again when the cmpxchg() fails.  After a reader
swap it points to the previous reader page, which the reader has
finished with.  In the main ring buffer, rb_head_page_set() reports
this case as RB_PAGE_MOVED, and rb_move_tail() makes the writer retry
the reservation.

This should be safe because only simple_ring_buffer_swap_reader_page()
changes tail->link.next under the writer, and only once.  After the swap
the head follows the previous reader page, and once the tail page itself
is swapped out, further swaps return early until the writer leaves it.

When the reload observes the link published by the reader's successful,
fully ordered try_cmpxchg(), the address dependency from READ_ONCE() to
the page reset and the writes for the current reservation orders them
after the reader's final accesses to that page.

Tested in a 4-vCPU x86-64 KVM guest, writing consecutive ids to
remote_test on CPU 1 and reading per_cpu/cpu1/trace_pipe on CPU 0.
Unpatched, three 60 s runs report 11, 7 and 13 gaps without a LOST
notice and leave the reader stuck.  Patched, no run does.

The bug was found with the help of an LLM, which was also used to write
the fix, the changelog and the tests.

Fixes: 34e5b958bdad ("tracing: Introduce simple_ring_buffer")
Cc: stable@vger.kernel.org # 7.1.x: 2a6d7231c79e: ring-buffer: Skip remote reader page swap when on tail
Cc: stable@vger.kernel.org # 7.1.x
Signed-off-by: Andrea Parri <parri.andrea@gmail.com>
---
The herd7 test below (tools/memory-model, linux-kernel.cfg) models the
READ_ONCE() reload and gives "Never".  With a plain reload instead,
herd7 gives "Sometimes" and flags a data race.

C simple-rb-move-tail-reload-once

(*
 * Result: Never
 *
 * simple_rb_move_tail() losing its HEAD cmpxchg() to
 * simple_ring_buffer_swap_reader_page(), then reloading tail->link.next
 * with READ_ONCE(), as in the fix.
 *
 * an models tail->link.next, without the HEAD/HEAD_MOVING flag bits, and
 * initially points to the head page b.  P0 is the reader: its last read
 * of its reader page r is a plain read, then its cmpxchg() swaps b out
 * and links r after the tail.  P1 is the writer: its HEAD cmpxchg()
 * fails, it reloads an and stores into the page it finds, as
 * simple_bpage_reset() and the event writes do.  The exists clause is the
 * writer's store into r being visible to the reader's last read of r.
 *)

{
	an=b;
}

P0(int **an, int *b, int *r)
{
	int r0;
	int *r1;

	r0 = *r;
	r1 = cmpxchg(an, b, r);
}

P1(int **an, int *b, int *c)
{
	int *r2;
	int *p;

	r2 = cmpxchg(an, b, c);
	if (r2 != b) {
		p = READ_ONCE(*an);
		*p = 1;
	}
}

exists (0:r0=1 /\ 0:r1=b /\ 1:p=r)

Reproducer below, run as root on a kernel with CONFIG_TRACE_REMOTE_TEST=y
and at least two CPUs, as "srbrace [seconds [wcpu [rcpu]]]".  Without
this patch it prints "VIOLATION" with the first gaps and reports its
trace_pipe reader as stuck: once the buffer is drained, read() does not
return after a signal, and the thread keeps spinning after main()
returns.  With it, it prints "no violation" and exits.

// SPDX-License-Identifier: GPL-2.0
/*
 * Stress simple_rb_move_tail() against simple_ring_buffer_swap_reader_page()
 * through the remote_test trace remote (CONFIG_TRACE_REMOTE_TEST=y).
 *
 * The writer thread, pinned to WCPU, writes consecutive ids to write_event,
 * so every event lands in WCPU's simple_ring_buffer.  The reader thread,
 * pinned to RCPU, consumes per_cpu/cpuWCPU/trace_pipe.  The buffer is kept at
 * its minimum size so the writer keeps overwriting the head page.
 *
 * Lost events must be reported: a gap in the ids not preceded by a
 * "[LOST n EVENTS]" line, or an id going backwards, means the writer
 * overwrote pages without accounting for them.  A notice whose count
 * differs from the gap after it is counted as "miscounted", for
 * information only.
 *
 * Once the writer stops and the reader has drained the buffer, trace_pipe
 * must sleep in read(), where a signal interrupts it.  A reader that does
 * not return from read() after SIGUSR1 is spinning in the kernel, which
 * the overwrites cause even when the gaps hide behind a loss notice.
 *
 * Usage: srbrace [seconds [wcpu [rcpu]]]   (defaults: 60 1 0)
 * Exit status: 0 = violation seen, 2 = none, 1 = setup error, read()
 * error or no progress.
 */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define RDIR "/sys/kernel/tracing/remotes/test/"

static int wcpu = 1, rcpu = 0;
static atomic_int stop;
static unsigned long long written, failed;

/* Updated by the reader thread, read by main() while it may still run. */
static atomic_ullong events, lost_lines, lost_total;
static atomic_ullong gaps, backwards, garbled, miscounted;
static atomic_int read_err;

#define add(var, n)	atomic_fetch_add_explicit(&(var), (n), memory_order_relaxed)
#define get(var)	atomic_load_explicit(&(var), memory_order_relaxed)

static void pin(int cpu)
{
	cpu_set_t set;

	CPU_ZERO(&set);
	CPU_SET(cpu, &set);
	if (sched_setaffinity(0, sizeof(set), &set)) {
		perror("sched_setaffinity");
		exit(1);
	}
}

static void put(const char *file, const char *val)
{
	char path[256];
	int fd;

	snprintf(path, sizeof(path), RDIR "%s", file);
	fd = open(path, O_WRONLY | O_TRUNC);
	if (fd < 0 || write(fd, val, strlen(val)) < 0) {
		fprintf(stderr, "%s: %s\n", path, strerror(errno));
		exit(1);
	}
	close(fd);
}

static void *writer(void *arg)
{
	unsigned long long id = 1;
	char buf[32];
	int fd, len;

	pin(wcpu);
	fd = open(RDIR "write_event", O_WRONLY);
	if (fd < 0) {
		perror("write_event");
		exit(1);
	}

	while (!atomic_load_explicit(&stop, memory_order_relaxed)) {
		len = snprintf(buf, sizeof(buf), "%llu", id);
		if (write(fd, buf, len) == len) {
			id++;
			written++;
		} else {
			failed++;
		}
	}

	close(fd);
	return NULL;
}

static void report(const char *what, unsigned long long prev, const char *line)
{
	static int printed;

	if (printed++ < 10)
		printf("%s after id=%llu: %s\n", what, prev, line);
}

static void check_line(char *line)
{
	static unsigned long long prev, lost_n;
	static int lost_pending;
	unsigned long long id, n;
	char *p;

	if (sscanf(line, "CPU:%*d [LOST %llu EVENTS]", &n) == 1) {
		add(lost_lines, 1);
		add(lost_total, n);
		lost_pending = 1;
		lost_n += n;
		return;
	}

	p = strstr(line, " selftest id=");
	if (!p || sscanf(p, " selftest id=%llu", &id) != 1) {
		add(garbled, 1);
		report("garbled line", prev, line);
		return;
	}

	add(events, 1);
	if (prev && id <= prev) {
		add(backwards, 1);
		report("id went backwards", prev, line);
	} else if (prev && id != prev + 1 && !lost_pending) {
		add(gaps, 1);
		report("unreported gap", prev, line);
	} else if (prev && lost_pending && id - prev - 1 != lost_n) {
		add(miscounted, 1);
	}
	lost_pending = 0;
	lost_n = 0;
	prev = id;
}

static void *reader(void *arg)
{
	static char buf[1 << 16];
	char path[256], *nl, *start;
	size_t fill = 0;
	ssize_t n;
	int fd;

	pin(rcpu);
	snprintf(path, sizeof(path), RDIR "per_cpu/cpu%d/trace_pipe", wcpu);
	fd = open(path, O_RDONLY);
	if (fd < 0) {
		perror(path);
		exit(1);
	}

	for (;;) {
		n = read(fd, buf + fill, sizeof(buf) - 1 - fill);
		if (n < 0 && errno == EINTR)	/* SIGUSR1 from main() */
			break;
		if (n <= 0) {
			/* trace_pipe blocks rather than returning 0 */
			atomic_store(&read_err, n < 0 ? errno : ENODATA);
			break;
		}
		fill += n;
		buf[fill] = '\0';

		start = buf;
		while ((nl = strchr(start, '\n'))) {
			*nl = '\0';
			check_line(start);
			start = nl + 1;
		}
		fill -= start - buf;
		memmove(buf, start, fill);
	}

	return NULL;
}

static void on_sigusr1(int sig)
{
}

int main(int argc, char **argv)
{
	struct sigaction sa = { .sa_handler = on_sigusr1 };	/* no SA_RESTART */
	int secs = argc > 1 ? atoi(argv[1]) : 60;
	int err, i, stuck = 1;
	struct timespec ts;
	pthread_t w, r;

	if (argc > 2)
		wcpu = atoi(argv[2]);
	if (argc > 3)
		rcpu = atoi(argv[3]);

	put("tracing_on", "0");
	put("trace", "");
	put("buffer_size_kb", "7");
	put("events/enable", "0");
	put("events/test/selftest/enable", "1");
	put("tracing_on", "1");

	sigaction(SIGUSR1, &sa, NULL);
	setvbuf(stdout, NULL, _IOLBF, 0);
	err = pthread_create(&r, NULL, reader, NULL);
	if (!err)
		err = pthread_create(&w, NULL, writer, NULL);
	if (err) {
		fprintf(stderr, "pthread_create: %s\n", strerror(err));
		return 1;
	}

	sleep(secs);
	atomic_store(&stop, 1);
	pthread_join(w, NULL);
	/* Let the reader drain what is left; it blocks in trace_pipe after. */
	sleep(1);

	/* Repeat in case a signal lands while the reader is not in read(). */
	for (i = 0; i < 20 && stuck; i++) {
		pthread_kill(r, SIGUSR1);
		clock_gettime(CLOCK_REALTIME, &ts);
		ts.tv_nsec += 100000000;
		if (ts.tv_nsec >= 1000000000) {
			ts.tv_sec++;
			ts.tv_nsec -= 1000000000;
		}
		stuck = pthread_timedjoin_np(r, NULL, &ts) != 0;
	}

	printf("written=%llu failed=%llu events=%llu lost_lines=%llu lost=%llu gaps=%llu backwards=%llu garbled=%llu miscounted=%llu\n",
	       written, failed, get(events), get(lost_lines), get(lost_total),
	       get(gaps), get(backwards), get(garbled), get(miscounted));

	if (stuck)
		printf("reader stuck in trace_pipe read() after SIGUSR1\n");
	if (get(gaps) || get(backwards) || get(garbled) || stuck) {
		printf("VIOLATION\n");
		return 0;
	}
	if (atomic_load(&read_err)) {
		printf("reader: read: %s\n", strerror(atomic_load(&read_err)));
		return 1;
	}
	if (!written || !get(events)) {
		printf("no progress\n");
		return 1;
	}
	printf("no violation\n");
	return 2;
}

 kernel/trace/simple_ring_buffer.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/kernel/trace/simple_ring_buffer.c b/kernel/trace/simple_ring_buffer.c
index 2dddaef638dc6..f7ec0b9a2df92 100644
--- a/kernel/trace/simple_ring_buffer.c
+++ b/kernel/trace/simple_ring_buffer.c
@@ -200,6 +200,9 @@ static struct simple_buffer_page *simple_rb_move_tail(struct simple_rb_per_cpu *
 
 		simple_bpage_set_head_link(new_tail);
 		simple_bpage_set_normal_link(tail);
+	} else {
+		/* new_tail may have been swapped out by the reader */
+		new_tail = simple_bpage_from_link(READ_ONCE(tail->link.next));
 	}
 
 	simple_bpage_reset(new_tail);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 3+ messages in thread

* Re: [PATCH] tracing: Fix simple_ring_buffer writer moving onto the reader page
  2026-12-04 16:46 [PATCH] tracing: Fix simple_ring_buffer writer moving onto the reader page Andrea Parri
@ 2026-12-04 17:56 ` Vincent Donnefort
  2026-12-04 18:10   ` Andrea Parri
  0 siblings, 1 reply; 3+ messages in thread
From: Vincent Donnefort @ 2026-12-04 17:56 UTC (permalink / raw)
  To: Andrea Parri
  Cc: Steven Rostedt, Masami Hiramatsu, Mathieu Desnoyers, linux-kernel,
	linux-trace-kernel, kvmarm

On Fri, Dec 04, 2026 at 05:46:08PM +0100, Andrea Parri wrote:
> simple_rb_move_tail() loads the page after the tail and, if it is the
> head, moves the HEAD flag past it with a cmpxchg() on tail->link.next.
> simple_ring_buffer_swap_reader_page() can swap the head out in between,
> so the cmpxchg() fails and the writer moves onto the page it loaded,
> now the reader page:
> 
>   CPU 1 (writer)                    CPU 0 (reader)
>   simple_rb_move_tail()             simple_ring_buffer_swap_reader_page()
>     new_tail = B  (A->next == B|HEAD)
>                                       cmpxchg(A->next, B|HEAD, R)
>                                       reader_page = B
>     cmpxchg(A->next) fails
>     simple_bpage_reset(B)
>     tail_page = B
> 
> The writer then overwrites the page the reader is consuming.  Once that
> page is full, the writer moves on to the new head through a link that
> does not carry the HEAD flag, and overwrites unread pages without adding
> them to overrun.
> 
> The reader gets no "[LOST n EVENTS]" notice for these events, and the
> unread count, entries - (overrun + read), no longer drops to zero.  Once
> the buffer is drained, ring_buffer_wait() returns without sleeping and
> no event is found, so a trace_pipe reader spins in trace_pipe_read() and
> cannot be killed.  SysRq-L with the remote_test module:
> 
>   NMI backtrace for cpu 0
>   CPU: 0 UID: 0 PID: 87 Comm: srbrace Not tainted 7.4.0-rc5 #1 PREEMPT(lazy)
>   RIP: 0010:rb_buffer_peek+0x37/0x170
>   Call Trace:
>    <TASK>
>    ring_buffer_peek+0x84/0x160
>    trace_remote_iter_read_event+0x14d/0x180
>    trace_pipe_read+0xb1/0xf0
>    vfs_read+0xb4/0x370
>    ksys_read+0x68/0xe0
>    do_syscall_64+0xdf/0x4c0
>    entry_SYSCALL_64_after_hwframe+0x77/0x7f
> 
> The arm64 pKVM hypervisor runs the same writer at EL2 with
> NVHE_EL2_TRACING.  Its tracing_reserve_entry() does not take the
> trace_buffer lock that __tracing_swap_reader() holds, so hypervisor
> tracing should hit the same race.  This was only tested with remote_test.
> 
> Read tail->link.next again when the cmpxchg() fails.  After a reader
> swap it points to the previous reader page, which the reader has
> finished with.  In the main ring buffer, rb_head_page_set() reports
> this case as RB_PAGE_MOVED, and rb_move_tail() makes the writer retry
> the reservation.
> 
> This should be safe because only simple_ring_buffer_swap_reader_page()
> changes tail->link.next under the writer, and only once.  After the swap
> the head follows the previous reader page, and once the tail page itself
> is swapped out, further swaps return early until the writer leaves it.
> 
> When the reload observes the link published by the reader's successful,
> fully ordered try_cmpxchg(), the address dependency from READ_ONCE() to
> the page reset and the writes for the current reservation orders them
> after the reader's final accesses to that page.
> 
> Tested in a 4-vCPU x86-64 KVM guest, writing consecutive ids to
> remote_test on CPU 1 and reading per_cpu/cpu1/trace_pipe on CPU 0.
> Unpatched, three 60 s runs report 11, 7 and 13 gaps without a LOST
> notice and leave the reader stuck.  Patched, no run does.
> 
> The bug was found with the help of an LLM, which was also used to write
> the fix, the changelog and the tests.

Could you replace this with a concise, human-readable commit message without all
the unnecessary churn, so this is actually reviewable?
> 
> Fixes: 34e5b958bdad ("tracing: Introduce simple_ring_buffer")
> Cc: stable@vger.kernel.org # 7.1.x: 2a6d7231c79e: ring-buffer: Skip remote reader page swap when on tail
> Cc: stable@vger.kernel.org # 7.1.x
> Signed-off-by: Andrea Parri <parri.andrea@gmail.com>
> ---
> The herd7 test below (tools/memory-model, linux-kernel.cfg) models the
> READ_ONCE() reload and gives "Never".  With a plain reload instead,
> herd7 gives "Sometimes" and flags a data race.
> 
> C simple-rb-move-tail-reload-once

Why do we need this if remote_test is enough to reproduce the issue? 

> 
> (*
>  * Result: Never
>  *
>  * simple_rb_move_tail() losing its HEAD cmpxchg() to
>  * simple_ring_buffer_swap_reader_page(), then reloading tail->link.next
>  * with READ_ONCE(), as in the fix.
>  *
>  * an models tail->link.next, without the HEAD/HEAD_MOVING flag bits, and
>  * initially points to the head page b.  P0 is the reader: its last read
>  * of its reader page r is a plain read, then its cmpxchg() swaps b out
>  * and links r after the tail.  P1 is the writer: its HEAD cmpxchg()
>  * fails, it reloads an and stores into the page it finds, as
>  * simple_bpage_reset() and the event writes do.  The exists clause is the
>  * writer's store into r being visible to the reader's last read of r.
>  *)
> 
> {
> 	an=b;
> }
> 
> P0(int **an, int *b, int *r)
> {
> 	int r0;
> 	int *r1;
> 
> 	r0 = *r;
> 	r1 = cmpxchg(an, b, r);
> }
> 
> P1(int **an, int *b, int *c)
> {
> 	int *r2;
> 	int *p;
> 
> 	r2 = cmpxchg(an, b, c);
> 	if (r2 != b) {
> 		p = READ_ONCE(*an);
> 		*p = 1;
> 	}
> }
> 
> exists (0:r0=1 /\ 0:r1=b /\ 1:p=r)
> 
> Reproducer below, run as root on a kernel with CONFIG_TRACE_REMOTE_TEST=y
> and at least two CPUs, as "srbrace [seconds [wcpu [rcpu]]]".  Without
> this patch it prints "VIOLATION" with the first gaps and reports its
> trace_pipe reader as stuck: once the buffer is drained, read() does not
> return after a signal, and the thread keeps spinning after main()
> returns.  With it, it prints "no violation" and exits.
> 
> // SPDX-License-Identifier: GPL-2.0
> /*
>  * Stress simple_rb_move_tail() against simple_ring_buffer_swap_reader_page()
>  * through the remote_test trace remote (CONFIG_TRACE_REMOTE_TEST=y).
>  *
>  * The writer thread, pinned to WCPU, writes consecutive ids to write_event,
>  * so every event lands in WCPU's simple_ring_buffer.  The reader thread,
>  * pinned to RCPU, consumes per_cpu/cpuWCPU/trace_pipe.  The buffer is kept at
>  * its minimum size so the writer keeps overwriting the head page.
>  *
>  * Lost events must be reported: a gap in the ids not preceded by a
>  * "[LOST n EVENTS]" line, or an id going backwards, means the writer
>  * overwrote pages without accounting for them.  A notice whose count
>  * differs from the gap after it is counted as "miscounted", for
>  * information only.
>  *
>  * Once the writer stops and the reader has drained the buffer, trace_pipe
>  * must sleep in read(), where a signal interrupts it.  A reader that does
>  * not return from read() after SIGUSR1 is spinning in the kernel, which
>  * the overwrites cause even when the gaps hide behind a loss notice.
>  *
>  * Usage: srbrace [seconds [wcpu [rcpu]]]   (defaults: 60 1 0)
>  * Exit status: 0 = violation seen, 2 = none, 1 = setup error, read()
>  * error or no progress.
>  */
> #define _GNU_SOURCE
> #include <errno.h>
> #include <fcntl.h>
> #include <pthread.h>
> #include <sched.h>
> #include <signal.h>
> #include <stdatomic.h>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> #include <time.h>
> #include <unistd.h>
> 
> #define RDIR "/sys/kernel/tracing/remotes/test/"
> 
> static int wcpu = 1, rcpu = 0;
> static atomic_int stop;
> static unsigned long long written, failed;
> 
> /* Updated by the reader thread, read by main() while it may still run. */
> static atomic_ullong events, lost_lines, lost_total;
> static atomic_ullong gaps, backwards, garbled, miscounted;
> static atomic_int read_err;
> 
> #define add(var, n)	atomic_fetch_add_explicit(&(var), (n), memory_order_relaxed)
> #define get(var)	atomic_load_explicit(&(var), memory_order_relaxed)
> 
> static void pin(int cpu)
> {
> 	cpu_set_t set;
> 
> 	CPU_ZERO(&set);
> 	CPU_SET(cpu, &set);
> 	if (sched_setaffinity(0, sizeof(set), &set)) {
> 		perror("sched_setaffinity");
> 		exit(1);
> 	}
> }
> 
> static void put(const char *file, const char *val)
> {
> 	char path[256];
> 	int fd;
> 
> 	snprintf(path, sizeof(path), RDIR "%s", file);
> 	fd = open(path, O_WRONLY | O_TRUNC);
> 	if (fd < 0 || write(fd, val, strlen(val)) < 0) {
> 		fprintf(stderr, "%s: %s\n", path, strerror(errno));
> 		exit(1);
> 	}
> 	close(fd);
> }
> 
> static void *writer(void *arg)
> {
> 	unsigned long long id = 1;
> 	char buf[32];
> 	int fd, len;
> 
> 	pin(wcpu);
> 	fd = open(RDIR "write_event", O_WRONLY);
> 	if (fd < 0) {
> 		perror("write_event");
> 		exit(1);
> 	}
> 
> 	while (!atomic_load_explicit(&stop, memory_order_relaxed)) {
> 		len = snprintf(buf, sizeof(buf), "%llu", id);
> 		if (write(fd, buf, len) == len) {
> 			id++;
> 			written++;
> 		} else {
> 			failed++;
> 		}
> 	}
> 
> 	close(fd);
> 	return NULL;
> }
> 
> static void report(const char *what, unsigned long long prev, const char *line)
> {
> 	static int printed;
> 
> 	if (printed++ < 10)
> 		printf("%s after id=%llu: %s\n", what, prev, line);
> }
> 
> static void check_line(char *line)
> {
> 	static unsigned long long prev, lost_n;
> 	static int lost_pending;
> 	unsigned long long id, n;
> 	char *p;
> 
> 	if (sscanf(line, "CPU:%*d [LOST %llu EVENTS]", &n) == 1) {
> 		add(lost_lines, 1);
> 		add(lost_total, n);
> 		lost_pending = 1;
> 		lost_n += n;
> 		return;
> 	}
> 
> 	p = strstr(line, " selftest id=");
> 	if (!p || sscanf(p, " selftest id=%llu", &id) != 1) {
> 		add(garbled, 1);
> 		report("garbled line", prev, line);
> 		return;
> 	}
> 
> 	add(events, 1);
> 	if (prev && id <= prev) {
> 		add(backwards, 1);
> 		report("id went backwards", prev, line);
> 	} else if (prev && id != prev + 1 && !lost_pending) {
> 		add(gaps, 1);
> 		report("unreported gap", prev, line);
> 	} else if (prev && lost_pending && id - prev - 1 != lost_n) {
> 		add(miscounted, 1);
> 	}
> 	lost_pending = 0;
> 	lost_n = 0;
> 	prev = id;
> }
> 
> static void *reader(void *arg)
> {
> 	static char buf[1 << 16];
> 	char path[256], *nl, *start;
> 	size_t fill = 0;
> 	ssize_t n;
> 	int fd;
> 
> 	pin(rcpu);
> 	snprintf(path, sizeof(path), RDIR "per_cpu/cpu%d/trace_pipe", wcpu);
> 	fd = open(path, O_RDONLY);
> 	if (fd < 0) {
> 		perror(path);
> 		exit(1);
> 	}
> 
> 	for (;;) {
> 		n = read(fd, buf + fill, sizeof(buf) - 1 - fill);
> 		if (n < 0 && errno == EINTR)	/* SIGUSR1 from main() */
> 			break;
> 		if (n <= 0) {
> 			/* trace_pipe blocks rather than returning 0 */
> 			atomic_store(&read_err, n < 0 ? errno : ENODATA);
> 			break;
> 		}
> 		fill += n;
> 		buf[fill] = '\0';
> 
> 		start = buf;
> 		while ((nl = strchr(start, '\n'))) {
> 			*nl = '\0';
> 			check_line(start);
> 			start = nl + 1;
> 		}
> 		fill -= start - buf;
> 		memmove(buf, start, fill);
> 	}
> 
> 	return NULL;
> }
> 
> static void on_sigusr1(int sig)
> {
> }
> 
> int main(int argc, char **argv)
> {
> 	struct sigaction sa = { .sa_handler = on_sigusr1 };	/* no SA_RESTART */
> 	int secs = argc > 1 ? atoi(argv[1]) : 60;
> 	int err, i, stuck = 1;
> 	struct timespec ts;
> 	pthread_t w, r;
> 
> 	if (argc > 2)
> 		wcpu = atoi(argv[2]);
> 	if (argc > 3)
> 		rcpu = atoi(argv[3]);
> 
> 	put("tracing_on", "0");
> 	put("trace", "");
> 	put("buffer_size_kb", "7");
> 	put("events/enable", "0");
> 	put("events/test/selftest/enable", "1");
> 	put("tracing_on", "1");
> 
> 	sigaction(SIGUSR1, &sa, NULL);
> 	setvbuf(stdout, NULL, _IOLBF, 0);
> 	err = pthread_create(&r, NULL, reader, NULL);
> 	if (!err)
> 		err = pthread_create(&w, NULL, writer, NULL);
> 	if (err) {
> 		fprintf(stderr, "pthread_create: %s\n", strerror(err));
> 		return 1;
> 	}
> 
> 	sleep(secs);
> 	atomic_store(&stop, 1);
> 	pthread_join(w, NULL);
> 	/* Let the reader drain what is left; it blocks in trace_pipe after. */
> 	sleep(1);
> 
> 	/* Repeat in case a signal lands while the reader is not in read(). */
> 	for (i = 0; i < 20 && stuck; i++) {
> 		pthread_kill(r, SIGUSR1);
> 		clock_gettime(CLOCK_REALTIME, &ts);
> 		ts.tv_nsec += 100000000;
> 		if (ts.tv_nsec >= 1000000000) {
> 			ts.tv_sec++;
> 			ts.tv_nsec -= 1000000000;
> 		}
> 		stuck = pthread_timedjoin_np(r, NULL, &ts) != 0;
> 	}
> 
> 	printf("written=%llu failed=%llu events=%llu lost_lines=%llu lost=%llu gaps=%llu backwards=%llu garbled=%llu miscounted=%llu\n",
> 	       written, failed, get(events), get(lost_lines), get(lost_total),
> 	       get(gaps), get(backwards), get(garbled), get(miscounted));
> 
> 	if (stuck)
> 		printf("reader stuck in trace_pipe read() after SIGUSR1\n");
> 	if (get(gaps) || get(backwards) || get(garbled) || stuck) {
> 		printf("VIOLATION\n");
> 		return 0;
> 	}
> 	if (atomic_load(&read_err)) {
> 		printf("reader: read: %s\n", strerror(atomic_load(&read_err)));
> 		return 1;
> 	}
> 	if (!written || !get(events)) {
> 		printf("no progress\n");
> 		return 1;
> 	}
> 	printf("no violation\n");
> 	return 2;
> }
> 
>  kernel/trace/simple_ring_buffer.c | 3 +++
>  1 file changed, 3 insertions(+)
> 
> diff --git a/kernel/trace/simple_ring_buffer.c b/kernel/trace/simple_ring_buffer.c
> index 2dddaef638dc6..f7ec0b9a2df92 100644
> --- a/kernel/trace/simple_ring_buffer.c
> +++ b/kernel/trace/simple_ring_buffer.c
> @@ -200,6 +200,9 @@ static struct simple_buffer_page *simple_rb_move_tail(struct simple_rb_per_cpu *
>  
>  		simple_bpage_set_head_link(new_tail);
>  		simple_bpage_set_normal_link(tail);
> +	} else {
> +		/* new_tail may have been swapped out by the reader */
> +		new_tail = simple_bpage_from_link(READ_ONCE(tail->link.next));
>  	}
>  
>  	simple_bpage_reset(new_tail);
> -- 
> 2.53.0
> 

-- 
Vincent

^ permalink raw reply	[flat|nested] 3+ messages in thread

* Re: [PATCH] tracing: Fix simple_ring_buffer writer moving onto the reader page
  2026-12-04 17:56 ` Vincent Donnefort
@ 2026-12-04 18:10   ` Andrea Parri
  0 siblings, 0 replies; 3+ messages in thread
From: Andrea Parri @ 2026-12-04 18:10 UTC (permalink / raw)
  To: Vincent Donnefort
  Cc: Steven Rostedt, Masami Hiramatsu, Mathieu Desnoyers, linux-kernel,
	linux-trace-kernel, kvmarm

On Fri, Dec 04, 2026 at 05:56:06PM +0000, Vincent Donnefort wrote:
> On Fri, Dec 04, 2026 at 05:46:08PM +0100, Andrea Parri wrote:
> > simple_rb_move_tail() loads the page after the tail and, if it is the
> > head, moves the HEAD flag past it with a cmpxchg() on tail->link.next.

[...]

> Could you replace this with a concise, human-readable commit message without all
> the unnecessary churn, so this is actually reviewable?

Sure, I'll send a v2 with a short changelog.

> > C simple-rb-move-tail-reload-once
>
> Why do we need this if remote_test is enough to reproduce the issue?

We don't.  It only modelled why the READ_ONCE() reload needs no extra
barrier; I'll drop it from v2.

Thanks,
Andrea

^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2026-12-04 18:10 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04 16:46 [PATCH] tracing: Fix simple_ring_buffer writer moving onto the reader page Andrea Parri
2026-12-04 17:56 ` Vincent Donnefort
2026-12-04 18:10   ` Andrea Parri

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox