Netdev List
 help / color / mirror / Atom feed
* net: rtnetlink: rtnl_link_unregister() vs in-flight  RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix  (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3
       [not found] ` <2026102727-data-sequel-ce41@gregkh>
@ 2026-11-03 11:57   ` 徐晗翔
  2026-11-03 15:49     ` Eric Dumazet
  2026-11-04 15:03     ` Sasha Levin
  2026-11-03 12:07   ` wifi: wilc1000: SDIO/SPI remove destroys the srcu_struct before wiphy_unregister() -- late cfg80211 callbacks write through dangling srcu state (unfixed upstream; controlled + natural Oops) 徐晗翔
  2026-11-22  7:39   ` io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race) 徐晗翔
  2 siblings, 2 replies; 7+ messages in thread
From: 徐晗翔 @ 2026-11-03 11:57 UTC (permalink / raw)
  To: davem, edumazet, kuba, pabeni; +Cc: netdev, linux-kernel, stable

[-- Attachment #1: Type: text/plain, Size: 4303 bytes --]

On v7.3, rtnl_link_unregister() removes the rtnl_link_ops from the
global list and immediately destroys the embedded srcu_struct and
frees the ops memory -- a concurrent RTM_GETLINK dump that already
found the ops (rtnl_link_ops_get(), rtnetlink.c:599 hand-off inside
an RCU read critical section at :595) but has not yet taken
ops->srcu will, after the free, execute __srcu_read_lock() /
__srcu_read_unlock() on freed memory: two reads of the destroyed
object (ssp->srcu_ctrp, ssp->sda) whose subsequent percpu counter
writes land wherever the freed percpu pointers point -- for a module
rtnl_link_ops, the ops (and its srcu) live in module memory, so
module_memfree() is the freeing side.  Upstream already fixed this
with a synchronize_rcu() in rtnl_link_unregister() (the patch with
Fixes: 6b57ff21a310; its own comment: "Wait for rtnl_link_ops_get()
readers that found ops but have not yet taken ops->srcu").  v7.3
does not contain it.  I verified both sides on a stock 7.3 KASAN
kernel: parking a real dump reader (driven by an ordinary
RTM_GETLINK + IFLA_LINKINFO dump request) exactly at the :599
hand-off and unregistering+freeing underneath produces three KASAN
slab-use-after-free reports (__srcu_read_lock+0xe, +0x25,
__srcu_read_unlock+0x1a; bad address = ops+0x10 = ops->srcu); and
rebuilding the SAME kernel with ONLY the upstream one-line fix
flips the outcome to zero reports, with the kfree demonstrably
delayed until the parked reader left its RCU section.  Natural
hammering did not hit (the hand-off window is ~100 ns against a
~4 ms unregister -- it needs a preempted/preemptible-RCU reader),
which matches the fix's own reasoning; the controlled run models
exactly that preemption.  The purpose of this mail is to support
the fix's propagation: trees still carrying the unfixed
rtnl_link_unregister() keep a cross-CPU UAF (write) plus potential
freed-module execution reachable by unprivileged netlink dumps
racing a module unload.


The detailed description:

* The gap (v7.3, net/core/rtnetlink.c)
  rtnl_dump_ifinfo() runs lockless for dumps
  (RTNL_FLAG_DUMP_UNLOCKED), takes rcu_read_lock() at :595, calls
  linkinfo_to_kind_ops() -> rtnl_link_ops_get() which returns the
  ops pointer at :599, and only then takes ops->srcu
  (srcu_read_lock) to call ops->dumpit.  rtnl_link_unregister()
  holds rtnl_mutex, removes the ops from the list, calls
  cleanup_srcu_struct(&ops->srcu) and returns to the module, whose
  exit then frees the module memory.  Nothing between the :599
  hand-off and the srcu_read_lock is waited for on the unregister
  side in 7.3 -- hence the fix's synchronize_rcu().

* Evidence (stock 7.3 KASAN, QEMU; A/B on the one-line fix;
  reproducers attached)
  rtnlrace.c registers a kzalloc'd rtnl_link_ops (kind "rtnlrace"),
  parks a dump reader by kprobe at the exact hand-off (return
  address rtnl_dump_ifinfo+0x374, ENDBR-adjusted), and unregisters
  + kfrees from another thread (modeling module_exit ->
  module_memfree).  nlr (userspace) sends the IFLA_LINKINFO dump
  request that drives the reader path.
  Defect kernel (stock 7.3):
    park t=127041 (1004 ms) -> unregister+kfree at t=127249 (park
    +208 ms, reader still parked 792 ms) -> park ends t=128045:
    BUG: KASAN: slab-use-after-free in __srcu_read_lock+0xe
    BUG: KASAN: slab-use-after-free in __srcu_read_lock+0x25
    BUG: KASAN: slab-use-after-free in __srcu_read_unlock+0x1a
      read stack: __srcu_read_lock <- rtnl_dump_ifinfo+0x374 <-
        rtnl_dumpit <- netlink_dump <- rtnetlink_rcv_msg (task nlr)
      bad address = object+0x10 == ops->srcu (matches the
      disassembly lea 0x10(%rbx))
      alloc: insmod kzalloc;  free: unregister thread kfree
  Fixed kernel (same sources, ONLY the upstream synchronize_rcu()
  added to rtnl_link_unregister()):
    park t=191305 -> park ENDS t=192306 -> unregister+kfree
    t=192307 -- the order literally inverts -- zero KASAN reports,
    dump completes with zero errors.  Same module, same parking.
  Natural runs (three samplings, up to ~267k dumps/reader plus
  6-CPU preemption spinners): zero hits; the window arithmetic
  (~100 ns hand-off vs ~4 ms unregister) explains it, and the
  controlled park models precisely the preemption the upstream
  fix's comment describes.


Regards,
Hanxiang Xu
xuhx@hust.edu.cn

[-- Attachment #2: nlr.c --]
[-- Type: text/plain, Size: 3485 bytes --]

// SPDX-License-Identifier: GPL-2.0+
/*
 * nlr.c - userspace RTM_GETLINK dump hammer for the rtnl_link_ops_get()
 * verification (audit-report Case 1).
 *
 * Sends NLM_F_DUMP RTM_GETLINK requests carrying a nested
 * IFLA_LINKINFO{ IFLA_INFO_KIND=<kind> } filter, which drives exactly:
 *
 *   rtnl_dump_ifinfo -> linkinfo_to_kind_ops -> rtnl_link_ops_get(kind)
 *     -> (inlined) list_for_each_entry_rcu + strcmp + srcu_read_lock(&ops->srcu)
 *
 * i.e. the audited reader path. The dump walk itself runs without RTNL
 * (RTM_GETLINK is registered RTNL_FLAG_DUMP_UNLOCKED), so it is fully
 * concurrent with rtnl_link_unregister().
 *
 * Usage: nlr <kind> [seconds]
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>

#ifndef RTNL_FAMILY_MAX
#define RTNL_FAMILY_MAX 33
#endif

#define NLR_BUF 65536

static int mk_dump_req(char *b, int blen, const char *kind, uint32_t seq)
{
	struct nlmsghdr *nh = (struct nlmsghdr *)b;
	struct ifinfomsg *ifi;
	struct rtattr *linfo, *ikind;
	int klen = strlen(kind) + 1;

	memset(b, 0, blen);
	nh->nlmsg_len = NLMSG_LENGTH(sizeof(*ifi));
	nh->nlmsg_type = RTM_GETLINK;
	nh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
	nh->nlmsg_seq = seq;
	nh->nlmsg_pid = 0;

	ifi = NLMSG_DATA(nh);
	ifi->ifi_family = AF_UNSPEC;

	/* nested IFLA_LINKINFO { IFLA_INFO_KIND = kind } */
	linfo = (struct rtattr *)((char *)b + NLMSG_ALIGN(nh->nlmsg_len));
	linfo->rta_type = IFLA_LINKINFO;
	linfo->rta_len = RTA_LENGTH(0);

	ikind = (struct rtattr *)((char *)linfo + RTA_ALIGN(linfo->rta_len));
	ikind->rta_type = IFLA_INFO_KIND;
	ikind->rta_len = RTA_LENGTH(klen);
	memcpy(RTA_DATA(ikind), kind, klen);

	linfo->rta_len = (char *)ikind + RTA_ALIGN(ikind->rta_len) - (char *)linfo;
	nh->nlmsg_len = (char *)ikind + RTA_ALIGN(ikind->rta_len) - b;
	return nh->nlmsg_len;
}

int main(int argc, char **argv)
{
	const char *kind = argc > 1 ? argv[1] : "rtnlrace";
	int secs = argc > 2 ? atoi(argv[2]) : 30;
	int fd, iters = 0, errs = 0;
	uint32_t seq = 1;
	char req[NLR_BUF], buf[NLR_BUF];
	struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
	time_t t0 = time(NULL);

	fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
	if (fd < 0) {
		perror("socket");
		return 1;
	}
	setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));

	fprintf(stderr, "nlr: hammering RTM_GETLINK dumps with kind=%s for %ds\n",
		kind, secs);

	while (time(NULL) - t0 < secs) {
		struct sockaddr_nl sa = { .nl_family = AF_NETLINK };
		struct iovec iov = { buf, sizeof(buf) };
		struct msghdr msg = {
			.msg_name = &sa, .msg_namelen = sizeof(sa),
			.msg_iov = &iov, .msg_iovlen = 1,
		};
		int len = mk_dump_req(req, sizeof(req), kind, seq++);
		ssize_t n;

		if (sendto(fd, req, len, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
			errs++;
			continue;
		}
		/* drain until DONE or timeout/error */
		for (;;) {
			n = recvmsg(fd, &msg, 0);
			if (n <= 0) {
				errs++;
				break;
			}
			{
				struct nlmsghdr *nh = (struct nlmsghdr *)buf;

				for (; NLMSG_OK(nh, (unsigned)n);
				     nh = NLMSG_NEXT(nh, n)) {
					if (nh->nlmsg_type == NLMSG_DONE ||
					    nh->nlmsg_type == NLMSG_ERROR)
						goto next_iter;
				}
			}
		}
next_iter:
		iters++;
		if ((iters & 0x3ff) == 0)
			fprintf(stderr, "nlr: %d iters (%d errs)\n", iters, errs);
	}
	fprintf(stderr, "nlr: done: %d iters, %d errs\n", iters, errs);
	return 0;
}

[-- Attachment #3: rtnlrace.c --]
[-- Type: text/plain, Size: 7729 bytes --]

// SPDX-License-Identifier: GPL-2.0+
/*
 * rtnlrace.c - dynamic verification for the audit-report Case 1:
 *
 *   rtnl_link_unregister() (net/core/rtnetlink.c:701-729) is missing the
 *   synchronize_rcu() that upstream "rtnetlink: wait for RCU readers in
 *   rtnl_link_unregister()" (Fixes: 6b57ff21a310) added.
 *
 *   Reader window under test (rtnetlink.c:595-606, rtnl_link_ops_get inlined):
 *        rcu_read_lock();                       // :595
 *        list_for_each_entry_rcu(...)           // :597  found ops via RCU
 *          strcmp(ops->kind, kind)              // :598  matched
 *          *srcu_index = srcu_read_lock(&ops->srcu);   // :599  <-- handoff
 *        rcu_read_unlock();                     // :606
 *
 * Controlled mode (stall_us > 0):
 *   - registers a kzalloc()'d rtnl_link_ops with kind "rtnlrace"
 *     (rtnl_link_register is EXPORT_SYMBOL_GPL), so a userspace RTM_GETLINK
 *     dump with IFLA_INFO_KIND=rtnlrace walks exactly the audited path.
 *   - a kprobe on __srcu_read_lock with return-address filter parks the dump
 *     reader exactly at the :599 handoff (inside the RCU read-side critical
 *     section, before any SRCU state is touched): the audited window, enlarged
 *     for deterministic observation (same technique as kmod/r4_stall.c).
 *   - the unregister kthread then performs what module_exit does:
 *     rtnl_link_unregister(ops) -> list_del_rcu + synchronize_srcu (returns
 *     immediately: the parked reader has NOT entered the SRCU region) +
 *     cleanup_srcu_struct (frees srcu_usage and the percpu sda, sets
 *     ssp->srcu_sup/sda to NULL, leaves srcu_ctrp dangling), then kfree(ops)
 *     (models module_memfree of the unloaded module's static storage; KASAN
 *     slab poisoning makes the post-free read observable).
 *   - the parked reader resumes: READ_ONCE(ssp->srcu_ctrp) on freed memory
 *     => KASAN use-after-free Read in __srcu_read_lock.
 *
 * Natural mode (stall_us == 0): no kprobe, no init registration. A kthread
 * hammers kzalloc/rtnl_link_register/rtnl_link_unregister/kfree cycles of a
 * kind-"rtnlrace" ops while userspace hammers dumps; the natural
 * strcmp->srcu_read_lock window is the only interleaving (rmmod shape).
 *
 * Offsets for build-kasan-7.3/vmlinux (rtnl_link_ops_get fully inlined):
 *   rtnl_dump_ifinfo @ 0xffffffff826e8030 (size 0x925)
 *     call __srcu_read_lock @ +0x36f -> return address +0x374 (kprobe base skips ENDBR, live filter +0x370)
 */
#define pr_fmt(fmt) "RTNLRACE: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/srcu.h>
#include <net/rtnetlink.h>
#include <linux/kthread.h>
#include <linux/atomic.h>

static int stall_ms = 1000;	/* 0 = natural mode */
module_param(stall_ms, int, 0600);
MODULE_PARM_DESC(stall_ms, "park the dump reader this long at the handoff (0=natural); implemented as udelay(10000) x N to dodge x86 __bad_udelay truncation for >20ms values");

static int unreg_delay_ms = 120;
module_param(unreg_delay_ms, int, 0600);

static int natural_secs = 90;
module_param(natural_secs, int, 0600);

static ulong ret_off = 0x370;
module_param(ret_off, ulong, 0600);
MODULE_PARM_DESC(ret_off, "return-address offset of the __srcu_read_lock call inside rtnl_dump_ifinfo");

static struct rtnl_link_ops *rops;	/* controlled mode only */
static atomic_t hits = ATOMIC_INIT(0);
static atomic_t parked = ATOMIC_INIT(0);
static atomic_t freed = ATOMIC_INIT(0);
static atomic_t rounds = ATOMIC_INIT(0);
static unsigned long base_addr;
static struct kprobe kp;
static int probe_live;
static struct task_struct *uthr;

static int stall_pre(struct kprobe *p, struct pt_regs *regs)
{
	unsigned long ra = *(unsigned long *)regs->sp;

	if (ra == base_addr + ret_off) {
		int h = atomic_inc_return(&hits);
		u64 t0 = ktime_to_ms(ktime_get());
		int i;

		atomic_set(&parked, 1);
		if (h <= 3)
			pr_warn("stall #%d: parking dump reader %d ms at handoff (ra=%lx == rtnl_dump_ifinfo+0x%lx) t=%llu\n",
				h, stall_ms, ra, ret_off, t0);
		for (i = 0; i < stall_ms / 10; i++)
			udelay(10000);
		if (h <= 3)
			pr_warn("stall #%d: park END t=%llu (held %llu ms)\n",
				h, ktime_to_ms(ktime_get()),
				ktime_to_ms(ktime_get()) - t0);
	} else if (ra > base_addr && ra < base_addr + 0x2000) {
		static atomic_t dbg;

		int d = atomic_inc_return(&dbg);

		if (d <= 8)
			pr_warn("near-caller #%d ra-off=0x%lx\n", d, ra - base_addr);
	}
	return 0;
}

static unsigned long sym_addr(const char *name)
{
	struct kprobe probe = { .symbol_name = name, };
	unsigned long addr = 0;

	if (register_kprobe(&probe) == 0) {
		addr = (unsigned long)probe.addr;
		unregister_kprobe(&probe);
	}
	return addr;
}

static int unreg_thr(void *unused)
{
	if (stall_ms > 0) {
		/* controlled: wait until the kprobe parked the dump reader */
		while (!atomic_read(&parked) && !kthread_should_stop())
			msleep(5);
		if (kthread_should_stop())
			return 0;
		msleep(unreg_delay_ms);

		rtnl_link_unregister(rops);
		/* protocol evidence: what did cleanup_srcu_struct leave behind?
		 * (rops itself is still allocated here, so these reads are safe) */
		pr_warn("post-unregister t=%llu: ops=%px srcu.srcu_sup=%px srcu.sda=%px srcu.srcu_ctrp=%px\n",
			ktime_to_ms(ktime_get()), rops, rops->srcu.srcu_sup, rops->srcu.sda,
			rops->srcu.srcu_ctrp);
		kfree(rops);
		atomic_set(&freed, 1);
		pr_warn("ops kfree()d (models module_memfree of the unloaded module); parked reader will resume on freed memory\n");
	} else {
		/* natural: hammer kzalloc/register/unregister/kfree (rmmod shape) */
		u64 t0 = ktime_to_ms(ktime_get());

		while (!kthread_should_stop() &&
		       ktime_to_ms(ktime_get()) - t0 < (u64)natural_secs * 1000) {
			struct rtnl_link_ops *o = kzalloc(sizeof(*o), GFP_KERNEL);

			if (!o)
				break;
			o->kind = "rtnlrace";
			if (rtnl_link_register(o) == 0) {
				rtnl_link_unregister(o);
				kfree(o);
			} else {
				kfree(o);
			}
			atomic_inc(&rounds);
			if ((atomic_read(&rounds) & 0x3ff) == 0)
				pr_warn("natural round %d\n", atomic_read(&rounds));
		}
		pr_warn("natural done: %d register/unregister/kfree rounds\n",
			atomic_read(&rounds));
	}
	return 0;
}

static int __init rtnlrace_init(void)
{
	int ret;

	if (stall_ms > 0) {
		rops = kzalloc(sizeof(*rops), GFP_KERNEL);
		if (!rops)
			return -ENOMEM;
		rops->kind = "rtnlrace";
		ret = rtnl_link_register(rops);
		if (ret) {
			pr_err("rtnl_link_register failed: %d\n", ret);
			kfree(rops);
			rops = NULL;
			return ret;
		}
		pr_warn("registered rtnl_link_ops kind=rtnlrace (%px); start: /nlr rtnlrace\n", rops);

		base_addr = sym_addr("rtnl_dump_ifinfo");
		if (!base_addr) {
			pr_err("cannot resolve rtnl_dump_ifinfo\n");
			return -EINVAL;
		}
		kp.symbol_name = "__srcu_read_lock";
		kp.pre_handler = stall_pre;
		ret = register_kprobe(&kp);
		if (ret) {
			pr_err("cannot register kprobe: %d\n", ret);
			return ret;
		}
		probe_live = 1;
		pr_warn("kprobe on __srcu_read_lock, park ra=rtnl_dump_ifinfo+0x%lx (%px)\n",
			ret_off, (void *)(base_addr + ret_off));
	}

	uthr = kthread_run(unreg_thr, NULL, "rtnlrace_unreg");
	if (IS_ERR(uthr))
		return PTR_ERR(uthr);
	pr_warn("armed: stall_ms=%d unreg_delay_ms=%d mode=%s\n", stall_ms,
		unreg_delay_ms, stall_ms > 0 ? "controlled" : "natural");
	return 0;
}

static void __exit rtnlrace_exit(void)
{
	if (uthr)
		kthread_stop(uthr);
	if (probe_live)
		unregister_kprobe(&kp);
	if (stall_ms > 0 && atomic_read(&freed) == 0 && rops) {
		rtnl_link_unregister(rops);
		kfree(rops);
	}
	pr_warn("module exit (hits=%d rounds=%d)\n", atomic_read(&hits),
		atomic_read(&rounds));
}

module_init(rtnlrace_init);
module_exit(rtnlrace_exit);
MODULE_LICENSE("GPL");

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

* wifi: wilc1000: SDIO/SPI remove destroys the srcu_struct  before wiphy_unregister() -- late cfg80211 callbacks write through  dangling srcu state (unfixed upstream; controlled + natural Oops)
       [not found] ` <2026102727-data-sequel-ce41@gregkh>
  2026-11-03 11:57   ` net: rtnetlink: rtnl_link_unregister() vs in-flight RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3 徐晗翔
@ 2026-11-03 12:07   ` 徐晗翔
  2026-11-22  7:39   ` io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race) 徐晗翔
  2 siblings, 0 replies; 7+ messages in thread
From: 徐晗翔 @ 2026-11-03 12:07 UTC (permalink / raw)
  To: ajay.kathat, claudiu.beznea; +Cc: linux-wireless, linux-kernel, netdev

[-- Attachment #1: Type: text/plain, Size: 4022 bytes --]

In wilc1000's SDIO/SPI remove path, the driver destroys its
srcu_struct (cleanup_srcu_struct at sdio.c:228-229, via
wlan_deinit_locks) BEFORE wiphy_unregister() tears down the wiphy --
so any cfg80211 callback that arrives late and holds only the wiphy
lock (which nl80211 releases before dispatching, nl80211.c:4303)
will execute srcu_read_lock()/srcu_read_unlock() on an already
destroyed srcu_struct whose backing percpu memory is freed: the
counter writes in __srcu_read_lock/unlock land on
__per_cpu_offset[cpu]+{0,16} -- the first bytes of the current
CPU's percpu area, corrupting whatever lives there.  I verified the
mechanism on a stock 7.3 KASAN kernel with a field/lock-faithful
simulator of the two sides: the controlled run pins the reader
inside the callback (holding only the simulated wiphy_lock), runs
the real cleanup_srcu_struct() underneath, then deliberately
re-allocates percpu memory at the freed sda address -- the reader's
subsequent srcu_read_lock increments a counter inside that
replacement object (read back as +1: cross-object percpu corruption
demonstrated); the natural run, with no instrumentation at all,
crashes the kernel in under one second of reader/init/cleanup churn
with a page-fault write Oops in __srcu_read_unlock+0x25 whose
disassembly state matches the dangling-state chain instruction for
instruction (RAX=0 -> sda==NULL, RSI=0x10, incq %gs:0x8(%rax,%rsi)
-> a write into the first 32 bytes of the CPU's percpu area).  The
fix is the ordering: wiphy_unregister() (which waits for the wiphy
srcu readers) must happen before cleanup_srcu_struct().  As far as I
can tell this is unfixed in mainline.

The detailed description:

* The ordering bug (Linux 7.3)
  drivers/net/wireless/microchip/wilc1000/sdio.c remove path (SPI
  variant identical): ... -> wilc_netdev_cleanup ->
  wlan_deinit_locks -> cleanup_srcu_struct(&wilc->srcu) (sdio.c:
  228-229), while the wiphy is still registered.  cfg80211 dispatch
  (e.g. set_wiphy_params, whose first statement is
  srcu_read_lock(cfg80211.c:803); likewise wilc_set_wakeup) holds
  only wiphy_lock -- rtnl is already released at nl80211.c:4303 --
  so the driver's remove path and a late callback share no lock.

* What the destroyed-srcu accesses do
  cleanup_srcu_struct() frees the sda percpu arrays (or leaks them
  into the WARN branch when a reader is caught inside, which is
  itself observable) and leaves srcu_ctrp dangling or the unlock
  path reading sda==NULL: __srcu_read_unlock's
  this_cpu_inc(&sdp->locks[...]) then computes GS-base+0x8(0,16) --
  a blind percpu write.  Both jumps of the hazard chain were
  demonstrated (see below).

* Evidence (stock 7.3 KASAN; simulator attached)
  wilcsim.c mirrors the real field/lock structure
  (sim wiphy_lock <-> wiphy_lock; reader parked at the callback's
  srcu_read_lock; remover executing the real cleanup_srcu_struct()
  without any of the reader's locks -- faithful to "no common lock"
  in the real paths):
  Controlled: cleanup completes with sda freed and ctrp dangling;
  a same-size alloc_percpu lands at the EXACT freed sda address
  (zero retries) carrying markers; the released reader's
  srcu_read_lock executes and the marker on cpu3 reads back
  ctr[0].locks=+1 -- the dangling counter write, captured inside
  the replacement object.
  Natural (no kprobe, reader lock/unlock loop vs init/cleanup
  churn): by round ~768 an interleaving hits: Oops 0002 (write
  fault), RIP __srcu_read_unlock+0x25, RAX=0, RSI=0x10, instruction
  65 48 ff 44 30 08 -- writing GS-base+0x18, i.e. inside the first
  32 bytes of the CPU's percpu area.  Kernel dead <1 s into the
  churn.  (Three WARNING: srcutree.c:696 events during the churn
  additionally show the remover catching readers mid-section -- the
  defensive leak branch.)
  Fidelity note: real wilc1000 hardware was not available; the
  simulator reproduces the mechanism (the exact srcu API calls and
  lock topology of the real two paths) on the real library code.


Regards,
Hanxiang Xu
xuhx@hust.edu.cn

[-- Attachment #2: wilcsim.c --]
[-- Type: text/plain, Size: 8436 bytes --]

// SPDX-License-Identifier: GPL-2.0+
/*
 * wilcsim.c - dynamic verification for the audit-report Case 2 (wilc1000):
 *
 *   wilc_sdio_remove()/wilc_bus_remove() run wilc_netdev_cleanup() (which
 *   ends in cleanup_srcu_struct(&wilc->srcu), cfg80211.c:1757) BEFORE
 *   wiphy_unregister() (sdio.c:228-229). While the wiphy is still
 *   registered, cfg80211 callbacks can still enter and several of them
 *   (set_wiphy_params cfg80211.c:803, wilc_set_wakeup :1626) take
 *   wl->srcu as their first statement, dispatched under wiphy_lock only
 *   (nl80211_set_wiphy releases rtnl at nl80211.c:4303 before the callback;
 *   SET_WOWLAN has no NEED_RTNL) - the remove path holds neither.
 *
 * This module reproduces the exact interleaving shape with a simulated
 * private struct (struct wilc equivalent) and a simulated wiphy_lock,
 * and makes the otherwise-silent post-cleanup writes OBSERVABLE:
 *
 * Controlled mode (default):
 *   reader kthread   = the cfg80211 callback: takes sim_wiphy_lock, "parks"
 *                      at the audited point (before srcu_read_lock), then
 *                      resumes on the destroyed srcu.
 *   remover kthread  = wilc_sdio_remove: with the reader parked (and NOT
 *                      holding any lock the remover needs - faithful),
 *                      cleanup_srcu_struct() frees srcu_usage + percpu sda.
 *   Then the percpu allocator is asked for a same-size allocation until it
 *   hands back EXACTLY the freed sda address (percpu block reuse), and the
 *   reader resumes: its stale srcu_ctrp this_cpu_inc lands inside the new
 *   object => directly readable cross-object percpu corruption (the
 *   audited harm chain link 1). The unlock path additionally writes at
 *   percpu offset 0/16 (link 2) because ssp->sda == NULL.
 *
 * Natural mode (natural_secs>0 & controlled=0): reader loops
 * lock/unlock and remover loops init/cleanup without any parking; the
 * post-cleanup unlock writes at percpu offset 0/16 corrupt the first
 * percpu symbol of the executing CPU -> expected rapid crash (severity
 * demonstration).
 */
#define pr_fmt(fmt) "WILCSIM: " fmt

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/srcu.h>
#include <linux/mutex.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/atomic.h>
#include <linux/delay.h>
#include <linux/cpumask.h>

struct sim_wl {
	struct mutex	wiphy_lock_sim;	/* models wiphy->mtx (nl80211 dispatch) */
	struct srcu_struct srcu;	/* models wl->srcu */
};

static int controlled = 1;
module_param(controlled, int, 0600);
MODULE_PARM_DESC(controlled, "1=controlled parking interleave, 0=natural hammer");

static int natural_secs = 30;
module_param(natural_secs, int, 0600);

static int reuse_tries = 128;
module_param(reuse_tries, int, 0600);

static struct sim_wl *wl;
static struct srcu_data __percpu *marker;	/* reallocated over freed sda */
static struct completion parked;
static struct completion go;
static struct completion reader_done;
static atomic_t natural_rounds = ATOMIC_INIT(0);
static atomic_t natural_warns = ATOMIC_INIT(0);

static long ctr_read(int cpu, int slot, int which)
{
	struct srcu_data *sd = per_cpu_ptr(marker, cpu);

	if (slot == 0 && which == 0)
		return atomic_long_read(&sd->srcu_ctrs[0].srcu_locks);
	if (slot == 0 && which == 1)
		return atomic_long_read(&sd->srcu_ctrs[0].srcu_unlocks);
	if (slot == 1 && which == 0)
		return atomic_long_read(&sd->srcu_ctrs[1].srcu_locks);
	return atomic_long_read(&sd->srcu_ctrs[1].srcu_unlocks);
}

static int reader_thr(void *unused)
{
	int cpu;

	if (controlled) {
		mutex_lock(&wl->wiphy_lock_sim);
		pr_info("reader parked inside callback (holds sim wiphy_lock; remove path needs neither lock)\n");
		complete(&parked);
		wait_for_completion(&go);

		cpu = smp_processor_id();
		{
			struct srcu_ctr __percpu *ctrp =
				READ_ONCE(wl->srcu.srcu_ctrp);
			int idx;
			long b00 = ctr_read(cpu, 0, 0), b01 = ctr_read(cpu, 0, 1);
			long b10 = ctr_read(cpu, 1, 0), b11 = ctr_read(cpu, 1, 1);

			pr_info("reader resumed: stale srcu_ctrp=%px (sda freed), executing srcu_read_lock on DESTROYED srcu\n",
				ctrp);
			idx = srcu_read_lock(&wl->srcu);
			/* NOTE: srcu_read_unlock() deliberately NOT executed in the
			 * controlled run: with ssp->sda == NULL it would write at
			 * percpu offset 0/16 (the first percpu symbol of this CPU)
			 * and could kill the evidence path itself; that write is
			 * demonstrated live by the wilcnat natural run instead. */
			pr_info("reader after lock (idx=%d): marker[cpu%d] deltas ctr[0].locks=%ld ctr[0].unlocks=%ld ctr[1].locks=%ld ctr[1].unlocks=%ld\n",
				idx, cpu,
				ctr_read(cpu, 0, 0) - b00,
				ctr_read(cpu, 0, 1) - b01,
				ctr_read(cpu, 1, 0) - b10,
				ctr_read(cpu, 1, 1) - b11);
			if (ctr_read(cpu, 0, 0) != b00 || ctr_read(cpu, 1, 0) != b10)
				pr_warn("CROSS-OBJECT PERCPU CORRUPTION OBSERVED: stale srcu_ctrp write landed inside the reallocated percpu object\n");
		}
		mutex_unlock(&wl->wiphy_lock_sim);
		complete(&reader_done);
	} else {
		while (!kthread_should_stop()) {
			int idx;

			mutex_lock(&wl->wiphy_lock_sim);
			idx = srcu_read_lock(&wl->srcu);
			srcu_read_unlock(&wl->srcu, idx);
			mutex_unlock(&wl->wiphy_lock_sim);
			cond_resched();
		}
	}
	return 0;
}

static int remove_thr(void *unused)
{
	struct srcu_data __percpu *old_sda;
	int i;

	if (controlled) {
		wait_for_completion(&parked);

		old_sda = wl->srcu.sda;
		pr_info("remove path: cleanup_srcu_struct while reader parked in callback (pre sda=%px ctrp=%px)\n",
			old_sda, wl->srcu.srcu_ctrp);
		cleanup_srcu_struct(&wl->srcu);
		pr_info("cleanup done: srcu.sda=%px srcu.srcu_sup=%px (NULL=NULL => freed) srcu_ctrp=%px (stale, never reset)\n",
			wl->srcu.sda, wl->srcu.srcu_sup, wl->srcu.srcu_ctrp);

		/* reallocate over the freed percpu block: same size, retry until
		 * the allocator hands back the exact address */
		for (i = 0; i < reuse_tries; i++) {
			marker = alloc_percpu(struct srcu_data);
			if (!marker) {
				pr_err("alloc_percpu failed\n");
				break;
			}
			if (marker == old_sda)
				break;
			free_percpu(marker);
			marker = NULL;
		}
		if (marker == old_sda && marker)
			pr_info("marker reallocated at EXACT freed sda address %px after %d tries\n",
				marker, i);
		else
			pr_warn("exact reuse not achieved (marker=%px old=%px tries=%d); chunk-level overlap only\n",
				marker, old_sda, i);
		complete(&go);
		wait_for_completion(&reader_done);

		/* full per-cpu marker scan */
		for_each_possible_cpu(i) {
			long v0 = ctr_read(i, 0, 0), v1 = ctr_read(i, 1, 0);

			if (v0 || v1)
				pr_warn("marker cpu%d: ctr[0].locks=%ld ctr[1].locks=%ld\n", i, v0, v1);
		}
		pr_info("controlled interleave complete\n");
	} else {
		u64 t0 = ktime_to_ms(ktime_get());

		while (ktime_to_ms(ktime_get()) - t0 < (u64)natural_secs * 1000 &&
		       !kthread_should_stop()) {
			cleanup_srcu_struct(&wl->srcu);	/* may WARN+leak if reader inside */
			if (atomic_read(&natural_warns) > 4096)
				break;
			init_srcu_struct(&wl->srcu);
			atomic_inc(&natural_rounds);
			if ((atomic_read(&natural_rounds) & 0xff) == 0)
				pr_warn("natural round %d\n", atomic_read(&natural_rounds));
		}
		pr_warn("natural done: %d init/cleanup rounds\n",
			atomic_read(&natural_rounds));
	}
	return 0;
}

static int __init wilcsim_init(void)
{
	struct task_struct *r, *m;
	int ret;

	wl = kzalloc(sizeof(*wl), GFP_KERNEL);
	if (!wl)
		return -ENOMEM;
	mutex_init(&wl->wiphy_lock_sim);
	ret = init_srcu_struct(&wl->srcu);
	if (ret) {
		kfree(wl);
		return ret;
	}
	init_completion(&parked);
	init_completion(&go);
	init_completion(&reader_done);

	r = kthread_run(reader_thr, NULL, "wilcsim_reader");
	m = kthread_run(remove_thr, NULL, "wilcsim_remove");
	if (IS_ERR(r) || IS_ERR(m))
		return IS_ERR(r) ? PTR_ERR(r) : PTR_ERR(m);
	pr_warn("armed: mode=%s\n", controlled ? "controlled" : "natural");
	return 0;
}

static void __exit wilcsim_exit(void)
{
	/* natural mode: threads self-terminate after natural_secs; controlled:
	 * both completions are done. cleanup may leak sup intentionally. */
	if (wl) {
		/* best effort: if srcu still live, clean it */
		if (wl->srcu.srcu_sup)
			cleanup_srcu_struct(&wl->srcu);
		if (marker)
			free_percpu(marker);
		kfree(wl);
	}
	pr_warn("module exit (natural_rounds=%d)\n", atomic_read(&natural_rounds));
}

module_init(wilcsim_init);
module_exit(wilcsim_exit);
MODULE_LICENSE("GPL");

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

* Re: net: rtnetlink: rtnl_link_unregister() vs in-flight RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3
  2026-11-03 11:57   ` net: rtnetlink: rtnl_link_unregister() vs in-flight RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3 徐晗翔
@ 2026-11-03 15:49     ` Eric Dumazet
  2026-11-04 15:03     ` Sasha Levin
  1 sibling, 0 replies; 7+ messages in thread
From: Eric Dumazet @ 2026-11-03 15:49 UTC (permalink / raw)
  To: 徐晗翔
  Cc: davem, kuba, pabeni, netdev, linux-kernel, stable

Le mar. 3 nov. 2026 à 12:57, 徐晗翔 <xuhx@hust.edu.cn> a écrit :
>
> On v7.3, rtnl_link_unregister() removes the rtnl_link_ops from the
> global list and immediately destroys the embedded srcu_struct and
> frees the ops memory -- a concurrent RTM_GETLINK dump that already
> found the ops (rtnl_link_ops_get(), rtnetlink.c:599 hand-off inside
> an RCU read critical section at :595) but has not yet taken
> ops->srcu will, after the free, execute __srcu_read_lock() /
> __srcu_read_unlock() on freed memory: two reads of the destroyed
> object (ssp->srcu_ctrp, ssp->sda) whose subsequent percpu counter
> writes land wherever the freed percpu pointers point -- for a module
> rtnl_link_ops, the ops (and its srcu) live in module memory, so
> module_memfree() is the freeing side.  Upstream already fixed this
> with a synchronize_rcu() in rtnl_link_unregister() (the patch with
> Fixes: 6b57ff21a310; its own comment: "Wait for rtnl_link_ops_get()
> readers that found ops but have not yet taken ops->srcu").  v7.3
> does not contain it.  I verified both sides on a stock 7.3 KASAN
> kernel: parking a real dump reader (driven by an ordinary
> RTM_GETLINK + IFLA_LINKINFO dump request) exactly at the :599
> hand-off and unregistering+freeing underneath produces three KASAN
> slab-use-after-free reports (__srcu_read_lock+0xe, +0x25,
> __srcu_read_unlock+0x1a; bad address = ops+0x10 = ops->srcu); and
> rebuilding the SAME kernel with ONLY the upstream one-line fix
> flips the outcome to zero reports, with the kfree demonstrably
> delayed until the parked reader left its RCU section.  Natural
> hammering did not hit (the hand-off window is ~100 ns against a
> ~4 ms unregister -- it needs a preempted/preemptible-RCU reader),
> which matches the fix's own reasoning; the controlled run models
> exactly that preemption.  The purpose of this mail is to support
> the fix's propagation: trees still carrying the unfixed
> rtnl_link_unregister() keep a cross-CPU UAF (write) plus potential
> freed-module execution reachable by unprivileged netlink dumps
> racing a module unload.
>
>
> The detailed description:
>
> * The gap (v7.3, net/core/rtnetlink.c)
>   rtnl_dump_ifinfo() runs lockless for dumps
>   (RTNL_FLAG_DUMP_UNLOCKED), takes rcu_read_lock() at :595, calls
>   linkinfo_to_kind_ops() -> rtnl_link_ops_get() which returns the
>   ops pointer at :599, and only then takes ops->srcu
>   (srcu_read_lock) to call ops->dumpit.  rtnl_link_unregister()
>   holds rtnl_mutex, removes the ops from the list, calls
>   cleanup_srcu_struct(&ops->srcu) and returns to the module, whose
>   exit then frees the module memory.  Nothing between the :599
>   hand-off and the srcu_read_lock is waited for on the unregister
>   side in 7.3 -- hence the fix's synchronize_rcu().
>
> * Evidence (stock 7.3 KASAN, QEMU; A/B on the one-line fix;
>   reproducers attached)
>   rtnlrace.c registers a kzalloc'd rtnl_link_ops (kind "rtnlrace"),
>   parks a dump reader by kprobe at the exact hand-off (return
>   address rtnl_dump_ifinfo+0x374, ENDBR-adjusted), and unregisters
>   + kfrees from another thread (modeling module_exit ->
>   module_memfree).  nlr (userspace) sends the IFLA_LINKINFO dump
>   request that drives the reader path.
>   Defect kernel (stock 7.3):
>     park t=127041 (1004 ms) -> unregister+kfree at t=127249 (park
>     +208 ms, reader still parked 792 ms) -> park ends t=128045:
>     BUG: KASAN: slab-use-after-free in __srcu_read_lock+0xe
>     BUG: KASAN: slab-use-after-free in __srcu_read_lock+0x25
>     BUG: KASAN: slab-use-after-free in __srcu_read_unlock+0x1a
>       read stack: __srcu_read_lock <- rtnl_dump_ifinfo+0x374 <-
>         rtnl_dumpit <- netlink_dump <- rtnetlink_rcv_msg (task nlr)
>       bad address = object+0x10 == ops->srcu (matches the
>       disassembly lea 0x10(%rbx))
>       alloc: insmod kzalloc;  free: unregister thread kfree
>   Fixed kernel (same sources, ONLY the upstream synchronize_rcu()
>   added to rtnl_link_unregister()):
>     park t=191305 -> park ENDS t=192306 -> unregister+kfree
>     t=192307 -- the order literally inverts -- zero KASAN reports,
>     dump completes with zero errors.  Same module, same parking.
>   Natural runs (three samplings, up to ~267k dumps/reader plus
>   6-CPU preemption spinners): zero hits; the window arithmetic
>   (~100 ns hand-off vs ~4 ms unregister) explains it, and the
>   controlled park models precisely the preemption the upstream
>   fix's comment describes.
>

What is the point of this email ? This looks like LLM slope to me.

I think we have far more serious bugs to fix.

3b70edea393d was tagged stable+noautosel on purpose: the race needs
a module unload (CAP_SYS_MODULE in init_user_ns) to line up with a
~100ns window, which your report also shows you could not hit
without a kprobe. It is not reachable by an unprivileged user alone.

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

* Re: net: rtnetlink: rtnl_link_unregister() vs in-flight RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3
  2026-11-03 11:57   ` net: rtnetlink: rtnl_link_unregister() vs in-flight RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3 徐晗翔
  2026-11-03 15:49     ` Eric Dumazet
@ 2026-11-04 15:03     ` Sasha Levin
  1 sibling, 0 replies; 7+ messages in thread
From: Sasha Levin @ 2026-11-04 15:03 UTC (permalink / raw)
  To: davem, edumazet, kuba, pabeni
  Cc: Sasha Levin, netdev, linux-kernel, stable,
	徐晗翔

On 2026-11-03, 徐晗翔 <xuhx@hust.edu.cn> wrote:
> Upstream already fixed this with a synchronize_rcu() in rtnl_link_unregister()

Queued for 7.3 and 6.18, thanks.

-- 
Thanks,
Sasha

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

* io_uring/zcrx: copy statistics lose updates when one ifq is  shared by multiple rings (Data race)
       [not found] ` <2026102727-data-sequel-ce41@gregkh>
  2026-11-03 11:57   ` net: rtnetlink: rtnl_link_unregister() vs in-flight RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3 徐晗翔
  2026-11-03 12:07   ` wifi: wilc1000: SDIO/SPI remove destroys the srcu_struct before wiphy_unregister() -- late cfg80211 callbacks write through dangling srcu state (unfixed upstream; controlled + natural Oops) 徐晗翔
@ 2026-11-22  7:39   ` 徐晗翔
  2026-11-23 13:50     ` Pavel Begunkov
  2 siblings, 1 reply; 7+ messages in thread
From: 徐晗翔 @ 2026-11-22  7:39 UTC (permalink / raw)
  To: asml.silence, axboe; +Cc: io-uring, netdev, linux-kernel

[-- Attachment #1: Type: text/plain, Size: 8235 bytes --]

An io_uring zero-copy RX ifq can be exported by one ring and imported by
another.  Both rings then perform receive-zc on their own TCP sockets,
but they share the same struct io_zcrx_ifq and therefore the same
ifq->notif_stats.  The statistics update is not atomic:

    static void zcrx_stat_add(__u64 *p, s64 v)
    {
        WRITE_ONCE(*p, READ_ONCE(*p) + v);
    }

io_uring/zcrx.c:1337-1340.  It is called for copy_count and copy_bytes
from io_zcrx_copy_frag() at zcrx.c:1770-1771.  There is no ifq-level
lock in this path.  lock_sock() in io_zcrx_tcp_recvmsg() is per TCP
socket, the ring's uring_lock is per ring, alloc_lock only protects
fallback niov allocation and is released before the copy, and
ctx_lock/notification is taken after the statistics update and is not
involved when event_desc.type_mask == 0.  Two CPUs can therefore read
the same old value, add their own increments, and write back the same
new value: one update is lost.

The effect is limited to the UAPI cumulative copy statistics
(struct zcrx_stats at include/uapi/linux/io_uring/zcrx.h:83-86).  The
values are user-mappable diagnostic data; the race does not control
buffer lifetime, DMA, reference counts, or packet contents.  


The detailed description:

* Test environment / affected version

  Linux 7.3.0 (gcc 13.3.0, GNU ld 2.42) #6 SMP PREEMPT_DYNAMIC,
  vanilla mainline 7.3, x86_64 QEMU/KVM guest, 8 vCPUs, 4 GiB,
  CONFIG_KASAN=y.  The tested io_uring/zcrx.c is byte-identical to
  v7.3: SHA-256
  6e4e9828c84179b7a1877f0f843cc230f865d42665cbd0d43441493c67c70980.
  The kernel was not modified; no delay or other amplification was
  inserted.  bzImage SHA-256:
  cdc1122bc0bdd2c65f92650bef919ff7b1f15d42bf64e3b0b079352fccf7b104.
  Relevant config includes CONFIG_IO_URING=y, CONFIG_IO_URING_ZCRX=y
  and CONFIG_KASAN=y.

* Mechanism

  Shared object and two writers:

    - Ring A registers a ZCRX_REG_NODEV ifq with a user-memory area and
      a stats-only event descriptor: event_desc.flags =
      ZCRX_EVENT_DESC_FLAG_STATS and event_desc.type_mask = 0.  The
      stats pointer is validated and stored at zcrx.c:935-960 (pointer
      at 956, memset at 957).  Because type_mask is zero,
      zcrx_set_ring_ctx() is not called (zcrx.c:1092-1093) and
      master_ctx is NULL; this is valid and statistics still update.
    - A exports the ifq with ZCRX_CTRL_EXPORT.  zcrx_export() checks
      that the control fields are zero and increments refs and
      user_refs at zcrx.c:805-806, attaches the original ifq to the
      [zcrx] file at 808-809, and installs an fd.
    - Ring B imports the same ifq with ZCRX_REG_IMPORT.  import_zcrx()
      requires DEFER_TASKRUN plus CQE32 or CQE_MIXED, rejects
      nonzero if_rxq/rq_entries/area_ptr/region_ptr/event_desc, takes
      the same ifq at zcrx.c:861, increments refs/user_refs at 862-863,
      and stores it in B's xarray at 880.
    - A and B each submit a multishot IORING_OP_RECV_ZC on a different
      TCP socket.  A's and B's recv paths can execute
      io_zcrx_copy_frag() concurrently.

  The missing serialization:

    - zcrx_stat_add() is a plain load-add-store, not an atomic RMW.
    - lock_sock(sk) at zcrx.c:1927 only serializes operations on one
      socket; A and B use different sockets.
    - uring_lock is per ring and does not cross rings.
    - alloc_lock at zcrx.c:1663 only covers io_alloc_fallback_niov();
      it is not held during the copy or the statistics update.
    - ctx_lock at zcrx.c:1351 protects notification state and
      master_ctx, is taken after the statistics update, and is not
      reached at all for type_mask == 0.
    - no pp_lock or rq.lock is held by the copy path.

  Minimal interleaving for one field:

    CPU 0: read copy_bytes == V
    CPU 1: read copy_bytes == V
    CPU 0: write V + len0
    CPU 1: write V + len1     (len0 is lost)

  copy_count has the same pattern with v = 1.  The final values can be
  lower than the number/bytes of data CQEs actually delivered, and the
  two fields can be mutually inconsistent.

  The paged-fragment requirement is important: the linear skb head is
  handled by io_zcrx_copy_chunk() (zcrx.c:1710-1758) and does not
  update stats.  A non-net_iov paged fragment enters
  io_zcrx_copy_frag() through io_zcrx_recv_frag() at zcrx.c:1785-1786,
  which is where zcrx_stat_add() is called.  A pure linear send may
  therefore produce CQEs without exercising the race.

* Trigger model

  Requirements:

    1. Two rings, each created with DEFER_TASKRUN, SINGLE_ISSUER and
       CQE32 or CQE_MIXED (the io_uring_setup requirement for
       DEFER_TASKRUN is in io_uring/io_uring.c:2832-2833).
    2. Ring A has a stat-enabled NODEV ifq with a user-memory area and
       a valid stats_offset; event_desc.type_mask may be zero.
    3. A exports the ifq and B imports it, so both use the same ifq and
       the same notif_stats address.
    4. A and B receive on different TCP sockets (different lock_sock
       instances).
    5. Paged non-net_iov skb fragments enter io_zcrx_copy_frag(); a
       sendfile()/splice/MSG_ZEROCOPY style sender on loopback is
       sufficient in the reproducer.
    6. The two updates overlap in the load-add-store window.

  No special hardware is needed for the NODEV path; a loopback TCP pair
  is enough.  The existing reproducer uses two independent loopback
  connections and two sender threads.

* Reproducer (attached: zcrx_verify.c) and results on 7.3

  zcrx_verify.c is a self-contained raw-syscall program; no liburing is
  required.  It creates two rings A/B, registers the NODEV ifq on A,
  exports it, imports it on B, drives one multishot IORING_OP_RECV_ZC
  per ring, returns each data CQE's rcqe->off as an RQE, and calls
  IORING_REGISTER_ZCRX_CTRL with ZCRX_CTRL_FLUSH_RQ on the owning ring.
  FLUSH_RQ is required on the NODEV path: there is no page_pool
  automatic refill, so without it the area is exhausted and the run
  stops.  FLUSH_RQ must be issued by the thread that owns the ring
  (otherwise the kernel returns -EEXIST).

  Build:

      gcc -static -O2 -g -pthread -Wall -Wextra \
        -Ilinux-7.3/include/uapi -Ilinux-7.3/include \
        -o zcrx_verify zcrx_verify.c

  Run: boot the 7.3 KASAN bzImage under QEMU/KVM with a custom
  initramfs whose /init runs /zcrx_verify, with 8 vCPUs and 4 GiB.
  The program takes the run time in seconds as its argument.  The
  dual-ring log was captured with a 0-error clean run; SINGLE=1 runs
  the same binary with only ring A as a control.

  Results (unmodified v7.3, no test delay):

    single ring, zcrx-single3.log:
      data_cqes = 223000, data_bytes = 859635712
      copy_count = 223000, copy_bytes = 859635712
      delta_count = 0, delta_bytes = 0

    dual ring, zcrx-final-clean.log (0 error CQEs):
      data_cqes = 76888, data_bytes = 296353792
      copy_count = 76863, copy_bytes = 296243359
      delta_count = -25, delta_bytes = -110433

    additional dual-ring trials:
      -8245 bytes / -3 count, -24470 bytes / -6 count,
      -77824 bytes / -17 count

  The single-ring control is exact at 223,000 CQEs / 859 MB, so the
  accounting convention is consistent and there is no systemic
  linear-head or CQ-loss bias in this test.  The dual-ring runs are
  consistently negative; the clean run has zero error CQEs and still
  loses 110,433 bytes and 25 count increments.  copy_count counts
  per-fragment updates while the data CQE count is per completed
  buffer, so the count delta is not expected to be numerically equal
  to the CQE delta; copy_bytes is the primary signal.  No KASAN
  report, WARN or Oops was observed.




* Suggested direction 

  Serialize the two updates per ifq, e.g. add a spinlock_t stats_lock
  to struct io_zcrx_ifq, initialize it in io_zcrx_ifq_alloc(), and
  hold it around both zcrx_stat_add() calls in io_zcrx_copy_frag(),
  releasing it before zcrx_send_notif().  A lockless alternative is to
  keep private atomic64 counters and publish a consistent snapshot, or
  to document the fields as best-effort.  READ_ONCE()/WRITE_ONCE() alone
  do not make the read-modify-write atomic and do not fix the lost
  update.


  Please keep me in Cc; I am not subscribed to the lists.

Regards,
Hanxiang Xu
xuhx@hust.edu.cn

[-- Attachment #2: zcrx_verify.c --]
[-- Type: text/plain, Size: 15077 bytes --]

// Test-only PoC for io_uring ZCRX shared-ifq copy statistics lost update.
// Runs in the verification VM as root. Uses raw syscalls (no liburing).
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <linux/io_uring.h>
#include <linux/io_uring/zcrx.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <net/if.h>

#ifndef __NR_io_uring_setup
#define __NR_io_uring_setup 425
#endif
#ifndef __NR_io_uring_enter
#define __NR_io_uring_enter 426
#endif
#ifndef __NR_io_uring_register
#define __NR_io_uring_register 427
#endif

#define PAGE 4096UL
#define AREA_PAGES 16384
#define AREA_SIZE (PAGE * AREA_PAGES)
#define REGION_SIZE 262144
#define RQ_ENTRIES 4096
#define STATS_OFF 131072
#define CQE_SIZE 32

struct ring {
    int fd;
    unsigned *sq_head, *sq_tail, *sq_mask, *sq_array;
    struct io_uring_sqe *sqes;
    unsigned *cq_head, *cq_tail, *cq_mask;
    char *cqes;
    unsigned entries;
};

static int io_uring_setup(unsigned e, struct io_uring_params *p) { return syscall(__NR_io_uring_setup, e, p); }
static int io_uring_enter(int fd, unsigned to_submit, unsigned min_complete, unsigned flags) {
    return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, NULL, 0);
}
static int io_uring_register(int fd, unsigned op, void *arg, unsigned nr) {
    return syscall(__NR_io_uring_register, fd, op, arg, nr);
}

static int setup_ring(struct ring *r, unsigned entries, unsigned flags)
{
    struct io_uring_params p;
    memset(&p, 0, sizeof(p));
    p.flags = flags;
    r->fd = io_uring_setup(entries, &p);
    if (r->fd < 0) { perror("io_uring_setup"); return -1; }
    r->entries = p.sq_entries;
    size_t sq_sz = p.sq_off.array + p.sq_entries * sizeof(unsigned);
    size_t cq_sz = p.cq_off.cqes + p.cq_entries * CQE_SIZE;
    size_t map_sz = sq_sz > cq_sz ? sq_sz : cq_sz;
    char *base = mmap(NULL, map_sz, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE, r->fd, IORING_OFF_SQ_RING);
    if (base == MAP_FAILED) { perror("mmap sq"); return -1; }
    char *cqbase;
    if (p.features & IORING_FEAT_SINGLE_MMAP) {
        cqbase = base;
    } else {
        cqbase = mmap(NULL, cq_sz, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_POPULATE, r->fd, IORING_OFF_CQ_RING);
        if (cqbase == MAP_FAILED) { perror("mmap cq"); return -1; }
    }
    r->sq_head = (unsigned *)(base + p.sq_off.head);
    r->sq_tail = (unsigned *)(base + p.sq_off.tail);
    r->sq_mask = (unsigned *)(base + p.sq_off.ring_mask);
    r->sq_array = (unsigned *)(base + p.sq_off.array);
    r->sqes = mmap(NULL, p.sq_entries * sizeof(struct io_uring_sqe), PROT_READ|PROT_WRITE,
                   MAP_SHARED|MAP_POPULATE, r->fd, IORING_OFF_SQES);
    if (r->sqes == MAP_FAILED) { perror("mmap sqes"); return -1; }
    r->cq_head = (unsigned *)(cqbase + p.cq_off.head);
    r->cq_tail = (unsigned *)(cqbase + p.cq_off.tail);
    r->cq_mask = (unsigned *)(cqbase + p.cq_off.ring_mask);
    r->cqes = cqbase + p.cq_off.cqes;
    printf("ring fd=%d entries=%u cq=%u feat=0x%x single=%d\n", r->fd, p.sq_entries, p.cq_entries,
           p.features, !!(p.features & IORING_FEAT_SINGLE_MMAP));
    return 0;
}

static void submit_recvzc(struct ring *r, int sock, unsigned ifq_idx, uint64_t ud)
{
    unsigned tail = __atomic_load_n(r->sq_tail, __ATOMIC_RELAXED);
    unsigned idx = tail & *r->sq_mask;
    struct io_uring_sqe *sqe = &r->sqes[idx];
    memset(sqe, 0, sizeof(*sqe));
    sqe->opcode = IORING_OP_RECV_ZC;
    sqe->fd = sock;
    sqe->len = 0;
    sqe->ioprio = IORING_RECV_MULTISHOT;
    sqe->zcrx_ifq_idx = ifq_idx;
    sqe->user_data = ud;
    r->sq_array[idx] = idx;
    __atomic_store_n(r->sq_tail, tail + 1, __ATOMIC_RELEASE);
    int ret = io_uring_enter(r->fd, 1, 0, 0);
    if (ret < 0) fprintf(stderr, "enter submit: %s\n", strerror(errno));
}

static int make_loop_pair(int *rx, int *tx)
{
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if (lfd < 0) { perror("socket l"); return -1; }
    int one = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    struct sockaddr_in a; memset(&a, 0, sizeof(a));
    a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); a.sin_port = 0;
    if (bind(lfd, (void *)&a, sizeof(a)) < 0) { perror("bind"); return -1; }
    if (listen(lfd, 8) < 0) { perror("listen"); return -1; }
    socklen_t alen = sizeof(a);
    if (getsockname(lfd, (void *)&a, &alen) < 0) { perror("getsockname"); return -1; }
    int c = socket(AF_INET, SOCK_STREAM, 0);
    if (c < 0) { perror("socket c"); return -1; }
    if (connect(c, (void *)&a, sizeof(a)) < 0) { perror("connect"); return -1; }
    int s = accept(lfd, NULL, NULL);
    if (s < 0) { perror("accept"); return -1; }
    close(lfd);
    setsockopt(c, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
    setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
    *rx = c; *tx = s;
    return 0;
}

struct zcrx {
    struct ring ring;
    unsigned ifq_id;
    unsigned rq_entries;
    uint64_t area_token;
    char *region;
    uint32_t *rq_tail;
    struct io_uring_zcrx_rqe *rqes;
    uint64_t *stats;
    pthread_mutex_t *rq_lock;
    pthread_mutex_t rq_lock_storage;
    int ctrl_fd;
    volatile int *stop;
    uint64_t cqes_data;
    uint64_t bytes_data;
    int errors;
};

static void return_cqe(struct zcrx *z, struct io_uring_cqe *cqe)
{
    struct io_uring_zcrx_cqe *rcqe = (struct io_uring_zcrx_cqe *)(cqe + 1);
    uint64_t off = rcqe->off;
    int res = cqe->res;
    if (res <= 0) return;
    pthread_mutex_lock(z->rq_lock);
    uint32_t tail = __atomic_load_n(z->rq_tail, __ATOMIC_RELAXED);
    struct io_uring_zcrx_rqe *rqe = &z->rqes[tail & (z->rq_entries - 1)];
    rqe->off = (off & ~IORING_ZCRX_AREA_MASK) | z->area_token;
    rqe->len = (uint32_t)res;
    rqe->__pad = 0;
    __atomic_store_n(z->rq_tail, tail + 1, __ATOMIC_RELEASE);
    struct zcrx_ctrl ctrl; memset(&ctrl, 0, sizeof(ctrl));
    ctrl.zcrx_id = z->ifq_id;
    ctrl.op = ZCRX_CTRL_FLUSH_RQ;
    int ret = io_uring_register(z->ctrl_fd, IORING_REGISTER_ZCRX_CTRL, &ctrl, 0);
    if (ret < 0) {
        if (z->errors++ < 5) fprintf(stderr, "flush err: %s\n", strerror(errno));
    }
    pthread_mutex_unlock(z->rq_lock);
}

static void *recv_loop(void *arg)
{
    struct zcrx *z = arg;
    unsigned head = __atomic_load_n(z->ring.cq_head, __ATOMIC_RELAXED);
    while (!*z->stop) {
        int ret = io_uring_enter(z->ring.fd, 0, 0, IORING_ENTER_GETEVENTS);
        if (ret < 0) {
            if (errno == EINTR || errno == EAGAIN) { usleep(50); continue; }
            fprintf(stderr, "enter wait: %s\n", strerror(errno));
            usleep(50);
            continue;
        }
        unsigned tail = __atomic_load_n(z->ring.cq_tail, __ATOMIC_ACQUIRE);
        while (head != tail) {
            struct io_uring_cqe *cqe = (struct io_uring_cqe *)(z->ring.cqes + (head & *z->ring.cq_mask) * CQE_SIZE);
            if (cqe->res > 0) {
                z->cqes_data++;
                z->bytes_data += (uint64_t)cqe->res;
                return_cqe(z, cqe);
            } else if (cqe->res < 0 && z->errors++ < 5) {
                fprintf(stderr, "cqe res=%d flags=0x%x\n", cqe->res, cqe->flags);
            }
            head++;
        }
        __atomic_store_n(z->ring.cq_head, head, __ATOMIC_RELEASE);
        usleep(50);
    }
    return NULL;
}

struct sender_arg { int fd; int file_fd; volatile int *stop; uint64_t bytes; };
static void *send_loop(void *arg)
{
    struct sender_arg *s = arg;
    char buf[65536];
    off_t off = 0;
    while (!*s->stop) {
        ssize_t n = sendfile(s->fd, s->file_fd, &off, sizeof(buf));
        if (n > 0) { s->bytes += n; continue; }
        if (n < 0 && (errno == EAGAIN || errno == EINTR)) continue;
        off = 0;
        if (n == 0) continue;
        break;
    }
    return NULL;
}

static void bring_lo_up(void)
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct ifreq ifr; memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, "lo");
    if (ioctl(fd, SIOCGIFFLAGS, &ifr) == 0) {
        ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
        ioctl(fd, SIOCSIFFLAGS, &ifr);
    }
    close(fd);
}

static int make_data_file(void)
{
    int fd = open("/tmp/zcrx-data", O_CREAT|O_RDWR|O_TRUNC, 0600);
    if (fd < 0) { perror("open data"); return -1; }
    char *buf = malloc(1 << 20);
    if (!buf) return -1;
    for (int i = 0; i < (1 << 20); i++) buf[i] = (char)(i * 7 + 1);
    if (write(fd, buf, 1 << 20) != (1 << 20)) { perror("write data"); return -1; }
    free(buf);
    lseek(fd, 0, SEEK_SET);
    return fd;
}

struct b_arg {
    struct zcrx *z;
    int export_fd;
    int rx;
    unsigned flags;
    volatile int *ready;
};

static void *b_thread(void *arg)
{
    struct b_arg *a = arg;
    struct zcrx *z = a->z;
    if (setup_ring(&z->ring, 4096, a->flags) < 0) { *a->ready = -1; return NULL; }
    struct io_uring_zcrx_ifq_reg ireg; memset(&ireg, 0, sizeof(ireg));
    ireg.if_idx = a->export_fd; ireg.flags = ZCRX_REG_IMPORT;
    int r = io_uring_register(z->ring.fd, IORING_REGISTER_ZCRX_IFQ, &ireg, 1);
    if (r < 0) { fprintf(stderr, "import: %s\n", strerror(errno)); *a->ready = -1; return NULL; }
    z->ifq_id = ireg.zcrx_id;
    z->ctrl_fd = z->ring.fd;
    submit_recvzc(&z->ring, a->rx, z->ifq_id, 0xBBBB);
    *a->ready = 1;
    recv_loop(z);
    return NULL;
}

struct stop_arg { volatile int *stop; int fds[4]; int secs; };
static void *timer_thread(void *arg)
{
    struct stop_arg *s = arg;
    sleep(s->secs);
    *s->stop = 1;
    for (int i = 0; i < 4; i++) if (s->fds[i] >= 0) shutdown(s->fds[i], SHUT_RDWR);
    return NULL;
}

int main(int argc, char **argv)
{
    int secs = argc > 1 ? atoi(argv[1]) : 8;
    int single = getenv("SINGLE") != NULL;
    signal(SIGPIPE, SIG_IGN);
    bring_lo_up();

    /* Ring A: owns the ifq, stats-only, NODEV, user area. */
    struct ring ra;
    unsigned flags = IORING_SETUP_CQE32 | IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN;
    if (setup_ring(&ra, 4096, flags) < 0) return 1;

    char *region = mmap(NULL, REGION_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE, -1, 0);
    if (region == MAP_FAILED) { perror("mmap region"); return 1; }
    memset(region, 0, REGION_SIZE);
    uint64_t *stats = (uint64_t *)(region + STATS_OFF);
    char *area_mem;
    if (posix_memalign((void **)&area_mem, PAGE, AREA_SIZE)) { perror("posix_memalign"); return 1; }
    memset(area_mem, 0x5a, AREA_SIZE);

    struct io_uring_region_desc rd; memset(&rd, 0, sizeof(rd));
    rd.user_addr = (uint64_t)region; rd.size = REGION_SIZE; rd.flags = IORING_MEM_REGION_TYPE_USER;
    struct io_uring_zcrx_area_reg area; memset(&area, 0, sizeof(area));
    area.addr = (uint64_t)area_mem; area.len = AREA_SIZE;
    struct zcrx_event_desc ev; memset(&ev, 0, sizeof(ev));
    ev.type_mask = 0; ev.flags = ZCRX_EVENT_DESC_FLAG_STATS; ev.stats_offset = STATS_OFF;
    struct io_uring_zcrx_ifq_reg reg; memset(&reg, 0, sizeof(reg));
    reg.rq_entries = RQ_ENTRIES; reg.flags = ZCRX_REG_NODEV;
    reg.area_ptr = (uint64_t)&area; reg.region_ptr = (uint64_t)&rd; reg.event_desc = (uint64_t)&ev;
    int ret = io_uring_register(ra.fd, IORING_REGISTER_ZCRX_IFQ, &reg, 1);
    if (ret < 0) { fprintf(stderr, "register ifq: %s\n", strerror(errno)); return 1; }
    printf("IFQ registered id=%u rx_buf_len=%u rqes_off=%u area_token=%#llx\n",
           reg.zcrx_id, reg.rx_buf_len, reg.offsets.rqes,
           (unsigned long long)area.rq_area_token);

    struct zcrx_ctrl ctrl; memset(&ctrl, 0, sizeof(ctrl));
    ctrl.zcrx_id = reg.zcrx_id; ctrl.op = ZCRX_CTRL_EXPORT;
    ret = io_uring_register(ra.fd, IORING_REGISTER_ZCRX_CTRL, &ctrl, 0);
    if (ret < 0) { fprintf(stderr, "export: %s\n", strerror(errno)); return 1; }
    int export_fd = ctrl.zc_export.zcrx_fd;
    printf("export fd=%d\n", export_fd);

    /* Two TCP pairs: A and B read from different sockets. */
    int rx_a, tx_a, rx_b, tx_b;
    if (make_loop_pair(&rx_a, &tx_a) || make_loop_pair(&rx_b, &tx_b)) return 1;
    int file_fd = make_data_file();
    if (file_fd < 0) return 1;

    struct zcrx za; memset(&za, 0, sizeof(za));
    za.ring = ra; za.ifq_id = reg.zcrx_id; za.rq_entries = RQ_ENTRIES;
    za.area_token = area.rq_area_token; za.region = region;
    za.rqes = (struct io_uring_zcrx_rqe *)(region + reg.offsets.rqes);
    za.rq_tail = (uint32_t *)(region + reg.offsets.tail);
    za.stats = stats;

    volatile int stop = 0;
    volatile int b_ready = 0;
    za.stop = &stop;
    za.ctrl_fd = ra.fd;
    pthread_mutex_init(&za.rq_lock_storage, NULL);
    za.rq_lock = &za.rq_lock_storage;

    /* Ring B imports the same ifq.  It must be created in the B thread for SINGLE_ISSUER. */
    struct zcrx zb; memset(&zb, 0, sizeof(zb));
    zb.ifq_id = reg.zcrx_id; zb.rq_entries = RQ_ENTRIES; zb.area_token = area.rq_area_token;
    zb.region = region; zb.rqes = za.rqes; zb.rq_tail = za.rq_tail; zb.stats = stats;
    zb.stop = &stop;
    zb.rq_lock = &za.rq_lock_storage;
    zb.ctrl_fd = ra.fd;

    struct sender_arg sa = { .fd = tx_a, .file_fd = file_fd, .stop = &stop };
    struct sender_arg sb = { .fd = tx_b, .file_fd = file_fd, .stop = &stop };
    pthread_t tb = 0, tsa, tsb = 0, tt;
    pthread_create(&tsa, NULL, send_loop, &sa);
    if (!single) pthread_create(&tsb, NULL, send_loop, &sb);

    struct b_arg ba = { .z = &zb, .export_fd = export_fd, .rx = rx_b, .flags = flags, .ready = &b_ready };
    if (!single) pthread_create(&tb, NULL, b_thread, &ba);
    else __atomic_store_n(&b_ready, 1, __ATOMIC_RELEASE);
    while (!__atomic_load_n(&b_ready, __ATOMIC_ACQUIRE) && !stop) usleep(1000);

    submit_recvzc(&ra, rx_a, reg.zcrx_id, 0xAAAA);
    struct stop_arg st = { .stop = &stop, .fds = { rx_a, tx_a, single ? -1 : rx_b, single ? -1 : tx_b }, .secs = secs };
    pthread_create(&tt, NULL, timer_thread, &st);
    recv_loop(&za);

    pthread_join(tt, NULL);
    if (!single) pthread_join(tb, NULL);
    pthread_join(tsa, NULL);
    if (!single) pthread_join(tsb, NULL);

    printf("RESULT data_cqes=%llu data_bytes=%llu copy_count=%llu copy_bytes=%llu\n",
           (unsigned long long)(za.cqes_data + zb.cqes_data),
           (unsigned long long)(za.bytes_data + zb.bytes_data),
           (unsigned long long)stats[0], (unsigned long long)stats[1]);
    printf("RESULT A cqes=%llu bytes=%llu B cqes=%llu bytes=%llu errors=%d/%d\n",
           (unsigned long long)za.cqes_data, (unsigned long long)za.bytes_data,
           (unsigned long long)zb.cqes_data, (unsigned long long)zb.bytes_data,
           za.errors, zb.errors);
    printf("RESULT delta_bytes=%lld delta_count_vs_cqes=%lld\n",
           (long long)((int64_t)stats[1] - (int64_t)(za.bytes_data + zb.bytes_data)),
           (long long)((int64_t)stats[0] - (int64_t)(za.cqes_data + zb.cqes_data)));
    return 0;
}

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

* Re: io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race)
  2026-11-22  7:39   ` io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race) 徐晗翔
@ 2026-11-23 13:50     ` Pavel Begunkov
  2026-11-24 17:17       ` Clément Léger
  0 siblings, 1 reply; 7+ messages in thread
From: Pavel Begunkov @ 2026-11-23 13:50 UTC (permalink / raw)
  To: 徐晗翔; +Cc: io-uring, netdev, linux-kernel, Jens Axboe

On 11/22/26 07:39, 徐晗翔 wrote:
> An io_uring zero-copy RX ifq can be exported by one ring and imported by
> another.  Both rings then perform receive-zc on their own TCP sockets,
> but they share the same struct io_zcrx_ifq and therefore the same
> ifq->notif_stats.  The statistics update is not atomic:
> 
>      static void zcrx_stat_add(__u64 *p, s64 v)
>      {
>          WRITE_ONCE(*p, READ_ONCE(*p) + v);
>      }
> 
> io_uring/zcrx.c:1337-1340.  It is called for copy_count and copy_bytes
> from io_zcrx_copy_frag() at zcrx.c:1770-1771.  There is no ifq-level
> lock in this path.  lock_sock() in io_zcrx_tcp_recvmsg() is per TCP
> socket, the ring's uring_lock is per ring, alloc_lock only protects
> fallback niov allocation and is released before the copy, and
> ctx_lock/notification is taken after the statistics update and is not
> involved when event_desc.type_mask == 0.  Two CPUs can therefore read
> the same old value, add their own increments, and write back the same
> new value: one update is lost.
> 
> The effect is limited to the UAPI cumulative copy statistics
> (struct zcrx_stats at include/uapi/linux/io_uring/zcrx.h:83-86).  The
> values are user-mappable diagnostic data; the race does not control
> buffer lifetime, DMA, reference counts, or packet contents.
It is racy, and IIRC Clement dropped atomicity at some point, perhaps
for performance reasons. I don't think it really matters though, the
main purposes of the stat is to be a flag saying "something is wrong,
setup steering rules". What's your use case? For precise statistics
I'd rather prefer to add a trace point, which would be able to do it
the right way (e.g. per-cpu counters).

-- 
Pavel Begunkov


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

* Re: io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race)
  2026-11-23 13:50     ` Pavel Begunkov
@ 2026-11-24 17:17       ` Clément Léger
  0 siblings, 0 replies; 7+ messages in thread
From: Clément Léger @ 2026-11-24 17:17 UTC (permalink / raw)
  To: Pavel Begunkov, 徐晗翔
  Cc: io-uring, netdev, linux-kernel, Jens Axboe

On 11/23/26 14:50, Pavel Begunkov wrote:
> > 
> On 11/22/26 07:39, 徐晗翔 wrote:
>> An io_uring zero-copy RX ifq can be exported by one ring and imported by
>> another.  Both rings then perform receive-zc on their own TCP sockets,
>> but they share the same struct io_zcrx_ifq and therefore the same
>> ifq->notif_stats.  The statistics update is not atomic:
>>
>>      static void zcrx_stat_add(__u64 *p, s64 v)
>>      {
>>          WRITE_ONCE(*p, READ_ONCE(*p) + v);
>>      }
>>
>> io_uring/zcrx.c:1337-1340.  It is called for copy_count and copy_bytes
>> from io_zcrx_copy_frag() at zcrx.c:1770-1771.  There is no ifq-level
>> lock in this path.  lock_sock() in io_zcrx_tcp_recvmsg() is per TCP
>> socket, the ring's uring_lock is per ring, alloc_lock only protects
>> fallback niov allocation and is released before the copy, and
>> ctx_lock/notification is taken after the statistics update and is not
>> involved when event_desc.type_mask == 0.  Two CPUs can therefore read
>> the same old value, add their own increments, and write back the same
>> new value: one update is lost.
>>
>> The effect is limited to the UAPI cumulative copy statistics
>> (struct zcrx_stats at include/uapi/linux/io_uring/zcrx.h:83-86).  The
>> values are user-mappable diagnostic data; the race does not control
>> buffer lifetime, DMA, reference counts, or packet contents.
> It is racy, and IIRC Clement dropped atomicity at some point, perhaps
> for performance reasons. I don't think it really matters though, the
> main purposes of the stat is to be a flag saying "something is wrong,
> setup steering rules". What's your use case? For precise statistics
> I'd rather prefer to add a trace point, which would be able to do it
> the right way (e.g. per-cpu counters).

Indeed, I used atomic first but then we dropped it. I don't remember 
exactly but we didn't consider export/import at that time. It make sense 
though so atomic would be fine as well although with an additional cost. 
I'll let Pavel be the judge but agreed that we do not really care about 
the value itself (there is nothing the userspace can really do about it
except check that "it's a lot").

Clément


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

end of thread, other threads:[~2026-11-24 17:17 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
     [not found] <4c7f9772.192e1.1a17d5c2ed5.Coremail.xuhx@hust.edu.cn>
     [not found] ` <2026102727-data-sequel-ce41@gregkh>
2026-11-03 11:57   ` net: rtnetlink: rtnl_link_unregister() vs in-flight RTM_GETLINK dump readers -- v7.3 lacks the synchronize_rcu() fix (Fixes: 6b57ff21a310 family); A/B reproduction on stock 7.3 徐晗翔
2026-11-03 15:49     ` Eric Dumazet
2026-11-04 15:03     ` Sasha Levin
2026-11-03 12:07   ` wifi: wilc1000: SDIO/SPI remove destroys the srcu_struct before wiphy_unregister() -- late cfg80211 callbacks write through dangling srcu state (unfixed upstream; controlled + natural Oops) 徐晗翔
2026-11-22  7:39   ` io_uring/zcrx: copy statistics lose updates when one ifq is shared by multiple rings (Data race) 徐晗翔
2026-11-23 13:50     ` Pavel Begunkov
2026-11-24 17:17       ` Clément Léger

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