Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.221.50 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796402781; b=uckKtaFa2pPaqEeDSN2RLoy/jw99ZJJ5euJWYsZoZibUzvRZ2u9kaj2/pnOOxQYD7D+X w5jdZuA+GgBweUr0TN0YcIPnFKC5LOGiMJaBYbqzt2tMA/uIuUp3rqf+emrb6lVh1G0cY 057Vt2YF6AZiz49uB5qMOmOPHBq3GM0sAiS46z77vLkESpM6QoHwZuog4CRBZa+O7dBLA 41/Q6WCeRG6MBundTo8wKsHHWg6/kFHWWFN1w29Gl6IzIDh6kMd0AD0IRDKlQri1vLsYk MwxWXtTNSt7LWElc+LMBTCyvwqnjAbeiQoip4B3qZlZrCEotEEW3ZYGvJumjtZ5XwqA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796402781; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Gm-Gg:X-Received:Received: From:To:Cc:Subject:Date:Message-ID:X-Mailer:MIME-Version: Content-Transfer-Encoding; bh=Uj331mEkZs0ixqLLZPb8xoUa6eNiR2zOhCDXLu72TtA=; b=t9a+Vtlld/ra4E0AICG4bMgdPSrFgwLMgxcPWIO8cuxv9b0a8Yhz+Utg/0EJr4S7HhKC 7gPZ5J7CHK6/jZd0hKlf3cEnLejYU7gj3zZDEHnunJlL3L7Aki62HxImc8YHweCoj8JJC psbVL9NLOe65Ldwo44sdyoYH8RB6BNLr6Gx7MLM3lNRULZHeyFRl1Muzlx8zUvz1EE83k DOCLBHJ+/M2Uat+Ut8cyccaKtcZ3VEZv3GRFzLYytwLvTOkjyFjmMKNWR/LClKZo+DYqp bKNzgBYxEpoAtFlNYn+MYOYRE9uddMMXG/79zrTXFjNyE0JfNdvcHJ5VQID2QDmQo9g== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=XZ3TxBL5; arc=none smtp.remote-ip=209.85.221.50 Received: from mail-wr1-f50.google.com (mail-wr1-f50.google.com [209.85.221.50]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id ECA84606A32D for ; Fri, 4 Dec 2026 16:46:20 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org ECA84606A32D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=XZ3TxBL5 Received: by mail-wr1-f50.google.com with SMTP id ffacd0b85a97d-4a5024b3c28so1325113f8f.0 for ; Fri, 04 Dec 2026 08:46:20 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796402779; x=1797007579; darn=lists.linux.dev; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to:content-type; bh=Uj331mEkZs0ixqLLZPb8xoUa6eNiR2zOhCDXLu72TtA=; b=XZ3TxBL5TiwqkJTix7XU1X0bf02psXSr56tq8iJ2qxE90+2t6/oWfhkfi8nRyAIyoR v9N7ZTmnYcOY+YtTp8NqR9fwtlzOA3UrNMBc87LLnrOtBATv5+/RavI1PuSGQo+p2IrA Pmb/mSjOdPWHBOSmze/IBnznutDEbuICKlZ4aiN8KLi0BF2Nf1OTlPnKxYwlG+5iRxaA JgWzu6MUSDz3Ocdfqua9/L6fwxz/hjnghQXJy8sQpdh4qDNCwXg8NRe8Rb3KjQLpjzLz F6xdA8MpzMg6zp8JDbA5BG275HJ3UEnHI2uNCUG17ZHoZtiiLInn12KdcD8pUyynyAiE vDLg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796402779; x=1797007579; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=Uj331mEkZs0ixqLLZPb8xoUa6eNiR2zOhCDXLu72TtA=; b=1jR/OeZMDUP1471EN6EINeMkPzNcaiX8bQvq6I0dIqnj01bCo6WOaopEmUsq2bkVu0 5CRvuB0jZLvaM6Ee7qnAtqRef8ldQVDin2Rz4Mi92mZqTPenPLn0ncGluQx2BKCP3X6w sbxZfqIDyx9Mk3oHfr7QSnXBsmskepKvNdXeT+iw148LZ8AZPP1mIj0K8nO/udxpy2zB QKBg2HdiYaMmkId1gIc6OKGjjdnDrFCmjx/w6asEaVk19etw9+x6Hja+1w8IXy7UO4OC dLOwjl5jENwpBZKREHD2mi39PZVVkyNJdIFeR3Rd8j+wuPWrwkxnBwLFmK68jzHFGqRA iY3A== X-Forwarded-Encrypted: i=1; AL+hErEeAyueUUUyYslTafARYfy9moyHGc3svOLDgRq+G+p+aoirp0DBehKqAqjHIN6b46B/zkAVpy0=@lists.linux.dev X-Gm-Message-State: AB4q+uHh1Lo+KQw/+xDFKcdKE/+VWCSzrDfVNZDbaJpVGJqEIiWDlP8Z LdoVFNtQRs0VbgIR1BT3q9Oed6IPy5ZJ+Nyk+FArC89ae2tZigDvwEiC4DkbiQ== X-Gm-Gg: AZFdTZdSSp0S9nXYlMN/wqvOqxaNYMIg5HKFCbJ2aAjnKwYlh617zxoRThoie83FdQc gozLqMnc6osvSRo5+gvyrR1EYVlK83y0WCqTsdqOecb4GHudvxL9TL2bVNfmWSe/GFRq0OF+2og R+eehio4EFcHiHhn6bhrcME7i9gvB6RNcPZy2cTS1Xstd0zjgZC9/5n7NBC59ehOueySze7oteU Y8R236Gc/fOyOreWjqBwShdOi3eQU2SssjozE3mkZ8JkuUr0hW7B4a3SfvzyOjC5nWJR+dfQl4m ujweslsaN2IkzLOx3n2LhdQlLxytLe4wA5GPM5IbDAvWZuj5uG64R630oaFVDfIwYvl7bAezC2p yQ0VE23jC+fU9infgeJsJP4j35cptU1+s8gY1uzWl9FYbhpsbv6itsB7+vdWCcSCBXn7AFqNMa6 RC3qIKXu2ND2Zkc0yoClcr5yWsokCeM4JmWpInGyK0n3M8JS0MFap+Cm2XYO1VdXSyaOiU6cFHb xXJ3k7wdtFfkaMrzo5uQy7/RL8KhPgem6a8y+uOjUSxTZItl1+6He7s17/LBwGxqidESZZgyf0A xO4RO4PzM2mP7snLhwOVGKcM0DSO4XNv/OdZUuLa+KaqloT9+m3Q9ZqINItn1MxwSAbcZ6kUBE/ V5T4MEQx6bHn6ChhNSVM+WA== X-Received: by 2002:a05:6000:4209:b0:4d1:3fc4:c6cc with SMTP id ffacd0b85a97d-4d1ea3be936mr6358025f8f.15.1796402779089; Fri, 04 Dec 2026 08:46:19 -0800 (PST) Received: from andreayoga.wind3.hub ([31.189.39.21]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-4d1737dac8esm6480223f8f.33.2026.12.04.08.46.18 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 04 Dec 2026 08:46:18 -0800 (PST) From: Andrea Parri To: Steven Rostedt , Vincent Donnefort , Masami Hiramatsu Cc: Mathieu Desnoyers , linux-kernel@vger.kernel.org, linux-trace-kernel@vger.kernel.org, kvmarm@lists.linux.dev Subject: [PATCH] tracing: Fix simple_ring_buffer writer moving onto the reader page Date: Fri, 4 Dec 2026 17:46:08 +0100 Message-ID: <20261204164610.37936-1-parri.andrea@gmail.com> X-Mailer: git-send-email 2.53.0 X-Mailing-List: kvmarm@lists.linux.dev List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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: 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 --- 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 #include #include #include #include #include #include #include #include #include #include #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