SUNRPC: cache_read() serialises readers with a per-open inode lock, but every open() gets a fresh inode: concurrent formatting of the shared upcall buffer and unsynchronised rq->len (Data Race KCSAN-confirmed)
From: 徐晗翔
Date: Thu Nov 26 2026 - 07:52:31 EST
------------------------------------------------------------------------
cache_read() (net/sunrpc/cache.c) guards the shared upcall-request
state of a sunrpc cache channel with inode_lock(file_inode(filp)),
commented "protect against multiple concurrent readers on this file".
But the state it needs to protect -- the cache_request's rq->buf and
rq->len -- is shared per struct cache_detail, not per inode, and on
procfs every open() of the channel gets a brand-new inode
(/proc/net/rpc entries force revalidation on every lookup and
proc_get_inode() allocates a fresh inode each time), so the lock
serialises nothing across readers: two concurrent readers of the same
channel both pass the "rq->len == 0" check and both run
cache_request(), concurrently formatting the same shared PAGE_SIZE
buffer, and both store rq->len with plain, unsynchronised stores --
while cache_ioctl(FIONREAD) reads rq->len under cd->queue_lock, a lock
the formatting write does not hold. A reader's copy_to_user() can
also run concurrently with the other reader's formatting, delivering
torn upcall text to the userspace cache daemons (gssd, nfsd's
export/idmap caches). This is a true data race on plain C accesses,
confirmed with KCSAN on mainline 7.3; the request lifetime itself is
correctly protected by rq->readers, so this is data corruption
(wrong/torn upcall text, failed daemon parsing), not memory unsafety.
The detailed description:
* Test environment / affected version
Linux version 7.3.0 (gcc 13.3.0, GNU ld 2.42) #1 SMP PREEMPT_DYNAMIC
-- vanilla mainline 7.3 tree; net/sunrpc/cache.c is byte-identical
between the audited tree and 7.3, line numbers below are from 7.3.
Data race confirmed with a KCSAN-enabled build of the same tree in
QEMU/KVM x86_64.
* Mechanism
Every cache_detail exposes an upcall channel (channel file, created
in create_cache_proc_entries(), cache.c:1670-1704, with private data
pointing at the shared struct cache_detail) and serves reads through
cache_read() (cache.c:841-910):
cache.c:852 inode_lock(inode); /* "protect against multiple
concurrent readers on this
file" */
cache.c:855 spin_lock(&cd->queue_lock);
cache.c:865 rq->readers++; /* under queue_lock -- safe */
cache.c:866 spin_unlock(&cd->queue_lock);
cache.c:868 if (rq->len == 0) {
cache.c:869 err = cache_request(cd, rq); /* formats rq->buf */
cache.c:872 rq->len = err; /* plain store */
cache.c:873 }
cache.c:879 count = rq->len - rp->offset; /* plain read */
cache.c:882 copy_to_user(buf, rq->buf + rp->offset, count);
cache.c:894 spin_lock(&cd->queue_lock); /* readers--, free */
Two things break this:
1. The lock is per inode, the data is per cache_detail. The
/proc/net/rpc hierarchy is created with pde_force_lookup()
(fs/proc/proc_net.c:393, propagated to children in
fs/proc/generic.c:482-483) and proc_net_d_revalidate()
(fs/proc/generic.c:352-356) returns 0 unconditionally, so every
path-walk lookup invalidates the cached dentry and
proc_get_inode() (fs/proc/inode.c:628-635) allocates a NEW inode
via new_inode(). Any two open()s of the channel therefore hold
two different inodes and two different inode_lock()s; the
"concurrent readers of this file" that the comment worries about
are never actually serialised. The pipefs channel
(cache_read_pipefs(), cache.c:1759) reaches the same code through
a different filesystem with the same outcome.
2. The critical state is touched outside every lock. After
cache.c:866 the reader holds only its own inode_lock, while
rq->buf and rq->len belong to the cache_request that sits on the
shared cd->requests list. Concurrent readers both observe
rq->len == 0 and both run cache_request() over the same buffer
(word-level write/write race; each formatter starts from offset
0), both store rq->len, and a reader that got past the check can
copy_to_user() from the buffer while the other is still formatting
it. cache_ioctl(FIONREAD) (cache.c:990-1012) reads
"rq->len - rp->offset" under cd->queue_lock (cache.c:1008) -- a
lock the rq->len store at cache.c:872 does not hold, so that
read/write pair is a plain data race as well.
What is NOT broken: the lifetime of rq. rq->readers is incremented
and decremented under cd->queue_lock and a request is only freed when
its reader count drops to zero while not CACHE_PENDING
(cache.c:894-905, cache_dequeue(), cache_release()), so the two
kfree()-adjacent races that a static analysis flags on this function
are genuinely refuted. This report is about the content/length
consistency of the shared buffer, which no lock currently covers.
* Trigger model
The channel files are mode 0600, so this needs root or the identity
of the legitimate cache daemon. Two concurrent readers of the same
channel (e.g. two gssd instances, or a daemon racing a manual
inspection) is the natural trigger; racing a read() with
ioctl(FIONREAD) on one fd needs no second opener at all. A cache
miss must have queued an upcall (cache_do_upcall()) for a request to
exist. Consequence: torn/garbled upcall text delivered to userspace
(daemon parse failures for RPCSEC_GSS and nfsd caches), and a formal
data race under the C memory model. No memory-unsafety: the
formatters are bounded by the remaining-length convention
(qword_add()/qword_addhex(), cache.c:1122-1170) and cache_request()
rejects overflow with -E2BIG, and copy_to_user()'s count is derived
from a length that is always <= PAGE_SIZE.
* Reproducer (attached: rpcrace.c + rpcrd.c) and results on 7.3
Because the reporting environment has no nfsd running (no pre-existing
auth caches with live traffic), the reproducer registers its own
cache_detail ("racetest", exposed at /proc/net/rpc/racetest/channel
via the exported cache_create_net()/cache_register_net()) whose
cache_request formats a deterministic text line, and a kernel feeder
thread calls sunrpc_cache_upcall() continuously so requests keep
appearing on cd->requests. rpcrd.c is a small userspace racer:
concurrent read() loops (mode r) and an FIONREAD loop (mode c).
# build (module + static userspace racer)
make -C <kernel-build-dir> M=$PWD modules
clang -O2 -static -o rpcrd rpcrd.c
# run on a KCSAN kernel (kcsan runtime enabled for the window):
insmod rpcrace.ko mode=mr02 secs=40
/rpcrd r 40 & /rpcrd r 40 & /rpcrd r 40 & /rpcrd c 40 &
Results (7.3 KCSAN build, 8 vCPU, one 40s window): 25 cache-related
reports, two shapes:
- "BUG: KCSAN: data-race in cache_read / cache_read": write of 4
bytes at cache_read+0x1d3 (the rq->len = err store) by one task
vs read of 4 bytes at cache_read+0x127 (the rq->len == 0 check)
by another task on another CPU -- the concurrent formatting
decision itself;
- "BUG: KCSAN: data-race in _copy_to_user / string_escape_mem" x11:
read of 134 bytes (_copy_to_user <- cache_read, the
copy_to_user() of rq->buf) vs write of 1 byte
(string_escape_mem <- qword_add <- cache_request <- cache_read)
at the same buffer -- the torn upcall text delivered to
userspace while the sibling reader is still formatting it.
A manual sanity pass also shows the functional effect: with two
readers started together the channel output of one reader comes back
interleaved/truncated. Serial logs and report excerpts are available
on request.
* Fix
The patch below formats the upcall text while holding cd->queue_lock.
cache_request() is pure formatting into the preallocated page (the
formatters only respect the remaining-length convention and never
sleep), so the lock hold is bounded and short; it makes the
"rq->len == 0 -> formatted" transition single-stepped, puts the
rq->len store under the same lock cache_ioctl() reads it under, and
guarantees every copy_to_user() is strictly ordered after the
formatting of the same request (a reader can only reach the copy once
rq->len is set, and from that moment nobody writes rq->buf again).
A negative length (formatting error) is made sticky for the request
so subsequent readers get the error instead of a negative copy count.
The patch has been reviewed but not runtime-tested (the race itself
is KCSAN-verified as above); happy to test alternatives, e.g. a
per-cache_request state bit with a waitqueue if the serialisation is
considered too coarse.
Please keep me in Cc; I am not subscribed to the lists.
Regards,
Hanxiang Xu <xuhx@xxxxxxxxxxx>
------------------------------------------------------------------------
The patch (text/plain; apply with patch -p1 or git am):
From: Hanxiang Xu <xuhx@xxxxxxxxxxx>
Subject: [PATCH] SUNRPC: format the cache upcall text under queue_lock
cache_read() serialises concurrent readers with inode_lock(inode), but
the state it protects -- the cache_request's rq->buf and rq->len -- is
shared per cache_detail, not per inode: /proc/net/rpc entries force
dentry revalidation on every lookup (proc_net_d_revalidate() returns 0)
and proc_get_inode() allocates a fresh inode each time, so every
open() of a channel file gets its own inode and the VFS lock never
actually serialises two readers. Concurrent readers both observe
rq->len == 0 and both run cache_request() over the same shared buffer
(word-level write/write race), a reader's copy_to_user() of rq->buf
can overlap the sibling's formatting (torn upcall text delivered to
gssd/nfsd cache daemons), and the rq->len store races the
cache_ioctl(FIONREAD) read, which is done under cd->queue_lock -- a
lock the store does not hold. All three were confirmed with KCSAN on
7.3 against a private cache_detail with concurrent readers and an
FIONREAD loop ("data-race in cache_read / cache_read" for the
rq->len store vs check, "data-race in _copy_to_user /
string_escape_mem" for the buffer content).
Format the upcall text while holding cd->queue_lock: cache_request()
is pure formatting into the preallocated page and cannot sleep, the
hold is bounded, and it makes the rq->len transition single-stepped
and ordered against both the sibling readers and cache_ioctl(). The
copy_to_user() can then only run once rq->len is set, after which
nobody writes rq->buf again. A negative cache_request() result is
stored and made sticky for the request so later readers receive the
error rather than computing a negative copy count.
The request lifetime itself is unaffected: rq->readers under
queue_lock already protects rq from premature free.
Signed-off-by: Hanxiang Xu <xuhx@xxxxxxxxxxx>
---
net/sunrpc/cache.c | 25 ++++++++++++++-----------
1 file changed, 14 insertions(+), 11 deletions(-)
--- a/net/sunrpc/cache.c
+++ b/net/sunrpc/cache.c
@@ -863,13 +863,26 @@
}
if (rp->offset == 0)
rq->readers++;
+ /*
+ * Format the upcall text while holding queue_lock. rq is shared
+ * by every reader of this cache: each open() of the channel gets a
+ * fresh inode (procfs revalidates /proc/net/rpc entries on every
+ * lookup and allocates a new inode), so the VFS inode_lock() above
+ * serialises nothing across readers, and cache_ioctl(FIONREAD)
+ * reads rq->len under this same lock. cache_request() is pure
+ * formatting into the preallocated page and cannot sleep. Doing
+ * it under the lock makes the "rq->len == 0 -> formatted"
+ * transition single-stepped and keeps the copy_to_user() below
+ * strictly ordered after the formatting of the same request.
+ */
+ if (rq->len == 0)
+ rq->len = cache_request(cd, rq);
spin_unlock(&cd->queue_lock);
- if (rq->len == 0) {
- err = cache_request(cd, rq);
- if (err < 0)
- goto out;
- rq->len = err;
+ /* a formatting error is sticky for this request */
+ if (rq->len < 0) {
+ err = rq->len;
+ goto out;
}
if (rp->offset == 0 && !test_bit(CACHE_PENDING, &rq->item->flags)) {
net/sunrpc/cache.c | 23 ++++++++++++++++++-----
1 file changed, 18 insertions(+), 5 deletions(-)
------------------------------------------------------------------------
/* rpcrd - userspace racer against /proc/net/rpc/racetest/channel
* usage: rpcrd r <secs> concurrent read() loop
* rpcrd c <secs> FIONREAD ioctl loop
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <time.h>
static time_t g_end;
static int expired(void) { return time(NULL) >= g_end; }
int main(int argc, char **argv)
{
char buf[4096];
int fd, secs;
unsigned long n = 0;
if (argc < 3) { fprintf(stderr, "usage: rpcrd r|c secs\n"); return 1; }
fd = open("/proc/net/rpc/racetest/channel", O_RDWR);
if (fd < 0) { perror("open"); return 1; }
secs = atoi(argv[2]);
g_end = time(NULL) + secs;
if (argv[1][0] == 'r') {
while (!expired()) {
ssize_t r = read(fd, buf, sizeof(buf));
if (r > 0)
n++;
}
printf("RPCRD-U: reads=%lu\n", n);
} else {
int len, got = -1;
while (!expired()) {
if (ioctl(fd, FIONREAD, &len) == 0 && len != got) {
got = len;
n++;
}
}
printf("RPCRD-U: fionread-transitions=%lu\n", n);
}
return 0;
}
// SPDX-License-Identifier: GPL-2.0
/*
* rpcrace.c - controlled-window verification instruments for the net/sunrpc
* conditional-race audit cases SUNRPC-MR-01..04
* (docs/manual-review-net-sunrpc-2026-11-25.md, v4).
*
* Methodology follows this environment's established controlled-window
* precedent (r4_stall.c, r1stall.c, fx*): zero kernel-source changes; a
* loadable module drives exported core APIs (rpc_create, rpcauth_register,
* rpc_switch_client_transport, rpc_mkpipe_data/rpc_add_pipe_dir_object,
* cache_create_net/sunrpc_cache_upcall) and kprobe pre-handlers widen the
* natural race windows into deterministic choreographies.
*
* Modes (module param "mode"):
* mr03pfs - SUNRPC-MR-03 pipefs flavor. Custom authops->create() holds the
* rpc_client_register() failure window open until a userspace
* helper has open(2)'d the failing client's <pipefs>/nfs/clntXX/info
* file (open takes a cl_count reference via rpc_info_open). After
* the window closes rpc_new_client() kfree()s the client anyway
* and the helper read()s/closes the fd -> use-after-free in
* rpc_show_info()/rpc_info_release().
* mr03dbg - same choreography against the debugfs "tasks" file
* (/sys/kernel/debug/sunrpc/rpc_clnt/<clid>/tasks, tasks_open
* takes the cl_count reference; full_proxy_release forwards
* tasks_release unconditionally). Only meaningful on a kernel
* built with CONFIG_SUNRPC_DEBUG (debugfs.c compiled in).
* mr01 - SUNRPC-MR-01. Double-kprobe choreography:
* kp1 = rpc_unregister_client entry, claimed by our failing
* client thread at err_auth (after rpc_get_sb_net() already saw
* pipefs unmounted and released pipefs_sb_lock);
* kp2 = rpc_create_client_dir entry, claimed by the concurrent
* "mount -t rpc_pipefs" notifier while it holds pipefs_sb_lock
* and has already written clnt->pipefs_sb = sb.
* Release order (A resumes -> unregister/remove/kfree, then B
* resumes) reproduces the audited interleaving: B writes
* pdh_dentry into the freed rpc_clnt (UAF write) and leaves an
* orphan pipedir whose info file private points at freed memory.
* mr04 - SUNRPC-MR-04. kprobe stall on simple_recursive_removal() when
* called with callback == rpc_close_pipes from the umount task,
* while a module thread drives rpc_switch_client_transport()
* (which calls __rpc_clnt_remove_pipedir() WITHOUT
* pipefs_sb_lock). Both threads read the same pdh_dentry /
* pipe->dentry before either clears it -> the umount thread
* resumes simple_recursive_removal() on the already-freed pipe
* child dentry (use-after-free).
* mr02 - SUNRPC-MR-02 (KCSAN kernel). Module-owned cache_detail
* ("racetest", /proc/net/rpc/racetest/channel) + an upcall
* feeder; userspace runs two concurrent readers and a
* FIONREAD ioctl loop against the shared cache_request so that
* cache_read()/cache_read()/cache_ioctl() race on rq->buf and
* rq->len (plain, unsynchronised accesses).
*
* Handshake with userspace (see scripts/init-rpcrace):
* /sys/module/rpcrace/parameters/event - readonly state machine
* /sys/module/rpcrace/parameters/helper_ready - write 1 to complete the
* window (mr03*); mr01/mr04 choreograph internally.
*/
#define pr_fmt(fmt) "RPCRACE: " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/kthread.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/kref.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/atomic.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/auth.h>
#include <linux/sunrpc/msg_prot.h>
#include <linux/sunrpc/rpc_pipe_fs.h>
#include <linux/sunrpc/cache.h>
#include <linux/sunrpc/xprt.h>
#include <linux/sunrpc/stats.h>
static char *mode = "mr03pfs";
static int hold_ms = 8000;
static int iters = 2;
static int stall_ms = 4000;
static int secs = 30;
static int auth_ok;
static unsigned long cb_addr;
static bool do_hold;
module_param(mode, charp, 0400);
module_param(hold_ms, int, 0400);
module_param(iters, int, 0400);
module_param(stall_ms, int, 0400);
module_param(secs, int, 0400);
module_param(auth_ok, int, 0400);
module_param(cb_addr, ulong, 0400);
MODULE_PARM_DESC(mode, "mr03pfs | mr03dbg | mr01 | mr04 | mr02");
MODULE_PARM_DESC(cb_addr, "runtime address of rpc_close_pipes (mr04)");
/* ------------------------------------------------------------------ */
/* state machine */
/* event==1 : A stalled / window open (helper may act) */
/* event==2 : B stalled (mr01: mount inside create_client_dir; */
/* mr04: umount inside simple_recursive_removal) */
/* event==3 : failing client freed / done */
/* ------------------------------------------------------------------ */
static atomic_t race_state = ATOMIC_INIT(0);
static DECLARE_COMPLETION(helper_compl);
static DECLARE_COMPLETION(go_compl);
static struct task_struct *worker;
static int kp_unreg_hit, kp_ccd_hit, kp_srr_hit;
/* ------------------------- fake rpc program ------------------------ */
static u32 race_counts[1];
static const struct rpc_procinfo race_procs[1] = { { 0 } };
static const struct rpc_version race_v1 = {
.number = 1,
.nrprocs = 1,
.procs = race_procs,
.counts = race_counts,
};
static const struct rpc_version *race_version[1] = { &race_v1 };
static struct rpc_stat race_stat;
static const struct rpc_program race_program = {
.name = "rpcrace",
.number = 200000,
.nrvers = 1,
.version = race_version,
.stats = &race_stat,
.pipe_dir_name = "nfs", /* exists in rpc_pipefs root */
};
/* ------------------------- fake rpc auth --------------------------- */
static void race_auth_destroy(struct rpc_auth *auth) { }
static struct rpc_auth race_fake_auth;
/*
* create() is called from rpcauth_create() inside rpc_client_register()
* (clnt.c L322) - i.e. AFTER the client was published to sn->all_clients
* (L318) and after the pipefs pipedir was created (L313-315). Holding this
* callback open holds the audited publication window open (mr03*).
*/
static struct rpc_auth *
race_auth_create(const struct rpc_auth_create_args *args, struct rpc_clnt *clnt)
{
if (auth_ok) {
refcount_set(&race_fake_auth.au_count, 1);
return &race_fake_auth;
}
if (do_hold) {
pr_info("window OPEN (hold_ms=%d), clnt=%p clid=%d\n",
hold_ms, clnt, clnt->cl_clid);
atomic_set(&race_state, 1);
wait_for_completion_timeout(&helper_compl,
msecs_to_jiffies(hold_ms));
}
return ERR_PTR(-EINVAL);
}
static const struct rpc_authops race_authops = {
.owner = THIS_MODULE,
.au_flavor = RPC_AUTH_KRB, /* 4, unregistered in-kernel */
.au_name = "rpcrace",
.create = race_auth_create,
.destroy = race_auth_destroy,
};
/* ------------------------- kprobe machinery ------------------------ */
static atomic_t arm = ATOMIC_INIT(0);
static atomic_t release_flag = ATOMIC_INIT(0);
static void spin_until(int target)
{
unsigned long until = jiffies + msecs_to_jiffies(stall_ms);
while (atomic_read(&race_state) < target && time_before(jiffies, until))
cpu_relax();
}
/* mr01 kp1: rpc_unregister_client entry on the failing-client thread */
static int mr01_kp_unreg_pre(struct kprobe *p, struct pt_regs *regs)
{
if (!atomic_read(&arm) || kp_unreg_hit || current != worker)
return 0;
kp_unreg_hit = 1;
atomic_set(&race_state, 1);
pr_info("kp1: failing thread stalled at err_auth unregister "
"(rpc_get_sb_net already returned NULL)\n");
spin_until(2);
pr_info("kp1: mount side stalled -> releasing failing thread\n");
return 0;
}
/* mr01 kp2: rpc_create_client_dir entry on the mount task */
static int mr01_kp_ccd_pre(struct kprobe *p, struct pt_regs *regs)
{
if (!atomic_read(&arm) || kp_ccd_hit || !kp_unreg_hit)
return 0;
if (strncmp(current->comm, "mount", 5) != 0)
return 0;
kp_ccd_hit = 1;
atomic_set(&race_state, 2);
pr_info("kp2: mount notifier stalled inside rpc_create_client_dir "
"(holds pipefs_sb_lock, clnt->pipefs_sb already written)\n");
spin_until(3);
pr_info("kp2: failing client freed -> resuming create_client_dir "
"on freed rpc_clnt\n");
return 0;
}
/* mr04 kp: simple_recursive_removal(dentry, callback==rpc_close_pipes) */
static int mr04_kp_srr_pre(struct kprobe *p, struct pt_regs *regs)
{
if (!atomic_read(&arm) || kp_srr_hit)
return 0;
#ifdef CONFIG_X86_64
if (!cb_addr || regs->si != cb_addr)
return 0;
#else
return 0;
#endif
if (strncmp(current->comm, "umount", 6) != 0)
return 0;
kp_srr_hit = 1;
atomic_set(&race_state, 2);
pr_info("kp: umount stalled inside simple_recursive_removal(pipe child)\n");
{
unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 2);
while (!atomic_read(&release_flag) &&
time_before(jiffies, until))
cpu_relax();
}
pr_info("kp: switch-side removal done -> resuming removal on freed "
"pipe dentry\n");
return 0;
}
static struct kprobe kp_unreg = { .symbol_name = "rpc_unregister_client",
.pre_handler = mr01_kp_unreg_pre };
static struct kprobe kp_ccd = { .symbol_name = "rpc_create_client_dir",
.pre_handler = mr01_kp_ccd_pre };
static struct kprobe kp_srr = { .symbol_name = "simple_recursive_removal",
.pre_handler = mr04_kp_srr_pre };
/*
* mr04: the switch thread blocks on pipefs_sb_lock inside the re-register
* (the stalled umount holds the mutex), so the release is driven by a timer
* armed just before rpc_switch_client_transport(): the switch's unlocked
* __rpc_clnt_remove_pipedir() completes in microseconds, well within the
* 2s window; the umount thread then resumes on the freed pipe dentry.
*/
static struct timer_list mr04_rel_timer;
static void mr04_rel_timer_fn(struct timer_list *t)
{
atomic_set(&release_flag, 1);
pr_info("mr04: release timer fired\n");
}
/* ------------------------- client helpers -------------------------- */
static struct rpc_clnt *race_make_client(bool want_ok)
{
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
.sin_port = htons(2049),
};
struct rpc_create_args args = {
.net = current->nsproxy->net_ns,
.protocol = XPRT_TRANSPORT_TCP,
.address = (struct sockaddr *)&sin,
.addrsize = sizeof(sin),
.servername = "racetest",
.program = &race_program,
.version = 0,
.authflavor = RPC_AUTH_KRB,
.cred = current_cred(),
.flags = RPC_CLNT_CREATE_NOPING,
};
auth_ok = want_ok ? 1 : 0;
return rpc_create(&args);
}
/* ------------------------- mr03 worker ----------------------------- */
static int mr03_threadfn(void *unused)
{
int i;
wait_for_completion(&go_compl);
for (i = 0; i < iters; i++) {
struct rpc_clnt *clnt;
reinit_completion(&helper_compl);
clnt = race_make_client(false);
if (!IS_ERR(clnt)) {
pr_err("unexpected success, aborting\n");
rpc_shutdown_client(clnt);
break;
}
pr_info("iteration %d: rpc_create failed (%ld); client freed "
"while file references were held\n", i, PTR_ERR(clnt));
atomic_set(&race_state, 3);
msleep(300);
}
atomic_set(&race_state, 3);
pr_info("mr03 done\n");
return 0;
}
/* ------------------------- mr01 worker ----------------------------- */
static int mr01_threadfn(void *unused)
{
struct rpc_clnt *clnt;
wait_for_completion(&go_compl);
kp_unreg_hit = 0;
kp_ccd_hit = 0;
/* pipefs must be unmounted at create time; kp1 stalls the err_auth
* unregister; the helper's concurrent mount stalls inside
* rpc_create_client_dir via kp2; release order reproduces the
* audited interleaving. */
atomic_set(&arm, 1);
clnt = race_make_client(false);
atomic_set(&arm, 0);
if (!IS_ERR(clnt)) {
pr_err("mr01: unexpected success\n");
rpc_shutdown_client(clnt);
} else {
pr_info("mr01: rpc_create failed (%ld)\n", PTR_ERR(clnt));
}
atomic_set(&race_state, 3);
return 0;
}
/* ------------------------- mr04 machinery -------------------------- */
struct race_pdo {
struct rpc_pipe_dir_object pdo;
struct rpc_pipe *pipe;
};
static struct rpc_clnt *mr04_clnt;
static struct race_pdo mr04_rp;
static ssize_t race_pipe_upcall(struct file *filp, struct rpc_pipe_msg *msg,
char __user *dst, size_t buflen)
{
return rpc_pipe_generic_upcall(filp, msg, dst, buflen);
}
static const struct rpc_pipe_ops race_pipe_ops = {
.upcall = race_pipe_upcall,
};
static int race_pdo_create(struct dentry *dir, struct rpc_pipe_dir_object *pdo)
{
struct race_pdo *rp = pdo->pdo_data;
return rpc_mkpipe_dentry(dir, "racetest", NULL, rp->pipe);
}
static void race_pdo_destroy(struct dentry *dir, struct rpc_pipe_dir_object *pdo)
{
struct race_pdo *rp = pdo->pdo_data;
rpc_unlink(rp->pipe);
}
static const struct rpc_pipe_dir_object_ops race_pdo_ops = {
.create = race_pdo_create,
.destroy = race_pdo_destroy,
};
static int mr04_setup(void)
{
int ret;
mr04_clnt = race_make_client(true); /* want_ok: fake valid auth */
if (IS_ERR(mr04_clnt))
return PTR_ERR(mr04_clnt);
mr04_rp.pipe = rpc_mkpipe_data(&race_pipe_ops, 0);
ret = PTR_ERR_OR_ZERO(mr04_rp.pipe);
if (ret)
goto out_clnt;
mr04_rp.pdo.pdo_data = &mr04_rp;
rpc_init_pipe_dir_object(&mr04_rp.pdo, &race_pdo_ops, &mr04_rp);
ret = rpc_add_pipe_dir_object(rpc_net_ns(mr04_clnt),
&mr04_clnt->cl_pipedir_objects,
&mr04_rp.pdo);
if (ret)
goto out_pipe;
pr_info("mr04: client clid=%d armed with pipedir + child pipe\n",
mr04_clnt->cl_clid);
return 0;
out_pipe:
rpc_destroy_pipe_data(mr04_rp.pipe);
out_clnt:
rpc_shutdown_client(mr04_clnt);
mr04_clnt = NULL;
return ret;
}
static void mr04_cleanup(void)
{
if (mr04_clnt)
rpc_shutdown_client(mr04_clnt);
mr04_clnt = NULL;
}
static int mr04_threadfn(void *unused)
{
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
.sin_port = htons(2049),
};
struct xprt_create xargs = {
.ident = XPRT_TRANSPORT_TCP,
.net = rpc_net_ns(mr04_clnt),
.dstaddr = (struct sockaddr *)&sin,
.addrlen = sizeof(sin),
.servername = "racetest",
};
int ret, i;
/* wait for the umount thread to stall inside simple_recursive_removal */
{
unsigned long until = jiffies + msecs_to_jiffies(stall_ms * 4);
while (atomic_read(&race_state) < 2 &&
time_before(jiffies, until))
msleep(1);
}
if (atomic_read(&race_state) < 2) {
pr_err("mr04: umount side never stalled, aborting\n");
return 0;
}
pr_info("mr04: driving rpc_switch_client_transport() against the "
"stalled umount\n");
timer_setup(&mr04_rel_timer, mr04_rel_timer_fn, 0);
/* 300ms: the switch-side unlocked removal completes in microseconds,
* while the freed dentries are still inside the KASAN quarantine when
* the umount thread resumes (clean slab-use-after-free instead of a
* post-reuse crash). */
mod_timer(&mr04_rel_timer, jiffies + msecs_to_jiffies(300));
for (i = 0; i < 3; i++) {
ret = rpc_switch_client_transport(mr04_clnt, &xargs, NULL);
pr_info("mr04: switch attempt %d -> %d\n", i, ret);
if (ret == 0)
break;
msleep(50);
}
timer_delete_sync(&mr04_rel_timer);
atomic_set(&release_flag, 1);
atomic_set(&race_state, 3);
return 0;
}
/* ------------------------- mr02 machinery -------------------------- */
static struct cache_detail *race_cd;
static struct task_struct *feeder;
static bool feeder_run = true;
static void race_cache_put(struct kref *ref) { }
static void race_cache_request(struct cache_detail *cd, struct cache_head *h,
char **bpp, int *blen)
{
/* deterministic, comfortably-sized upcall text */
qword_add(bpp, blen, (char *)"racetest");
qword_add(bpp, blen, (char *)"filler-line-for-concurrent-formatting-race");
qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
qword_add(bpp, blen, (char *)"0123456789012345678901234567890123456789");
if (*blen > 0)
(*bpp)[-1] = '\n';
}
static struct cache_head *race_alloc(void)
{
return kzalloc_obj(struct cache_head, GFP_KERNEL);
}
static int race_match(struct cache_head *a, struct cache_head *b) { return 1; }
static void race_init_h(struct cache_head *a, struct cache_head *b) { }
static void race_update(struct cache_head *a, struct cache_head *b) { }
static struct cache_detail race_cd_template = {
.owner = THIS_MODULE,
.hash_size = 16,
.name = "racetest",
.cache_put = race_cache_put,
.cache_request = race_cache_request,
.alloc = race_alloc,
.match = race_match,
.init = race_init_h,
.update = race_update,
};
static int mr02_setup(void)
{
int ret;
race_cd = cache_create_net(&race_cd_template, current->nsproxy->net_ns);
if (IS_ERR(race_cd))
return PTR_ERR(race_cd);
ret = cache_register_net(race_cd, current->nsproxy->net_ns);
if (ret)
goto out_free;
pr_info("mr02: channel at /proc/net/rpc/racetest/channel\n");
return 0;
out_free:
cache_destroy_net(race_cd, current->nsproxy->net_ns);
race_cd = NULL;
return ret;
}
static void mr02_cleanup(void)
{
if (!race_cd)
return;
feeder_run = false;
if (feeder && !IS_ERR(feeder)) {
kthread_stop(feeder);
feeder = NULL;
}
cache_unregister_net(race_cd, current->nsproxy->net_ns);
cache_destroy_net(race_cd, current->nsproxy->net_ns);
race_cd = NULL;
}
static int mr02_threadfn(void *unused)
{
unsigned long until = jiffies + secs * HZ;
while (feeder_run && time_before(jiffies, until)) {
struct cache_head *h = race_alloc();
if (h) {
memset(h, 0, sizeof(*h));
INIT_HLIST_NODE(&h->cache_list);
kref_init(&h->ref);
h->expiry_time = seconds_since_boot() + 3600;
h->last_refresh = seconds_since_boot();
sunrpc_cache_upcall(race_cd, h);
/* h intentionally left pending: the rq stays on
* cd->requests for the readers to race on; the
* per-item leak is bounded by the run duration. */
}
usleep_range(1000, 2000);
}
pr_info("mr02: feeder done\n");
return 0;
}
/* ------------------------- module glue ----------------------------- */
static int helper_ready_get(char *buf, const struct kernel_param *kp)
{
return sprintf(buf, "%d\n", atomic_read(&race_state) >= 1 ? 1 : 0);
}
static int helper_ready_set(const char *val, const struct kernel_param *kp)
{
int v;
if (kstrtoint(val, 0, &v))
return -EINVAL;
if (v) {
pr_info("helper_ready -> window closing\n");
complete(&helper_compl);
}
return 0;
}
static const struct kernel_param_ops helper_ready_ops = {
.flags = KERNEL_PARAM_OPS_FL_NOARG,
.get = helper_ready_get,
.set = helper_ready_set,
};
module_param_cb(helper_ready, &helper_ready_ops, NULL, 0600);
static int event_get(char *buf, const struct kernel_param *kp)
{
return sprintf(buf, "%d\n", atomic_read(&race_state));
}
static const struct kernel_param_ops event_ops = {
.flags = KERNEL_PARAM_OPS_FL_NOARG,
.get = event_get,
};
module_param_cb(event, &event_ops, NULL, 0444);
static int __init rpcrace_init(void)
{
int ret;
do_hold = !strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg");
pr_info("mode=%s hold_ms=%d iters=%d stall_ms=%d secs=%d cb_addr=0x%llx\n",
mode, hold_ms, iters, stall_ms, secs, (unsigned long long)cb_addr);
if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
ret = rpcauth_register(&race_authops);
if (ret)
return ret;
worker = kthread_run(mr03_threadfn, NULL, "rpcraceA");
ret = PTR_ERR_OR_ZERO(worker);
if (!ret)
complete(&go_compl);
return ret;
}
if (!strcmp(mode, "mr01")) {
ret = register_kprobe(&kp_unreg);
if (ret)
return ret;
ret = register_kprobe(&kp_ccd);
if (ret) {
unregister_kprobe(&kp_unreg);
return ret;
}
worker = kthread_run(mr01_threadfn, NULL, "rpcraceA");
ret = PTR_ERR_OR_ZERO(worker);
if (ret) {
unregister_kprobe(&kp_ccd);
unregister_kprobe(&kp_unreg);
return ret;
}
/* thread blocks on go_compl; release after worker assigned */
complete(&go_compl);
return 0;
}
if (!strcmp(mode, "mr04")) {
if (!cb_addr) {
pr_err("mr04 requires cb_addr=<rpc_close_pipes>\n");
return -EINVAL;
}
ret = rpcauth_register(&race_authops);
if (ret)
return ret;
ret = mr04_setup();
if (ret) {
rpcauth_unregister(&race_authops);
return ret;
}
ret = register_kprobe(&kp_srr);
if (ret) {
mr04_cleanup();
return ret;
}
atomic_set(&arm, 1);
worker = kthread_run(mr04_threadfn, NULL, "rpcraceA");
if (IS_ERR(worker)) {
unregister_kprobe(&kp_srr);
atomic_set(&arm, 0);
mr04_cleanup();
return PTR_ERR(worker);
}
return 0;
}
if (!strcmp(mode, "mr02")) {
ret = mr02_setup();
if (ret)
return ret;
feeder = kthread_run(mr02_threadfn, NULL, "rpcraceF");
if (IS_ERR(feeder)) {
mr02_cleanup();
return PTR_ERR(feeder);
}
return 0;
}
return -EINVAL;
}
static void __exit rpcrace_exit(void)
{
if (!strcmp(mode, "mr03pfs") || !strcmp(mode, "mr03dbg")) {
if (worker && !IS_ERR(worker))
kthread_stop(worker);
rpcauth_unregister(&race_authops);
} else if (!strcmp(mode, "mr01")) {
atomic_set(&arm, 0);
if (worker && !IS_ERR(worker))
kthread_stop(worker);
unregister_kprobe(&kp_ccd);
unregister_kprobe(&kp_unreg);
} else if (!strcmp(mode, "mr04")) {
atomic_set(&arm, 0);
atomic_set(&release_flag, 1);
if (worker && !IS_ERR(worker))
kthread_stop(worker);
unregister_kprobe(&kp_srr);
mr04_cleanup();
rpcauth_unregister(&race_authops);
} else if (!strcmp(mode, "mr02")) {
mr02_cleanup();
}
pr_info("exit\n");
}
module_init(rpcrace_init);
module_exit(rpcrace_exit);
MODULE_LICENSE("GPL");