From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.221.48 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796402781; b=xUyMyO7tRMm4xuIkmPxl7l/XWOBXd4lmBThE+DxhpvHk7VQ67xeQKrJeaCcyHkrmoiJx 5UDmvaS0OrwN5qdFG73emuXg2ft5JfxrbToj0V2u8+J75j77R9qvbivHfsPLZJmar7OF9 Jg1n2DPTKG/duif1zhWBvaCm/ila+PsJFCmw3sBLV4ykS21IKAhngs3r//h9/B08nS9KY RoXY15/DdOV1UJFD3hpi+clUQBpSDKmwx1SmjcJWELzyNOjnda+TmcQqmsP9hRoHfju5m PH0FlSMyGjE2YT4pL8To9I1XslDl24dV6NgWQ3OSKlGLwRylGG/2dabMeC6cVOOEl3g== 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=LCldEHSVOBQXtjgvrCi7Il5XeFZB/0jFOA/J9eqzJd8cPpgvtjA7jfLCQHybjbUeM/Px zDVe9kkIfJ7hEZwyO06M85KmqjhEJCMAoKqHkWb+rxf2A3ukQT7nyFJW2WJdXxotT0Rqe 3PTEEm0YZ4g2Kon1TqzWP1qSewiK7Oskmayz1EH/rKE/XbANxv3IKOz0Qgjvd8irbD3Z+ o+EQ/MYNPy3YLX3cYk5znmQGUu4R5s8ltbiDqIO1J/kQM5nYvQ1zMB8mhoZI0UD/aNAm3 lk0Wz5Sax35SeF4KJzpvJg86+4xVpk7Xv9xWIdCFj3mX9AozMbQjKqa22HklPQQweYQ== 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=Sim0Tprm; arc=none smtp.remote-ip=209.85.221.48 Received: from mail-wr1-f48.google.com (mail-wr1-f48.google.com [209.85.221.48]) (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 F20D6606A32F for ; Fri, 4 Dec 2026 16:46:20 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org F20D6606A32F 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=Sim0Tprm Received: by mail-wr1-f48.google.com with SMTP id ffacd0b85a97d-4c3f0acc1easo847385f8f.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=vger.kernel.org; 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=Sim0TprmPBKb/6zIbYAiVpikwOtpr5Epmc62LBAAmDAptTnLt8eqlbyT8Lb/o5r9XT VuJaL9aoqB0Vu78wTjixn4AuLlXQkFQT1tH4KGcBVko5UK+12VFbYsJUhfD8b5UQOWfQ ofZFK3Ee0gqLOnPm913OljXWTu/Ne2sINUTYbCPhb1eG14YjaIHsWwJFAAOjJpMufpln 3U1D/GqjvoYQCMCSWCl6kpulQ2u8HExZgeqTjf8JHqpm+ZpH4bnNu2+jiHagzOtPnY6L dDsy6E9n3toqQywHHF01PXXqxo5UULaiWFxAaiTkYZA/VyMHpke/Z5CNoYkxNBeDrYAM 0XKA== 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=kKDgg9wEwMECYw2WkcaKbs8+iKXQ8atP6gVq9qSOUjUqwVmSIcqZFkIHbtL/1/kwEE b+XcDB3+sGAGHTJSYFWYqnw5NZEK+MDUBUzbjOJikmcLNLWDFoHv5jSTUUhQTsA31Neh QwHB9xCduhRcK7Dj/DBB4bDnXHzWI2PTEyuV5uZhSdIs5K3aJjgvRAZnMv8oxed4LRyp QSV7ytVTNun3cwrk55ghsVn1tSlVOHqc2bmmBnIfAhZeC8pToiH3Xo5edUVEthvWvYrb RSnO9qc12aQahYYGv3yt2jQ1KxFv3YNYiK7WcXnKDGGayUq8p670DgbFjmNpiMfr+BZj AqcA== X-Forwarded-Encrypted: i=1; AL+hErHQ5XaZ8ygpual9GkCyj3amwbPbH+/m1TQgvkwyBb6eDcg+G6Ew5dXP2MnmkeGrc+OjPO6OIp8cUqGyh1KvnsX1iqw=@vger.kernel.org X-Gm-Message-State: AB4q+uGscz5sYKTszHuGYFK8+64e1bQgT1RPCNZtjc3/t/qlEVsiLs+i rSHIksBHrL53DJqddA6/j9KYewcO24JrWL36KAAvYarbUDpWr0PrULqJ X-Gm-Gg: AZFdTZewpzjLsPM0z1v4f5/vBDKUPf6oDiZ8Dby/E9gm+L5oo5NIlWQQ6ISJ3mbp39P sNr6vEXItpqSsmZmJ17VxH3i6iQEb6H1DghoiPBCR9+28jKWkjJ1LQYXCSbZbDkNSjyv8QWqaCU A+Ao7pmcMdKPEAMjr05gZ2mgE2wmyJ0jcyvq+PNI3dZfVdyeoFivvy/ZOVGItDHJZ89nrZlMllA jpqYgl0SDLTLW7SLLmMjXs+qB2z+27PCbxWki4Y288DKC7AOPAXFYyi8wiRfHffb8/mf+r2RO0m 2caPU5zUyj0ndqI2cv5/UV9Tf5ArmUEPytYyGWPmdixt4TtZIm33HBa7u02N/ffcxSs5sRARjss 6nHSWQyoDbFgWokaEs5gXJKiNhXlx7krQ29DiLwRUwoC9aQpsTzkpcM52q/Jeiwjeh6wYx3L7H6 6+XkjJwei2eDd9YP+3m0hNRGQcFDZ8BRicRlg11BErbWIfFiK0EuU/GIsVjyWY5m9PJI8lDyABn HqbUze+cnrrk6SOmAYiRdjKHnoIAtbpWsSGHhHOE8p38jcGqWK7G893mrHkAbqMbnquI/OVCDm2 WoePW298l0VMkEyvpkL0w4Q1+cV/vcXiMXZewO2GTCQQ4n/9DMG+TBWPdrmW8ZKZgmAGq5tVvwY ozU9/srNzSOD97TmgA0H3vA== 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: linux-trace-kernel@vger.kernel.org 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