| 0/0 |
2026/11/22 07:27 |
flow |
bisect-cause |
46m
Results: map[BisectReasoning:### Bisection Conclusion
The bug was introduced by commit **`d532cddb6c6049ced414d64d83c6ce7149a6421a`** (`"nbd: Reclassify sockets to avoid lockdep circular dependency"`).
---
### Root Cause Verification & Git History Analysis
1. **Buggy Mechanism (`drivers/block/nbd.c`, `include/net/sock.h`)**:
- `nbd_add_socket()` resolves a user-supplied file descriptor via `nbd_get_socket()` (`sockfd_lookup()`) and calls `nbd_reclassify_socket(sock)` (`drivers/block/nbd.c:1299`).
- Under `CONFIG_DEBUG_LOCK_ALLOC`, `nbd_reclassify_socket()` checks `sock_allow_reclassification(sk)` (`include/net/sock.h:1835-1841`), which reads `sk->sk_lock.owned` and `spin_is_locked(&sk->sk_lock.slock)` **without synchronization**.
- If that check returns `true`, `nbd_reclassify_socket()` invokes `sock_lock_init_class_and_name()` (`include/net/sock.h:1694-1705`), which unconditionally executes:
- `sk->sk_lock.owned = 0;`
- `init_waitqueue_head(&sk->sk_lock.wq);`
- `spin_lock_init(&(sk)->sk_lock.slock);`
- Because NBD uses a userspace-owned socket fd rather than a kernel-private `sock_create_kern()` socket, another thread (e.g. `inet_shutdown()` -> `release_sock()` or softirq processing) can concurrently acquire `sk->sk_lock.slock` in the TOCTOU window after `sock_allow_reclassification(sk)` returns `true` and before `spin_lock_init()` runs.
- `spin_lock_init()` resets the active `slock` to unlocked while it is held, causing `debug_spin_unlock()` to trigger `BUG: spinlock already unlocked in inet_shutdown` when the holder unlocks it.
2. **Commits Examined**:
- **`d532cddb6c6049ced414d64d83c6ce7149a6421a` (`"nbd: Reclassify sockets to avoid lockdep circular dependency"`)** — **Introducing commit**:
Added `nbd_reclassify_socket()` and the call to it in `nbd_add_socket()`, applying `sock_allow_reclassification()` + `sock_lock_init_class_and_name()` (a pattern copied from `nvme-tcp` where sockets are kernel-internal) to user-supplied sockets in NBD.
- **`9280e6edf65662b6aafc8b704ad065b54c08b519` (`"nbd: don't warn when reclassifying a busy socket lock"`)** — Ruled out:
Only changed `if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))` to `if (!sock_allow_reclassification(sk))` in `nbd_reclassify_socket()`. The TOCTOU race and destructive `spin_lock_init()` when the lock is acquired *after* `sock_allow_reclassification(sk)` evaluates to `true` already existed in `d532cddb6c60`.
- **`fafc4e1ea1a4c1eb13a30c9426fb799f5efacbc3` (`"sock: tigthen lockdep checks for sock_owned_by_user"`)** — Ruled out:
Introduced `sock_allow_reclassification()` in `include/net/sock.h` for existing kernel-owned socket callers (`cifs`, `bluetooth`, `sunrpc`); NBD did not call it until `d532cddb6c60`.
- **`04d8fb23e520` (`"nbd: disallow NBD_SET_SOCK on an active device"`)** and **`285908f554fe` (`"nbd: remove queue freeze in nbd_add_socket"`)** — Ruled out:
Only modified `nbd->pid` checks and queue freezing in `nbd_add_socket()`, leaving `nbd_reclassify_socket()` and the race against userspace/concurrent socket operations unchanged.
- **`e14cadfd80d7` (`"tcp: add annotations around sk->sk_shutdown accesses"`)** — Ruled out:
Unrelated annotation changes in `inet_shutdown()`.
### Result
- **Introducing commit**: `d532cddb6c6049ced414d64d83c6ce7149a6421a` Commits:[map[AuthorEmail:edumazet@google.com AuthorName:Eric Dumazet Date:2026-06-13T04:26:19Z Hash:d532cddb6c6049ced414d64d83c6ce7149a6421a Recipients:[map[Email:axboe@kernel.dk Name: To:true] map[Email:edumazet@google.com Name: To:true]] Title:nbd: Reclassify sockets to avoid lockdep circular dependency]] IsRelease:false KernelCommit:03897066069fd47caf2908183edf3b22b822ea73]
|
| 1/1 |
2026/11/22 07:27 |
action |
use-crash-commit |
0m
Results: map[KernelCommit:03897066069fd47caf2908183edf3b22b822ea73]
|
| 2/1 |
2026/11/22 07:27 |
action |
syz-repro-to-c-repro |
0m
Results: map[SimplifiedCRepro:#define _GNU_SOURCE
// Copyright 2026 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// IMPORTANT: Do not copy the macros or definitions below directly into your reproducer.
// Instead, add the following line to your reproducer:
// #include "race_toolkit.h"
// --- Race Condition Toolkit ---
// Macros and snippets for CPU pinning, memory barriers, and userfaultfd.
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/futex.h>
#include <linux/userfaultfd.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
// Unbuffered I/O: Ensure logs are written immediately.
#define SETUP_UNBUFFERED_IO() setvbuf(stdout, NULL, _IONBF, 0)
// CPU Pinning: Pin the current thread to a specific CPU core.
#define PIN_TO_CPU(cpu) \
do { \
cpu_set_t mask; \
CPU_ZERO(&mask); \
CPU_SET(cpu, &mask); \
if (sched_setaffinity(0, sizeof(mask), &mask) == -1) { \
perror("sched_setaffinity"); \
} \
} while (0)
// Memory Barrier: Ensure memory ordering.
#define MB() __atomic_thread_fence(__ATOMIC_SEQ_CST)
// Spin-wait Barrier: Wait until a memory location has a specific value.
// Best for tight race windows (low latency, no context switches).
#define WAIT_ON(addr, val) \
do { \
while (__atomic_load_n(addr, __ATOMIC_ACQUIRE) != (val)) \
; \
} while (0)
// Signal: Set a memory location to a specific value to release a WAIT_ON.
#define SIGNAL(addr, val) __atomic_store_n(addr, val, __ATOMIC_RELEASE)
// --- Timing Primitives ---
// Robust timing loops in VM environments (using CLOCK_MONOTONIC to avoid time(NULL) jumps).
static inline double timer_elapsed_sec(struct timespec* start)
{
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now) == -1) {
perror("clock_gettime(CLOCK_MONOTONIC) elapsed");
exit(1);
}
return (double)(now.tv_sec - start->tv_sec) + (double)(now.tv_nsec - start->tv_nsec) / 1e9;
}
// Initialize a monotonic timer variable.
#define TIMER_START(t) \
struct timespec t; \
if (clock_gettime(CLOCK_MONOTONIC, &t) == -1) { \
perror("clock_gettime(CLOCK_MONOTONIC) start"); \
exit(1); \
}
// Check if the elapsed time since 't' is less than 'sec' seconds.
#define TIMER_NOT_EXPIRED(t, sec) (timer_elapsed_sec(&(t)) < (double)(sec))
// Futex-based Event: Shared with syzkaller executor.
// Best for general synchronization or longer waits to save CPU.
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) {
fprintf(stderr, "event already set\n");
exit(1);
}
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
// userfaultfd setup: Register a memory range for page fault handling.
static int setup_uffd(void* addr, size_t len)
{
int uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
if (uffd == -1)
return -1;
struct uffdio_api api = {.api = UFFD_API, .features = 0};
if (ioctl(uffd, UFFDIO_API, &api) == -1) {
close(uffd);
return -1;
}
struct uffdio_register reg = {
.range = {.start = (uintptr_t)addr, .len = len},
.mode = UFFDIO_REGISTER_MODE_MISSING};
if (ioctl(uffd, UFFDIO_REGISTER, ®) == -1) {
close(uffd);
return -1;
}
return uffd;
}
// --- Guidance on Usage ---
// 1. Use WAIT_ON/SIGNAL for tight race conditions to avoid scheduling overhead.
// 2. Use event_t (futexes) for general coordination or when waiting for longer periods.
// 3. Always use PIN_TO_CPU to increase race probability on multi-core systems.
// 4. Use setup_uffd to register a memory range for page fault handling. This allows you to
// pause a thread accessing that memory until you handle the fault, creating a reliable
// and controllable race window.
// 5. Call SETUP_UNBUFFERED_IO() at the start of main() to ensure that logs are printed
// immediately. This is essential for understanding the exact interleaving of events
// when debugging race conditions.
// 6. For timing-based loops (e.g., running a race for 10 seconds), do NOT use time(NULL)
// or loops relying on real-time clocks, as VM clocks are highly unreliable and can fail or drift.
// Instead, use the robust monotonic timing primitives TIMER_START and TIMER_NOT_EXPIRED:
// TIMER_START(start);
// while (TIMER_NOT_EXPIRED(start, 10.0)) {
// // Your race logic here
// }
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/major.h>
#include <linux/nbd.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <sched.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#ifndef NBD_MAJOR
#define NBD_MAJOR 43
#endif
#ifndef NBD_SET_SOCK
#define NBD_SET_SOCK _IO(0xab, 0)
#endif
#ifndef NBD_DO_IT
#define NBD_DO_IT _IO(0xab, 3)
#endif
#ifndef NBD_CLEAR_SOCK
#define NBD_CLEAR_SOCK _IO(0xab, 4)
#endif
#ifndef NBD_DISCONNECT
#define NBD_DISCONNECT _IO(0xab, 8)
#endif
#ifndef SOL_TCP
#define SOL_TCP 6
#endif
#ifndef TCP_REPAIR
#define TCP_REPAIR 19
#endif
#ifndef TCP_REPAIR_ON
#define TCP_REPAIR_ON 1
#endif
#define TOTAL_DEVS 11
#define NUM_RECLASSIFIERS 5 /* Devices nbd0 through nbd4 */
#define NUM_RUNNERS 6 /* Devices nbd5 through nbd10 */
static int shared_sock = -1;
static volatile bool running = true;
static int num_cpus = 1;
static int open_nbd_device(int idx)
{
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%d", idx);
int fd = open(path, O_RDWR);
if (fd < 0 && errno == ENOENT) {
printf("[*] %s does not exist, attempting mknod...\n", path);
int res = mknod(path, S_IFBLK | 0660, makedev(NBD_MAJOR, idx));
if (res < 0) {
printf("[-] Failed to mknod %s: %s\n", path, strerror(errno));
return -1;
}
printf("[+] mknod %s successful.\n", path);
fd = open(path, O_RDWR);
}
if (fd < 0) {
printf("[-] Failed to open %s: %s\n", path, strerror(errno));
return -1;
}
printf("[+] open %s successful (fd=%d).\n", path, fd);
return fd;
}
static int setup_tcp_socket(void)
{
int srv = socket(AF_INET, SOCK_STREAM, 0);
if (srv < 0) {
printf("[-] Failed to socket(AF_INET, SOCK_STREAM, 0) for server: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server socket created.\n");
int opt = 1;
int res = setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (res < 0) {
printf("[-] Failed to setsockopt(SO_REUSEADDR): %s\n", strerror(errno));
exit(1);
}
printf("[+] setsockopt(SO_REUSEADDR) successful.\n");
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
sin.sin_port = 0;
res = bind(srv, (struct sockaddr*)&sin, sizeof(sin));
if (res < 0) {
printf("[-] Failed to bind server socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server socket bound to 127.0.0.1.\n");
socklen_t slen = sizeof(sin);
res = getsockname(srv, (struct sockaddr*)&sin, &slen);
if (res < 0) {
printf("[-] Failed to getsockname: %s\n", strerror(errno));
exit(1);
}
printf("[+] getsockname successful (port=%d).\n", ntohs(sin.sin_port));
res = listen(srv, 10);
if (res < 0) {
printf("[-] Failed to listen: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server socket listening.\n");
int cli = socket(AF_INET, SOCK_STREAM, 0);
if (cli < 0) {
printf("[-] Failed to socket(AF_INET, SOCK_STREAM, 0) for client: %s\n", strerror(errno));
exit(1);
}
printf("[+] Client socket created.\n");
res = connect(cli, (struct sockaddr*)&sin, sizeof(sin));
if (res < 0) {
printf("[-] Failed to connect client socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Client socket connected.\n");
int acc = accept(srv, NULL, NULL);
if (acc < 0) {
printf("[-] Failed to accept connection: %s\n", strerror(errno));
exit(1);
}
printf("[+] Accepted client connection on server.\n");
res = close(srv);
if (res < 0) {
printf("[-] Failed to close srv socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server listening socket closed.\n");
res = close(acc);
if (res < 0) {
printf("[-] Failed to close acc socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Accepted peer socket closed (peer EOF).\n");
int repair = TCP_REPAIR_ON;
res = setsockopt(cli, SOL_TCP, TCP_REPAIR, &repair, sizeof(repair));
if (res < 0) {
printf("[-] Failed to setsockopt(SOL_TCP, TCP_REPAIR, TCP_REPAIR_ON): %s\n", strerror(errno));
exit(1);
}
printf("[+] setsockopt(SOL_TCP, TCP_REPAIR, TCP_REPAIR_ON) successful.\n");
return cli;
}
/* Devices nbd5 through nbd10: Continuously trigger recv_work and inet_shutdown */
static void* runner_worker(void* arg)
{
long dev_idx = (long)arg;
PIN_TO_CPU((int)(dev_idx % num_cpus));
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%ld", dev_idx);
while (__atomic_load_n(&running, __ATOMIC_RELAXED)) {
int fd = open(path, O_RDWR);
if (fd < 0) {
usleep(1000);
continue;
}
ioctl(fd, NBD_SET_SOCK, shared_sock);
ioctl(fd, NBD_DO_IT, 0);
ioctl(fd, NBD_CLEAR_SOCK, 0);
close(fd);
}
return NULL;
}
/* Devices nbd0 through nbd4: Continuously invoke nbd_reclassify_socket -> spin_lock_init */
static void* reclassifier_worker(void* arg)
{
long dev_idx = (long)arg;
PIN_TO_CPU((int)(dev_idx % num_cpus));
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%ld", dev_idx);
while (__atomic_load_n(&running, __ATOMIC_RELAXED)) {
int fd = open(path, O_RDWR);
if (fd < 0) {
usleep(1000);
continue;
}
for (int k = 0; k < 20 && __atomic_load_n(&running, __ATOMIC_RELAXED); k++) {
ioctl(fd, NBD_SET_SOCK, shared_sock);
ioctl(fd, NBD_CLEAR_SOCK, 0);
}
close(fd);
}
return NULL;
}
/* Disconnector thread: race NBD_DISCONNECT and direct user-space shutdown */
static void* disconnector_worker(void* arg)
{
(void)arg;
PIN_TO_CPU((int)(TOTAL_DEVS % num_cpus));
while (__atomic_load_n(&running, __ATOMIC_RELAXED)) {
for (int i = 0; i < TOTAL_DEVS; i++) {
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%d", i);
int fd = open(path, O_RDWR);
if (fd >= 0) {
ioctl(fd, NBD_DISCONNECT, 0);
close(fd);
}
}
shutdown(shared_sock, SHUT_RDWR);
usleep(1000);
}
return NULL;
}
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
printf("[*] Starting reproducer for BUG: spinlock already unlocked in inet_shutdown...\n");
num_cpus = (int)sysconf(_SC_NPROCESSORS_ONLN);
if (num_cpus < 1)
num_cpus = 1;
printf("[+] Detected %d online CPUs.\n", num_cpus);
/* Step 1: Pre-open / mknod all NBD devices (nbd0..nbd10) to verify availability */
for (int i = 0; i < TOTAL_DEVS; i++) {
int fd = open_nbd_device(i);
if (fd < 0) {
printf("[-] Failed to open/mknod /dev/nbd%d\n", i);
exit(1);
}
int res = ioctl(fd, NBD_CLEAR_SOCK, 0);
if (res < 0) {
printf("[-] Failed to ioctl(NBD_CLEAR_SOCK) on /dev/nbd%d: %s\n", i, strerror(errno));
exit(1);
}
res = close(fd);
if (res < 0) {
printf("[-] Failed to close /dev/nbd%d: %s\n", i, strerror(errno));
exit(1);
}
}
printf("[+] All %d NBD devices initialized and verified.\n", TOTAL_DEVS);
/* Step 2: Set up shared TCP socket with TCP_REPAIR enabled */
shared_sock = setup_tcp_socket();
if (shared_sock < 0) {
printf("[-] Failed to setup TCP socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Shared TCP socket ready (fd=%d).\n", shared_sock);
/* Step 3: Launch worker threads */
pthread_t threads[TOTAL_DEVS + 1];
/* Start reclassifier threads on devices 0..4 */
for (long i = 0; i < NUM_RECLASSIFIERS; i++) {
int res = pthread_create(&threads[i], NULL, reclassifier_worker, (void*)i);
if (res != 0) {
printf("[-] Failed to pthread_create reclassifier %ld: %s\n", i, strerror(res));
exit(1);
}
}
printf("[+] Started %d reclassifier threads on devices 0..%d.\n",
NUM_RECLASSIFIERS, NUM_RECLASSIFIERS - 1);
/* Start runner threads on devices 5..10 */
for (long i = 0; i < NUM_RUNNERS; i++) {
long dev_idx = NUM_RECLASSIFIERS + i;
int res = pthread_create(&threads[dev_idx], NULL, runner_worker, (void*)dev_idx);
if (res != 0) {
printf("[-] Failed to pthread_create runner %ld: %s\n", dev_idx, strerror(res));
exit(1);
}
}
printf("[+] Started %d runner threads on devices %d..%d.\n",
NUM_RUNNERS, NUM_RECLASSIFIERS, TOTAL_DEVS - 1);
/* Start disconnector thread */
int res = pthread_create(&threads[TOTAL_DEVS], NULL, disconnector_worker, NULL);
if (res != 0) {
printf("[-] Failed to pthread_create disconnector thread: %s\n", strerror(res));
exit(1);
}
printf("[+] Started disconnector thread.\n");
printf("[*] Racing NBD_SET_SOCK against NBD_DO_IT (recv_work) and inet_shutdown...\n");
TIMER_START(start);
while (TIMER_NOT_EXPIRED(start, 25.0) && __atomic_load_n(&running, __ATOMIC_RELAXED)) {
usleep(200000);
}
printf("[*] Race window completed, stopping threads...\n");
__atomic_store_n(&running, false, __ATOMIC_RELAXED);
for (int i = 0; i <= TOTAL_DEVS; i++) {
pthread_join(threads[i], NULL);
}
printf("[+] All worker threads stopped.\n");
for (int i = 0; i < TOTAL_DEVS; i++) {
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%d", i);
int fd = open(path, O_RDWR);
if (fd >= 0) {
ioctl(fd, NBD_CLEAR_SOCK, 0);
close(fd);
}
}
res = close(shared_sock);
if (res < 0) {
printf("[-] Failed to close shared_sock: %s\n", strerror(errno));
exit(1);
}
printf("[+] Closed shared_sock successfully.\n");
printf("[+] Reproducer finished cleanly.\n");
return 0;
}
]
|
| 3/1 |
2026/11/22 07:27 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/1d2135ea1beb7770967e322eb24134829fc0fbf1/data]
|
| 4/1 |
2026/11/22 07:27 |
action |
kernel-builder |
14m
Results: map[KernelObj:/app/workdir/cache/build/77faaf623a1bcf10fd86f3033df7a86fd72cbd40/data]
|
| 5/1 |
2026/11/22 07:42 |
action |
codesearch-prepare |
23m
Results: map[Index:codesearch-index]
|
| 6/1 |
2026/11/22 08:05 |
agent |
cause-finder |
8m
Model:
Results: map[CandidateCommits:[d532cddb6c6049ced414d64d83c6ce7149a6421a]]
Instruction:
You are an experienced Linux kernel developer tasked with identifying the commit
that introduced a kernel bug (cause bisection).
Your investigation strategy:
1. Establish the root cause first.
A root cause analysis of the bug is provided; verify its key claims against the actual
source code before relying on it.
Identify the specific functions, structs, invariants, or lines of code where the buggy
logic resides.
2. Use git tools (git-blame, git-log, git-show) to trace the history
of the affected functions and lines.
3. Trace past pure refactorings, code movements, formatting changes, or variable renames
to find the commit that actually introduced the buggy logic or broke an existing invariant.
4. Do NOT blame commits that merely added debugging or sanitizer checks (WARN_ON, BUG_ON,
KASAN/KMSAN/LOCKDEP annotations) that exposed an older bug, unless the check itself is
incorrect and is the bug.
5. Do NOT return a merge commit unless the bug was introduced by the merge conflict
resolution itself; otherwise identify the underlying non-merge commit.
6. Verify your hypothesis by inspecting the full commit diff with git-show and
confirming how the change introduced the exact condition described in the root cause.
Output rules:
- Returning a SINGLE commit in CandidateCommits (a 1-element list) is the expected norm
and is strongly preferred. A single commit gives maintainers a clear, directly actionable
result, whereas returning extra commits dilutes the report and notifies additional commit
authors unnecessarily.
- Once you identify the primary commit that introduced (or fixed) the bug, return ONLY that
commit in CandidateCommits. Do NOT include secondary or "contributing" commits such as
earlier background/foundation commits, preparatory or follow-up commits in the same
series, later refactorings, incomplete fix attempts, or commits that merely exposed or
enabled the code path (e.g. new callers, default config changes, or sanitizer/debug checks).
Mention those related commits in your text reply for context instead.
- Returning more than one commit (at most 3) is the rare exception, not the norm. Only return
multiple commits when:
1. There is genuine, unresolvable ambiguity between 2-3 equally plausible candidates after
thorough investigation, OR
2. The bug was strictly and inseparably introduced (or fixed) by 2-3 commits together, with
no single primary commit.
In those rare cases, order CandidateCommits by relevance with the most important/likely
commit FIRST.
- If you cannot determine the commit with confidence, return an empty CandidateCommits list
rather than guessing.
- Your text reply must provide a clear bisection log explaining the root cause of the bug,
the git history you traced, the commits you examined (with their hashes and titles), why
you ruled out other commits, and how you reached your conclusion.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The crash is:
Warning: Permanently added '10.128.0.74' (ED25519) to the list of known hosts.
[*] Starting reproducer for BUG: spinlock already unlocked in inet_shutdown...
[+] Detected 2 online CPUs.
[+] open /dev/nbd0 successful (fd=3).
[+] open /dev/nbd1 successful (fd=3).
[+] open /dev/nbd2 successful (fd=3).
[+] open /dev/nbd3 successful (fd=3).
[+] open /dev/nbd4 successful (fd=3).
[+] open /dev/nbd5 successful (fd=3).
[+] open /dev/nbd6 successful (fd=3).
[+] open /dev/nbd7 successful (fd=3).
[+] open /dev/nbd8 successful (fd=3).
[+] open /dev/nbd9 successful (fd=3).
[+] open /dev/nbd10 successful (fd=3).
[+] All 11 NBD devices initialized and verified.
[+] Server socket created.
[+] setsockopt(SO_REUSEADDR) successful.
[+] Server socket bound to 127.0.0.1.
[+] getsockname successful (port=43427).
[+] Server socket listening.
[+] Client socket created.
[+] Client socket connected.
[+] Accepted client connection on server.
[+] Server listening socket closed.
[+] Accepted peer socket closed (peer EOF).
[+] setsockopt(SOL_TCP, TCP_REPAIR, TCP_REPAIR_ON) successful.
[+] Shared TCP socket ready (fd=4).
[+] Started 5 reclassifier threads on devices 0..4.
[+] Started 6 runner threads on devices 5..10.
[+] Started disconnector thread.
[*] Racing NBD_SET_SOCK against NBD_DO_IT (recv_work) and inet_shutdown...
The following C code is a draft of the syscall sequence that triggers the kernel crash. Keep in mind
that it may lack the precise threading, sandboxing, and some arguments of a working reproducer:
#define _GNU_SOURCE
// Copyright 2026 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// IMPORTANT: Do not copy the macros or definitions below directly into your reproducer.
// Instead, add the following line to your reproducer:
// #include "race_toolkit.h"
// --- Race Condition Toolkit ---
// Macros and snippets for CPU pinning, memory barriers, and userfaultfd.
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/futex.h>
#include <linux/userfaultfd.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
// Unbuffered I/O: Ensure logs are written immediately.
#define SETUP_UNBUFFERED_IO() setvbuf(stdout, NULL, _IONBF, 0)
// CPU Pinning: Pin the current thread to a specific CPU core.
#define PIN_TO_CPU(cpu) \
do { \
cpu_set_t mask; \
CPU_ZERO(&mask); \
CPU_SET(cpu, &mask); \
if (sched_setaffinity(0, sizeof(mask), &mask) == -1) { \
perror("sched_setaffinity"); \
} \
} while (0)
// Memory Barrier: Ensure memory ordering.
#define MB() __atomic_thread_fence(__ATOMIC_SEQ_CST)
// Spin-wait Barrier: Wait until a memory location has a specific value.
// Best for tight race windows (low latency, no context switches).
#define WAIT_ON(addr, val) \
do { \
while (__atomic_load_n(addr, __ATOMIC_ACQUIRE) != (val)) \
; \
} while (0)
// Signal: Set a memory location to a specific value to release a WAIT_ON.
#define SIGNAL(addr, val) __atomic_store_n(addr, val, __ATOMIC_RELEASE)
// --- Timing Primitives ---
// Robust timing loops in VM environments (using CLOCK_MONOTONIC to avoid time(NULL) jumps).
static inline double timer_elapsed_sec(struct timespec* start)
{
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now) == -1) {
perror("clock_gettime(CLOCK_MONOTONIC) elapsed");
exit(1);
}
return (double)(now.tv_sec - start->tv_sec) + (double)(now.tv_nsec - start->tv_nsec) / 1e9;
}
// Initialize a monotonic timer variable.
#define TIMER_START(t) \
struct timespec t; \
if (clock_gettime(CLOCK_MONOTONIC, &t) == -1) { \
perror("clock_gettime(CLOCK_MONOTONIC) start"); \
exit(1); \
}
// Check if the elapsed time since 't' is less than 'sec' seconds.
#define TIMER_NOT_EXPIRED(t, sec) (timer_elapsed_sec(&(t)) < (double)(sec))
// Futex-based Event: Shared with syzkaller executor.
// Best for general synchronization or longer waits to save CPU.
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) {
fprintf(stderr, "event already set\n");
exit(1);
}
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
// userfaultfd setup: Register a memory range for page fault handling.
static int setup_uffd(void* addr, size_t len)
{
int uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
if (uffd == -1)
return -1;
struct uffdio_api api = {.api = UFFD_API, .features = 0};
if (ioctl(uffd, UFFDIO_API, &api) == -1) {
close(uffd);
return -1;
}
struct uffdio_register reg = {
.range = {.start = (uintptr_t)addr, .len = len},
.mode = UFFDIO_REGISTER_MODE_MISSING};
if (ioctl(uffd, UFFDIO_REGISTER, ®) == -1) {
close(uffd);
return -1;
}
return uffd;
}
// --- Guidance on Usage ---
// 1. Use WAIT_ON/SIGNAL for tight race conditions to avoid scheduling overhead.
// 2. Use event_t (futexes) for general coordination or when waiting for longer periods.
// 3. Always use PIN_TO_CPU to increase race probability on multi-core systems.
// 4. Use setup_uffd to register a memory range for page fault handling. This allows you to
// pause a thread accessing that memory until you handle the fault, creating a reliable
// and controllable race window.
// 5. Call SETUP_UNBUFFERED_IO() at the start of main() to ensure that logs are printed
// immediately. This is essential for understanding the exact interleaving of events
// when debugging race conditions.
// 6. For timing-based loops (e.g., running a race for 10 seconds), do NOT use time(NULL)
// or loops relying on real-time clocks, as VM clocks are highly unreliable and can fail or drift.
// Instead, use the robust monotonic timing primitives TIMER_START and TIMER_NOT_EXPIRED:
// TIMER_START(start);
// while (TIMER_NOT_EXPIRED(start, 10.0)) {
// // Your race logic here
// }
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/major.h>
#include <linux/nbd.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <pthread.h>
#include <sched.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#ifndef NBD_MAJOR
#define NBD_MAJOR 43
#endif
#ifndef NBD_SET_SOCK
#define NBD_SET_SOCK _IO(0xab, 0)
#endif
#ifndef NBD_DO_IT
#define NBD_DO_IT _IO(0xab, 3)
#endif
#ifndef NBD_CLEAR_SOCK
#define NBD_CLEAR_SOCK _IO(0xab, 4)
#endif
#ifndef NBD_DISCONNECT
#define NBD_DISCONNECT _IO(0xab, 8)
#endif
#ifndef SOL_TCP
#define SOL_TCP 6
#endif
#ifndef TCP_REPAIR
#define TCP_REPAIR 19
#endif
#ifndef TCP_REPAIR_ON
#define TCP_REPAIR_ON 1
#endif
#define TOTAL_DEVS 11
#define NUM_RECLASSIFIERS 5 /* Devices nbd0 through nbd4 */
#define NUM_RUNNERS 6 /* Devices nbd5 through nbd10 */
static int shared_sock = -1;
static volatile bool running = true;
static int num_cpus = 1;
static int open_nbd_device(int idx)
{
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%d", idx);
int fd = open(path, O_RDWR);
if (fd < 0 && errno == ENOENT) {
printf("[*] %s does not exist, attempting mknod...\n", path);
int res = mknod(path, S_IFBLK | 0660, makedev(NBD_MAJOR, idx));
if (res < 0) {
printf("[-] Failed to mknod %s: %s\n", path, strerror(errno));
return -1;
}
printf("[+] mknod %s successful.\n", path);
fd = open(path, O_RDWR);
}
if (fd < 0) {
printf("[-] Failed to open %s: %s\n", path, strerror(errno));
return -1;
}
printf("[+] open %s successful (fd=%d).\n", path, fd);
return fd;
}
static int setup_tcp_socket(void)
{
int srv = socket(AF_INET, SOCK_STREAM, 0);
if (srv < 0) {
printf("[-] Failed to socket(AF_INET, SOCK_STREAM, 0) for server: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server socket created.\n");
int opt = 1;
int res = setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (res < 0) {
printf("[-] Failed to setsockopt(SO_REUSEADDR): %s\n", strerror(errno));
exit(1);
}
printf("[+] setsockopt(SO_REUSEADDR) successful.\n");
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
sin.sin_port = 0;
res = bind(srv, (struct sockaddr*)&sin, sizeof(sin));
if (res < 0) {
printf("[-] Failed to bind server socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server socket bound to 127.0.0.1.\n");
socklen_t slen = sizeof(sin);
res = getsockname(srv, (struct sockaddr*)&sin, &slen);
if (res < 0) {
printf("[-] Failed to getsockname: %s\n", strerror(errno));
exit(1);
}
printf("[+] getsockname successful (port=%d).\n", ntohs(sin.sin_port));
res = listen(srv, 10);
if (res < 0) {
printf("[-] Failed to listen: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server socket listening.\n");
int cli = socket(AF_INET, SOCK_STREAM, 0);
if (cli < 0) {
printf("[-] Failed to socket(AF_INET, SOCK_STREAM, 0) for client: %s\n", strerror(errno));
exit(1);
}
printf("[+] Client socket created.\n");
res = connect(cli, (struct sockaddr*)&sin, sizeof(sin));
if (res < 0) {
printf("[-] Failed to connect client socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Client socket connected.\n");
int acc = accept(srv, NULL, NULL);
if (acc < 0) {
printf("[-] Failed to accept connection: %s\n", strerror(errno));
exit(1);
}
printf("[+] Accepted client connection on server.\n");
res = close(srv);
if (res < 0) {
printf("[-] Failed to close srv socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Server listening socket closed.\n");
res = close(acc);
if (res < 0) {
printf("[-] Failed to close acc socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Accepted peer socket closed (peer EOF).\n");
int repair = TCP_REPAIR_ON;
res = setsockopt(cli, SOL_TCP, TCP_REPAIR, &repair, sizeof(repair));
if (res < 0) {
printf("[-] Failed to setsockopt(SOL_TCP, TCP_REPAIR, TCP_REPAIR_ON): %s\n", strerror(errno));
exit(1);
}
printf("[+] setsockopt(SOL_TCP, TCP_REPAIR, TCP_REPAIR_ON) successful.\n");
return cli;
}
/* Devices nbd5 through nbd10: Continuously trigger recv_work and inet_shutdown */
static void* runner_worker(void* arg)
{
long dev_idx = (long)arg;
PIN_TO_CPU((int)(dev_idx % num_cpus));
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%ld", dev_idx);
while (__atomic_load_n(&running, __ATOMIC_RELAXED)) {
int fd = open(path, O_RDWR);
if (fd < 0) {
usleep(1000);
continue;
}
ioctl(fd, NBD_SET_SOCK, shared_sock);
ioctl(fd, NBD_DO_IT, 0);
ioctl(fd, NBD_CLEAR_SOCK, 0);
close(fd);
}
return NULL;
}
/* Devices nbd0 through nbd4: Continuously invoke nbd_reclassify_socket -> spin_lock_init */
static void* reclassifier_worker(void* arg)
{
long dev_idx = (long)arg;
PIN_TO_CPU((int)(dev_idx % num_cpus));
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%ld", dev_idx);
while (__atomic_load_n(&running, __ATOMIC_RELAXED)) {
int fd = open(path, O_RDWR);
if (fd < 0) {
usleep(1000);
continue;
}
for (int k = 0; k < 20 && __atomic_load_n(&running, __ATOMIC_RELAXED); k++) {
ioctl(fd, NBD_SET_SOCK, shared_sock);
ioctl(fd, NBD_CLEAR_SOCK, 0);
}
close(fd);
}
return NULL;
}
/* Disconnector thread: race NBD_DISCONNECT and direct user-space shutdown */
static void* disconnector_worker(void* arg)
{
(void)arg;
PIN_TO_CPU((int)(TOTAL_DEVS % num_cpus));
while (__atomic_load_n(&running, __ATOMIC_RELAXED)) {
for (int i = 0; i < TOTAL_DEVS; i++) {
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%d", i);
int fd = open(path, O_RDWR);
if (fd >= 0) {
ioctl(fd, NBD_DISCONNECT, 0);
close(fd);
}
}
shutdown(shared_sock, SHUT_RDWR);
usleep(1000);
}
return NULL;
}
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
printf("[*] Starting reproducer for BUG: spinlock already unlocked in inet_shutdown...\n");
num_cpus = (int)sysconf(_SC_NPROCESSORS_ONLN);
if (num_cpus < 1)
num_cpus = 1;
printf("[+] Detected %d online CPUs.\n", num_cpus);
/* Step 1: Pre-open / mknod all NBD devices (nbd0..nbd10) to verify availability */
for (int i = 0; i < TOTAL_DEVS; i++) {
int fd = open_nbd_device(i);
if (fd < 0) {
printf("[-] Failed to open/mknod /dev/nbd%d\n", i);
exit(1);
}
int res = ioctl(fd, NBD_CLEAR_SOCK, 0);
if (res < 0) {
printf("[-] Failed to ioctl(NBD_CLEAR_SOCK) on /dev/nbd%d: %s\n", i, strerror(errno));
exit(1);
}
res = close(fd);
if (res < 0) {
printf("[-] Failed to close /dev/nbd%d: %s\n", i, strerror(errno));
exit(1);
}
}
printf("[+] All %d NBD devices initialized and verified.\n", TOTAL_DEVS);
/* Step 2: Set up shared TCP socket with TCP_REPAIR enabled */
shared_sock = setup_tcp_socket();
if (shared_sock < 0) {
printf("[-] Failed to setup TCP socket: %s\n", strerror(errno));
exit(1);
}
printf("[+] Shared TCP socket ready (fd=%d).\n", shared_sock);
/* Step 3: Launch worker threads */
pthread_t threads[TOTAL_DEVS + 1];
/* Start reclassifier threads on devices 0..4 */
for (long i = 0; i < NUM_RECLASSIFIERS; i++) {
int res = pthread_create(&threads[i], NULL, reclassifier_worker, (void*)i);
if (res != 0) {
printf("[-] Failed to pthread_create reclassifier %ld: %s\n", i, strerror(res));
exit(1);
}
}
printf("[+] Started %d reclassifier threads on devices 0..%d.\n",
NUM_RECLASSIFIERS, NUM_RECLASSIFIERS - 1);
/* Start runner threads on devices 5..10 */
for (long i = 0; i < NUM_RUNNERS; i++) {
long dev_idx = NUM_RECLASSIFIERS + i;
int res = pthread_create(&threads[dev_idx], NULL, runner_worker, (void*)dev_idx);
if (res != 0) {
printf("[-] Failed to pthread_create runner %ld: %s\n", dev_idx, strerror(res));
exit(1);
}
}
printf("[+] Started %d runner threads on devices %d..%d.\n",
NUM_RUNNERS, NUM_RECLASSIFIERS, TOTAL_DEVS - 1);
/* Start disconnector thread */
int res = pthread_create(&threads[TOTAL_DEVS], NULL, disconnector_worker, NULL);
if (res != 0) {
printf("[-] Failed to pthread_create disconnector thread: %s\n", strerror(res));
exit(1);
}
printf("[+] Started disconnector thread.\n");
printf("[*] Racing NBD_SET_SOCK against NBD_DO_IT (recv_work) and inet_shutdown...\n");
TIMER_START(start);
while (TIMER_NOT_EXPIRED(start, 25.0) && __atomic_load_n(&running, __ATOMIC_RELAXED)) {
usleep(200000);
}
printf("[*] Race window completed, stopping threads...\n");
__atomic_store_n(&running, false, __ATOMIC_RELAXED);
for (int i = 0; i <= TOTAL_DEVS; i++) {
pthread_join(threads[i], NULL);
}
printf("[+] All worker threads stopped.\n");
for (int i = 0; i < TOTAL_DEVS; i++) {
char path[32];
snprintf(path, sizeof(path), "/dev/nbd%d", i);
int fd = open(path, O_RDWR);
if (fd >= 0) {
ioctl(fd, NBD_CLEAR_SOCK, 0);
close(fd);
}
}
res = close(shared_sock);
if (res < 0) {
printf("[-] Failed to close shared_sock: %s\n", strerror(errno));
exit(1);
}
printf("[+] Closed shared_sock successfully.\n");
printf("[+] Reproducer finished cleanly.\n");
return 0;
}
A previous root cause analysis of this bug (at commit 03897066069fd47caf2908183edf3b22b822ea73) concluded:
### Root Cause Analysis
#### 1. Involved Components and Functions
* **Files**:
* `drivers/block/nbd.c`: Contains `nbd_add_socket()`, `nbd_get_socket()`, and `nbd_reclassify_socket()`.
* `include/net/sock.h`: Defines `sock_allow_reclassification()` and `sock_lock_init_class_and_name()`.
* `net/ipv4/af_inet.c`: Contains `inet_shutdown()`.
* `net/core/sock.c`: Contains `lock_sock()`, `lock_sock_nested()`, and `release_sock()`.
* `kernel/locking/spinlock_debug.c`: Contains `debug_spin_unlock()`.
* **Structures and Fields**:
* `struct socket`: Represents the BSD socket; contains `struct sock *sk`.
* `struct sock`: Represents the network-layer socket; contains `socket_lock_t sk_lock`.
* `socket_lock_t`: Contains spinlock `slock`, user ownership flag `owned`, waitqueue `wq`, and lockdep map `dep_map`.
---
#### 2. Technical Mechanism and Trigger Sequence
1. **User Socket Ingestion into NBD**:
In `drivers/block/nbd.c`, when userspace issues an ioctl such as `NBD_SET_SOCK` or sends a netlink connect message, `nbd_add_socket()` resolves the user-supplied file descriptor into a `struct socket *` via `nbd_get_socket(nbd, arg, &err)`. Unlike kernel-internal sockets (e.g., in NVMe-oF or SunRPC, which are allocated via `sock_create_kern()` and never exposed to userspace), the NBD socket is an active, open file descriptor owned by userspace. Userspace threads can freely issue concurrent syscalls (e.g., `shutdown()`, `send()`, `recv()`) or attach the same socket fd across multiple NBD devices.
2. **Lock Reclassification Mechanism**:
To prevent lockdep from flagging circular dependencies between filesystem/block memory reclaim (`fs_reclaim`) and socket locks (`sk_lock`), `nbd_add_socket()` invokes `nbd_reclassify_socket(sock)`. Under `#ifdef CONFIG_DEBUG_LOCK_ALLOC`, this function checks whether the socket can be reclassified:
```c
static inline bool sock_allow_reclassification(const struct sock *csk)
{
struct sock *sk = (struct sock *)csk;
return !sock_owned_by_user_nocheck(sk) &&
!spin_is_locked(&sk->sk_lock.slock);
}
```
This check performs an unsynchronized read of `sk->sk_lock.owned` and `sk->sk_lock.slock` without acquiring either lock. Immediately after this condition evaluates to `true`, a concurrent thread can lock the socket.
3. **Reinitialization of an Active Lock**:
`nbd_reclassify_socket()` then invokes `sock_lock_init_class_and_name()`:
```c
#define sock_lock_init_class_and_name(sk, sname, skey, name, key) \
do { \
sk_owner_set(sk, THIS_MODULE); \
sk->sk_lock.owned = 0; \
init_waitqueue_head(&sk->sk_lock.wq); \
spin_lock_init(&(sk)->sk_lock.slock); \
debug_check_no_locks_freed((void *)&(sk)->sk_lock, \
sizeof((sk)->sk_lock)); \
lockdep_set_class_and_name(&(sk)->sk_lock.slock, \
(skey), (sname)); \
lockdep_init_map(&(sk)->sk_lock.dep_map, (name), (key), 0); \
} while (0)
```
Although called to update lockdep class annotations, `sock_lock_init_class_and_name()` was originally written for fresh socket initialization in `sock_lock_init()` (`net/core/sock.c`). Consequently, it unconditionally resets:
- `sk->sk_lock.slock` via `spin_lock_init()` (resetting the raw spinlock to 0 and its owner to unowned).
- `sk->sk_lock.owned = 0` (resetting the user-space ownership flag).
- `sk->sk_lock.wq` via `init_waitqueue_head()` (reinitializing the waitqueue head).
4. **The Race Condition with `inet_shutdown`**:
- **Thread 1 (runner/shutdown)** calls `inet_shutdown()` -> `release_sock(sk)`. Inside `release_sock()`, Thread 1 acquires `spin_lock_bh(&sk->sk_lock.slock)`.
- **Thread 2 (reclassifier)** enters `nbd_add_socket()` -> `nbd_reclassify_socket(sock)`. Right before Thread 1 acquired the lock, `sock_allow_reclassification(sk)` returned `true`. Thread 2 calls `sock_lock_init_class_and_name()`, which invokes `spin_lock_init(&sk->sk_lock.slock)` while Thread 1 is holding `slock`.
- `spin_lock_init()` zeroes the spinlock and marks it unlocked (`SPINLOCK_OWNER_INIT`).
- Thread 1 finishes processing in `release_sock()` and calls `spin_unlock_bh(&sk->sk_lock.slock)`.
- In `kernel/locking/spinlock_debug.c`, `debug_spin_unlock()` validates lock state:
```c
SPIN_BUG_ON(!raw_spin_is_locked(lock), lock, "already unlocked");
```
- Since Thread 2's `spin_lock_init()` cleared the locked state, `SPIN_BUG_ON()` triggers, resulting in the reported crash: `BUG: spinlock already unlocked in inet_shutdown`.
---
#### 3. Configuration Guard
`nbd_reclassify_socket()` is explicitly guarded by `#ifdef CONFIG_DEBUG_LOCK_ALLOC` in `drivers/block/nbd.c`:
```c
#ifdef CONFIG_DEBUG_LOCK_ALLOC
static void nbd_reclassify_socket(struct socket *sock) { ... }
#else
static inline void nbd_reclassify_socket(struct socket *sock) {}
#endif
```
In builds without `CONFIG_DEBUG_LOCK_ALLOC` (standard production kernels), `nbd_reclassify_socket()` compiles to an empty inline stub, so reclassification and destructive lock reinitialization do not occur.
Search for the commit that introduced this bug.
Reply: ### Bisection Conclusion
The bug was introduced by commit **`d532cddb6c6049ced414d64d83c6ce7149a6421a`** (`"nbd: Reclassify sockets to avoid lockdep circular dependency"`).
---
### Root Cause Verification & Git History Analysis
1. **Buggy Mechanism (`drivers/block/nbd.c`, `include/net/sock.h`)**:
- `nbd_add_socket()` resolves a user-supplied file descriptor via `nbd_get_socket()` (`sockfd_lookup()`) and calls `nbd_reclassify_socket(sock)` (`drivers/block/nbd.c:1299`).
- Under `CONFIG_DEBUG_LOCK_ALLOC`, `nbd_reclassify_socket()` checks `sock_allow_reclassification(sk)` (`include/net/sock.h:1835-1841`), which reads `sk->sk_lock.owned` and `spin_is_locked(&sk->sk_lock.slock)` **without synchronization**.
- If that check returns `true`, `nbd_reclassify_socket()` invokes `sock_lock_init_class_and_name()` (`include/net/sock.h:1694-1705`), which unconditionally executes:
- `sk->sk_lock.owned = 0;`
- `init_waitqueue_head(&sk->sk_lock.wq);`
- `spin_lock_init(&(sk)->sk_lock.slock);`
- Because NBD uses a userspace-owned socket fd rather than a kernel-private `sock_create_kern()` socket, another thread (e.g. `inet_shutdown()` -> `release_sock()` or softirq processing) can concurrently acquire `sk->sk_lock.slock` in the TOCTOU window after `sock_allow_reclassification(sk)` returns `true` and before `spin_lock_init()` runs.
- `spin_lock_init()` resets the active `slock` to unlocked while it is held, causing `debug_spin_unlock()` to trigger `BUG: spinlock already unlocked in inet_shutdown` when the holder unlocks it.
2. **Commits Examined**:
- **`d532cddb6c6049ced414d64d83c6ce7149a6421a` (`"nbd: Reclassify sockets to avoid lockdep circular dependency"`)** — **Introducing commit**:
Added `nbd_reclassify_socket()` and the call to it in `nbd_add_socket()`, applying `sock_allow_reclassification()` + `sock_lock_init_class_and_name()` (a pattern copied from `nvme-tcp` where sockets are kernel-internal) to user-supplied sockets in NBD.
- **`9280e6edf65662b6aafc8b704ad065b54c08b519` (`"nbd: don't warn when reclassifying a busy socket lock"`)** — Ruled out:
Only changed `if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))` to `if (!sock_allow_reclassification(sk))` in `nbd_reclassify_socket()`. The TOCTOU race and destructive `spin_lock_init()` when the lock is acquired *after* `sock_allow_reclassification(sk)` evaluates to `true` already existed in `d532cddb6c60`.
- **`fafc4e1ea1a4c1eb13a30c9426fb799f5efacbc3` (`"sock: tigthen lockdep checks for sock_owned_by_user"`)** — Ruled out:
Introduced `sock_allow_reclassification()` in `include/net/sock.h` for existing kernel-owned socket callers (`cifs`, `bluetooth`, `sunrpc`); NBD did not call it until `d532cddb6c60`.
- **`04d8fb23e520` (`"nbd: disallow NBD_SET_SOCK on an active device"`)** and **`285908f554fe` (`"nbd: remove queue freeze in nbd_add_socket"`)** — Ruled out:
Only modified `nbd->pid` checks and queue freezing in `nbd_add_socket()`, leaving `nbd_reclassify_socket()` and the race against userspace/concurrent socket operations unchanged.
- **`e14cadfd80d7` (`"tcp: add annotations around sk->sk_shutdown accesses"`)** — Ruled out:
Unrelated annotation changes in `inet_shutdown()`.
### Result
- **Introducing commit**: `d532cddb6c6049ced414d64d83c6ce7149a6421a`
|
| 7/2 |
2026/11/22 08:05 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 11912
output: 189
thoughts: 67
Thoughts: **My Thought Process: Tracing the Evolution of Socket Reclassification**
My primary objective is to gain a deep understanding of how socket reclassification is handled within the codebase, specifically focusing on the functions `nbd_reclassify_socket`, `sock_allow_reclassification`, and `sock_lock_init_class_and_name`. To achieve this, I'm initiating two parallel investigations:
1. **`codesearch-definition-source`**: I'm running this to pinpoint the exact definition and implementation of these functions. I want to see precisely where they are declared and what code comprises their bodies. This will give me the static picture of the current implementation.
2. **`git-log`**: Concurrently, I'm examining the Git history associated with these functions. This is crucial for understanding their evolution. I want to see when they were introduced, what changes have been made to them over time, and crucially, what motivated those changes. By tracing the commit messages and diffs, I can infer the design decisions, bug fixes, or feature additions that led to their current state.
By running these in parallel, I aim to get a comprehensive view: the "what" from `codesearch-definition-source` and the "how and why" from `git-log`. This dual approach will allow me to not only understand the current functionality but also to appreciate the context and rationale behind its development, which is essential for an expert's understanding.
|
| 8/2 |
2026/11/22 08:05 |
tool |
codesearch-definition-source |
0m
Args: map[Name:nbd_reclassify_socket]
Results: map[SourceCode:1245: static void nbd_reclassify_socket(struct socket *sock)
1246: {
1247: struct sock *sk = sock->sk;
1248:
1249: if (!sock_allow_reclassification(sk))
1250: return;
1251:
1252: switch (sk->sk_family) {
1253: case AF_INET:
1254: sock_lock_init_class_and_name(sk, "slock-AF_INET-NBD",
1255: &nbd_slock_key[0],
1256: "sk_lock-AF_INET-NBD",
1257: &nbd_key[0]);
1258: break;
1259: case AF_INET6:
1260: sock_lock_init_class_and_name(sk, "slock-AF_INET6-NBD",
1261: &nbd_slock_key[1],
1262: "sk_lock-AF_INET6-NBD",
1263: &nbd_key[1]);
1264: break;
1265: case AF_UNIX:
1266: sock_lock_init_class_and_name(sk, "slock-AF_UNIX-NBD",
1267: &nbd_slock_key[2],
1268: "sk_lock-AF_UNIX-NBD",
1269: &nbd_key[2]);
1270: break;
1271: }
1272: }
SourceFile:drivers/block/nbd.c]
|
| 9/2 |
2026/11/22 08:05 |
tool |
codesearch-definition-source |
0m
Args:
Results: map[SourceCode:1277: static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1278: bool netlink)
1279: {
1280: struct nbd_config *config = nbd->config;
1281: struct socket *sock;
1282: struct nbd_sock **socks;
1283: struct nbd_sock *nsock;
1284: int err;
1285:
1286: /* Arg will be cast to int, check it to avoid overflow */
1287: if (arg > INT_MAX)
1288: return -EINVAL;
1289:
1290: if (nbd->pid) {
1291: dev_err(disk_to_dev(nbd->disk),
1292: "Cannot add socket to a running device\n");
1293: return -EBUSY;
1294: }
1295:
1296: sock = nbd_get_socket(nbd, arg, &err);
1297: if (!sock)
1298: return err;
1299: nbd_reclassify_socket(sock);
1300:
1301: if (!netlink && !nbd->task_setup &&
1302: !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1303: nbd->task_setup = current;
1304:
1305: if (!netlink &&
1306: (nbd->task_setup != current ||
1307: test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1308: dev_err(disk_to_dev(nbd->disk),
1309: "Device being setup by another task");
1310: err = -EBUSY;
1311: goto put_socket;
1312: }
1313:
1314: nsock = kzalloc_obj(*nsock);
1315: if (!nsock) {
1316: err = -ENOMEM;
1317: goto put_socket;
1318: }
1319:
1320: socks = krealloc(config->socks, (config->num_connections + 1) *
1321: sizeof(struct nbd_sock *), GFP_KERNEL);
1322: if (!socks) {
1323: kfree(nsock);
1324: err = -ENOMEM;
1325: goto put_socket;
1326: }
1327:
1328: config->socks = socks;
1329:
1330: nsock->fallback_index = -1;
1331: nsock->dead = false;
1332: mutex_init(&nsock->tx_lock);
1333: nsock->sock = sock;
1334: nsock->pending = NULL;
1335: nsock->sent = 0;
1336: nsock->cookie = 0;
1337: INIT_WORK(&nsock->work, nbd_pending_cmd_work);
1338: socks[config->num_connections++] = nsock;
1339: atomic_inc(&config->live_connections);
1340:
1341: return 0;
1342:
1343: put_socket:
1344: sockfd_put(sock);
1345: return err;
1346: }
SourceFile:drivers/block/nbd.c]
|
| 10/2 |
2026/11/22 08:05 |
tool |
codesearch-definition-source |
0m
Args: map[Name:sock_allow_reclassification]
Results: map[SourceCode:1834: /* no reclassification while locks are held */
1835: static inline bool sock_allow_reclassification(const struct sock *csk)
1836: {
1837: struct sock *sk = (struct sock *)csk;
1838:
1839: return !sock_owned_by_user_nocheck(sk) &&
1840: !spin_is_locked(&sk->sk_lock.slock);
1841: }
SourceFile:include/net/sock.h]
|
| 11/2 |
2026/11/22 08:05 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[Name:sock_lock_init_class_and_name]
Results: map[SourceCode: SourceFile:]
|
| 12/2 |
2026/11/22 08:05 |
tool |
git-log |
0m
Args: map[SourcePath:drivers/block/nbd.c SymbolName:nbd_reclassify_socket]
Results: map[Output:9280e6edf656 nbd: don't warn when reclassifying a busy socket lock
d532cddb6c60 nbd: Reclassify sockets to avoid lockdep circular dependency
]
|
| 13/2 |
2026/11/22 08:06 |
tool |
git-log |
6m
Args: map[CodeRegexp:sock_allow_reclassification|sock_lock_init_class_and_name]
Results: map[Output:9280e6edf656 nbd: don't warn when reclassifying a busy socket lock
d532cddb6c60 nbd: Reclassify sockets to avoid lockdep circular dependency
2caaa52c1a44 nvme-tcp: move nvme_tcp_reclassify_socket()
de41cbc64d02 RDMA/rxe: let rxe_reclassify_recv_socket() call sk_owner_put()
80a85a771deb RDMA/rxe: reclassify sockets in order to avoid false positives from lockdep
3a2c32d357db RDMA/siw: reclassify sockets in order to avoid false positives from lockdep
752e2217d789 smc: Fix lockdep false-positive for IPPROTO_SMC.
0bb2f7a1ad1f net: Fix null-ptr-deref by sock_lock_init_class_and_name() and rmmod.
8617e85e04bd mptcp: pm: split in-kernel PM specific code
cee4034a3db1 mptcp: fix lockdep false positive in mptcp_pm_nl_create_listen_socket()
]
|
| 14/2 |
2026/11/22 08:12 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 14224
output: 96
thoughts: 111
Thoughts: **Investigating a Potential Lockdep Issue in the Network Block Device (nbd) Driver**
I'm looking at these two recent commits related to the Network Block Device (nbd) driver: `9280e6edf656` and `d532cddb6c60`. The commit messages suggest a focus on socket reclassification and potential lockdep circular dependencies. My immediate thought is to delve deeper into the specifics of these changes.
To get a thorough understanding, I plan to use `git show` on both commit hashes. This will allow me to examine the diffs, understand exactly what code was added, removed, or modified in each case, and get the commit messages and author information.
Beyond just the commit details, I suspect the underlying issue might be related to how sockets are managed and locked within the nbd driver, specifically in conjunction with the lockdep mechanism. To get more context on the locking primitives being used, I intend to examine the `include/net/sock.h` header file. My specific target is around line 1834, where I expect to find the definition or usage of `sock_lock_init_class_and_name`. Understanding how this function is used, its parameters, and its role in initializing socket locks is crucial for grasping the implications of the nbd driver's changes.
My hypothesis is that the nbd driver was encountering a situation where the order of acquiring locks on sockets was leading to a deadlock scenario that lockdep was flagging. The commits likely represent a refactoring to alter this lock acquisition order or to adjust how socket locking classes are managed to prevent this circular dependency. The first commit, specifically mentioning "don't warn when reclassifying a busy socket lock," implies that a warning was being generated due to a legitimate, albeit problematic, reclassification. The second commit, "Reclassify sockets to avoid lockdep circular dependency," sounds like the actual fix that addresses the root cause identified by the warning. I need to see how `sock_lock_init_class_and_name` fits into this picture to fully appreciate the solution.
|
| 15/2 |
2026/11/22 08:12 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d532cddb6c6049ced414d64d83c6ce7149a6421a
Author: Eric Dumazet <edumazet@kernel.org>
Date: Sat Jun 13 04:26:19 2026 +0000
nbd: Reclassify sockets to avoid lockdep circular dependency
syzbot reported a possible circular locking dependency in udp_sendmsg()
where fs_reclaim can be triggered while holding sk_lock, and fs_reclaim
can eventually depend on another sk_lock (e.g., if NBD is used for swap
or writeback and NBD uses TLS/TCP which acquires sk_lock).
Since the UDP socket and the NBD TCP/TLS socket are different, this is a
false positive. Fix this by reclassifying NBD sockets to a separate lock
class when they are added to the NBD device.
This is similar to what nvme-tcp and other network block devices do.
Fixes: ffa1e7ada456 ("block: Make request_queue lockdep splats show up earlier")
Reported-by: syzbot+607cdcf978b3e79da878@syzkaller.appspotmail.com
Closes: https://lore.kernel.org/netdev/6a2cdafe.428ffe26.258b27.0161.GAE@google.com/T/#u
Signed-off-by: Eric Dumazet <edumazet@google.com>
Link: https://patch.msgid.link/20260613042619.1108126-1-edumazet@google.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index e2fe9e3308fc..3a585a0c882a 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -1238,6 +1238,42 @@ static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
return sock;
}
+#ifdef CONFIG_DEBUG_LOCK_ALLOC
+static struct lock_class_key nbd_key[3];
+static struct lock_class_key nbd_slock_key[3];
+
+static void nbd_reclassify_socket(struct socket *sock)
+{
+ struct sock *sk = sock->sk;
+
+ if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))
+ return;
+
+ switch (sk->sk_family) {
+ case AF_INET:
+ sock_lock_init_class_and_name(sk, "slock-AF_INET-NBD",
+ &nbd_slock_key[0],
+ "sk_lock-AF_INET-NBD",
+ &nbd_key[0]);
+ break;
+ case AF_INET6:
+ sock_lock_init_class_and_name(sk, "slock-AF_INET6-NBD",
+ &nbd_slock_key[1],
+ "sk_lock-AF_INET6-NBD",
+ &nbd_key[1]);
+ break;
+ case AF_UNIX:
+ sock_lock_init_class_and_name(sk, "slock-AF_UNIX-NBD",
+ &nbd_slock_key[2],
+ "sk_lock-AF_UNIX-NBD",
+ &nbd_key[2]);
+ break;
+ }
+}
+#else
+static inline void nbd_reclassify_socket(struct socket *sock) {}
+#endif
+
static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
bool netlink)
{
@@ -1254,6 +1290,7 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
sock = nbd_get_socket(nbd, arg, &err);
if (!sock)
return err;
+ nbd_reclassify_socket(sock);
/*
* We need to make sure we don't get any errant requests while we're
]
|
| 16/2 |
2026/11/22 08:12 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 9280e6edf65662b6aafc8b704ad065b54c08b519
Author: Deepanshu Kartikey <kartikey406@gmail.com>
Date: Mon Jun 22 05:22:55 2026 +0530
nbd: don't warn when reclassifying a busy socket lock
nbd_reclassify_socket() warns via WARN_ON_ONCE() if the socket lock is
held at the point of reclassification. That assertion was copied from
nvme-tcp, where the socket is created internally by the kernel
(sock_create_kern()) and is never visible to user space, so the lock
is guaranteed to be free.
NBD is different: the socket is looked up from a user-supplied fd in
nbd_get_socket(), and user space retains that fd. A concurrent syscall
on the same socket (or softirq processing taking bh_lock_sock() on a
connected TCP socket) can legitimately hold the lock at the instant
NBD reclassifies it. sock_allow_reclassification() then returns false
and the WARN_ON_ONCE() fires, which turns into a crash under
panic_on_warn. This is reachable by simply racing NBD_CMD_CONNECT
against socket activity on the same fd, as reported by syzbot.
Hitting a held lock here is expected for an externally owned socket and
is not a kernel bug, so skip reclassification silently instead of
warning. Reclassification is a lockdep-only annotation, so skipping it
in the rare racing case is harmless.
Reported-by: syzbot+6b85d1e39a5b8ed9a954@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=6b85d1e39a5b8ed9a954
Fixes: d532cddb6c60 ("nbd: Reclassify sockets to avoid lockdep circular dependency")
Signed-off-by: Deepanshu Kartikey <kartikey406@gmail.com>
Acked-by: Eric Dumazet <edumazet@google.com>
Link: https://patch.msgid.link/20260621235255.66015-1-kartikey406@gmail.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index 3a585a0c882a..8f10762e90ef 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -1246,7 +1246,7 @@ static void nbd_reclassify_socket(struct socket *sock)
{
struct sock *sk = sock->sk;
- if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))
+ if (!sock_allow_reclassification(sk))
return;
switch (sk->sk_family) {
]
|
| 17/2 |
2026/11/22 08:12 |
tool |
read-file |
0m
Args: map[File:include/net/sock.h FirstLine:1810 LineCount:60]
Results: map[Contents:1810: WARN_ON_ONCE(lockdep_sock_is_held(sk) && debug_locks);
1811: #endif
1812: }
1813:
1814: static inline bool sock_owned_by_user(const struct sock *sk)
1815: {
1816: sock_owned_by_me(sk);
1817: return sk->sk_lock.owned;
1818: }
1819:
1820: static inline bool sock_owned_by_user_nocheck(const struct sock *sk)
1821: {
1822: return sk->sk_lock.owned;
1823: }
1824:
1825: static inline void sock_release_ownership(struct sock *sk)
1826: {
1827: DEBUG_NET_WARN_ON_ONCE(!sock_owned_by_user_nocheck(sk));
1828: sk->sk_lock.owned = 0;
1829:
1830: /* The sk_lock has mutex_unlock() semantics: */
1831: mutex_release(&sk->sk_lock.dep_map, _RET_IP_);
1832: }
1833:
1834: /* no reclassification while locks are held */
1835: static inline bool sock_allow_reclassification(const struct sock *csk)
1836: {
1837: struct sock *sk = (struct sock *)csk;
1838:
1839: return !sock_owned_by_user_nocheck(sk) &&
1840: !spin_is_locked(&sk->sk_lock.slock);
1841: }
1842:
1843: struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
1844: struct proto *prot, int kern);
1845: void sk_free(struct sock *sk);
1846: void sk_net_refcnt_upgrade(struct sock *sk);
1847: void sk_destruct(struct sock *sk);
1848: struct sock *sk_clone(const struct sock *sk, const gfp_t priority, bool lock);
1849:
1850: static inline struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
1851: {
1852: return sk_clone(sk, priority, true);
1853: }
1854:
1855: struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
1856: gfp_t priority);
1857: void sock_wfree(struct sk_buff *skb);
1858: void __sock_wfree(struct sk_buff *skb);
1859: void tcp_wfree(struct sk_buff *skb);
1860:
1861: static inline bool is_skb_wmem(const struct sk_buff *skb)
1862: {
1863: return skb->destructor == sock_wfree ||
1864: (IS_ENABLED(CONFIG_INET) && skb->destructor == __sock_wfree) ||
1865: (IS_ENABLED(CONFIG_INET) && skb->destructor == tcp_wfree);
1866: }
1867:
1868: struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size,
1869: gfp_t priority);
]
|
| 18/2 |
2026/11/22 08:12 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 17369
output: 86
thoughts: 57
Thoughts: **My Investigative Process for `sock_lock_init_class_and_name`**
Right, to be absolutely certain about the intricacies of `sock_lock_init_class_and_name`, my immediate instinct is to verify its definition. I'll leverage `grepper` for a quick and precise location of this function. However, being an expert means I can't just stop at a static definition; context and history are paramount. Therefore, I'll be diving into the `git log` for both `include/net/sock.h` and `net/core/sock.c`. This dual approach – checking the current definition with `grepper` and then exploring the historical evolution and potential changes via `git log` – ensures that I have a 100% thorough understanding of its implementation, its dependencies, and any relevant changes over time. This meticulousness is crucial for truly grasping its role and impact within the networking stack.
|
| 19/2 |
2026/11/22 08:13 |
tool |
grepper |
0m
Args: map[Expression:sock_lock_init_class_and_name PathPrefixes:[include/ net/]]
Results: map[Output:include/net/sock.h=242=struct sk_filter;
--
include/net/sock.h-363- * @sk_owner: reference to the real owner of the socket that calls
include/net/sock.h:364: * sock_lock_init_class_and_name().
include/net/sock.h-365- */
--
include/net/sock.h=1683=static inline void sk_owner_put(struct sock *sk)
--
include/net/sock.h-1693- */
include/net/sock.h:1694:#define sock_lock_init_class_and_name(sk, sname, skey, name, key) \
include/net/sock.h-1695-do { \
--
net/bluetooth/af_bluetooth.c=71=void bt_sock_reclassify_lock(struct sock *sk, int proto)
--
net/bluetooth/af_bluetooth.c-75-
net/bluetooth/af_bluetooth.c:76: sock_lock_init_class_and_name(sk,
net/bluetooth/af_bluetooth.c-77- bt_slock_key_strings[proto], &bt_slock_key[proto],
--
net/core/sock.c=2214=static inline void sock_lock_init(struct sock *sk)
--
net/core/sock.c-2218- if (sk->sk_kern_sock)
net/core/sock.c:2219: sock_lock_init_class_and_name(
net/core/sock.c-2220- sk,
--
net/core/sock.c-2225- else
net/core/sock.c:2226: sock_lock_init_class_and_name(
net/core/sock.c-2227- sk,
--
net/mptcp/pm_kernel.c=852=static int mptcp_pm_nl_create_listen_socket(struct sock *sk,
--
net/mptcp/pm_kernel.c-876- */
net/mptcp/pm_kernel.c:877: sock_lock_init_class_and_name(newsk,
net/mptcp/pm_kernel.c-878- is_ipv6 ? "mlock-AF_INET6" : "mlock-AF_INET",
--
net/smc/af_smc.c=395=void smc_sk_init(struct net *net, struct sock *sk, int protocol)
--
net/smc/af_smc.c-407- INIT_LIST_HEAD(&smc->accept_q);
net/smc/af_smc.c:408: sock_lock_init_class_and_name(sk, "slock-AF_SMC", &smc_slock_key,
net/smc/af_smc.c-409- "sk_lock-AF_SMC", &smc_key);
--
net/sunrpc/svcsock.c=95=static void svc_reclassify_socket(struct socket *sock)
--
net/sunrpc/svcsock.c-103- case AF_INET:
net/sunrpc/svcsock.c:104: sock_lock_init_class_and_name(sk, "slock-AF_INET-NFSD",
net/sunrpc/svcsock.c-105- &svc_slock_key[0],
--
net/sunrpc/svcsock.c-110- case AF_INET6:
net/sunrpc/svcsock.c:111: sock_lock_init_class_and_name(sk, "slock-AF_INET6-NFSD",
net/sunrpc/svcsock.c-112- &svc_slock_key[1],
--
net/sunrpc/xprtsock.c=1891=static inline void xs_reclassify_socketu(struct socket *sock)
--
net/sunrpc/xprtsock.c-1894-
net/sunrpc/xprtsock.c:1895: sock_lock_init_class_and_name(sk, "slock-AF_LOCAL-RPC",
net/sunrpc/xprtsock.c-1896- &xs_slock_key[0], "sk_lock-AF_LOCAL-RPC", &xs_key[0]);
--
net/sunrpc/xprtsock.c=1899=static inline void xs_reclassify_socket4(struct socket *sock)
--
net/sunrpc/xprtsock.c-1902-
net/sunrpc/xprtsock.c:1903: sock_lock_init_class_and_name(sk, "slock-AF_INET-RPC",
net/sunrpc/xprtsock.c-1904- &xs_slock_key[1], "sk_lock-AF_INET-RPC", &xs_key[1]);
--
net/sunrpc/xprtsock.c=1907=static inline void xs_reclassify_socket6(struct socket *sock)
--
net/sunrpc/xprtsock.c-1910-
net/sunrpc/xprtsock.c:1911: sock_lock_init_class_and_name(sk, "slock-AF_INET6-RPC",
net/sunrpc/xprtsock.c-1912- &xs_slock_key[2], "sk_lock-AF_INET6-RPC", &xs_key[2]);
]
|
| 20/2 |
2026/11/22 08:13 |
tool |
git-log |
0m
Args: map[CodeRegexp:sock_lock_init_class_and_name PathPrefix:include/net/sock.h]
Results: map[Output:0bb2f7a1ad1f net: Fix null-ptr-deref by sock_lock_init_class_and_name() and rmmod.
dc6b9b78234f net: include/net/sock.h cleanup
ed07536ed673 [PATCH] lockdep: annotate nfs/nfsd in-kernel sockets
]
|
| 21/2 |
2026/11/22 08:13 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 19048
output: 109
thoughts: 51
Thoughts: **My Investigative Process**
My immediate thought is that I need to gain a comprehensive understanding of the `sock_allow_reclassification` functionality. To achieve this, I'm planning a two-pronged approach. Firstly, I'll delve into the source code itself. Specifically, I'm going to examine the `read-file` operation on `include/net/sock.h` within the line range of 1680 to 1715. This will allow me to see the current implementation details and how the reclassification mechanism is structured at its core.
Secondly, and crucially for understanding the evolution and rationale behind this code, I will perform a `git-log` on `sock_allow_reclassification`. This will give me a historical perspective, showing me who made changes, when they were made, and importantly, the commit messages associated with those changes. This historical context is vital for me to grasp the original intent, any subsequent refinements or bug fixes, and the overall journey of this particular piece of code. By combining a look at the present state with its complete history, I'm confident I'll have a thorough grasp of `sock_allow_reclassification`.
|
| 22/2 |
2026/11/22 08:13 |
tool |
read-file |
0m
Args: map[File:include/net/sock.h FirstLine:1680 LineCount:35]
Results: map[Contents:1680: {
1681: }
1682:
1683: static inline void sk_owner_put(struct sock *sk)
1684: {
1685: }
1686: #endif
1687: /*
1688: * Macro so as to not evaluate some arguments when
1689: * lockdep is not enabled.
1690: *
1691: * Mark both the sk_lock and the sk_lock.slock as a
1692: * per-address-family lock class.
1693: */
1694: #define sock_lock_init_class_and_name(sk, sname, skey, name, key) \
1695: do { \
1696: sk_owner_set(sk, THIS_MODULE); \
1697: sk->sk_lock.owned = 0; \
1698: init_waitqueue_head(&sk->sk_lock.wq); \
1699: spin_lock_init(&(sk)->sk_lock.slock); \
1700: debug_check_no_locks_freed((void *)&(sk)->sk_lock, \
1701: sizeof((sk)->sk_lock)); \
1702: lockdep_set_class_and_name(&(sk)->sk_lock.slock, \
1703: (skey), (sname)); \
1704: lockdep_init_map(&(sk)->sk_lock.dep_map, (name), (key), 0); \
1705: } while (0)
1706:
1707: static inline bool lockdep_sock_is_held(const struct sock *sk)
1708: {
1709: return lockdep_is_held(&sk->sk_lock) ||
1710: lockdep_is_held(&sk->sk_lock.slock);
1711: }
1712:
1713: void lock_sock_nested(struct sock *sk, int subclass);
1714:
]
|
| 23/2 |
2026/11/22 08:13 |
tool |
git-log |
0m
Args: map[CodeRegexp:sock_allow_reclassification PathPrefix:include/net/sock.h]
Results: map[Output:fafc4e1ea1a4 sock: tigthen lockdep checks for sock_owned_by_user
]
|
| 24/2 |
2026/11/22 08:13 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/block/nbd.c]
Results: map[Output:326d49039c10 nbd: add pre_defined_connections module parameter for pre-created devices
a9d414b4a15c nbd: remove queue freeze for newly created nbd from netlink path
f8d21c590e55 nbd: factor out a nbd_genl_foreach_sock
db285268df79 nbd: skip queue freeze when setting size at device startup
285908f554fe nbd: remove queue freeze in nbd_add_socket
]
|
| 25/2 |
2026/11/22 08:13 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 19986
output: 81
thoughts: 99
Thoughts: **My Internal Monologue on NBD Socket Handling**
Alright, I need to get a really solid grip on this `sock_allow_reclassification` and `sock_lock_init_class_and_name` situation. To do that, I'm going to dive deep into the commit history. Specifically, I'll be examining `git show` output for commits `fafc4e1ea1a4` and `ed07536ed673`. My goal here is to fully comprehend the *why* and *how* these functions are interacting and what their precise role is in the socket management within the NBD driver.
Beyond just those specific functions, I also need to trace the flow of socket interaction within the `nbd.c` file. This means I'll be looking at `nbd_get_socket` to understand how the socket is initially obtained and integrated. Crucially, I also need to dissect `nbd_ioctl` and its internal helper `__nbd_ioctl`. My assumption is that these are the primary points where the NBD device interacts with the underlying socket infrastructure, and therefore, where the `sock_allow_reclassification` and `sock_lock_init_class_and_name` functions are likely to be invoked or have their effects felt. This focused investigation should give me a comprehensive understanding of the socket lifecycle and classification within the NBD context.
|
| 26/2 |
2026/11/22 08:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit fafc4e1ea1a4c1eb13a30c9426fb799f5efacbc3
Author: Hannes Frederic Sowa <hannes@stressinduktion.org>
Date: Fri Apr 8 15:11:27 2016 +0200
sock: tigthen lockdep checks for sock_owned_by_user
sock_owned_by_user should not be used without socket lock held. It seems
to be a common practice to check .owned before lock reclassification, so
provide a little help to abstract this check away.
Cc: linux-cifs@vger.kernel.org
Cc: linux-bluetooth@vger.kernel.org
Cc: linux-nfs@vger.kernel.org
Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org>
Signed-off-by: David S. Miller <davem@davemloft.net>
diff --git a/fs/cifs/connect.c b/fs/cifs/connect.c
index 6f62ac821a84..2e2e0a6242d6 100644
--- a/fs/cifs/connect.c
+++ b/fs/cifs/connect.c
@@ -2918,7 +2918,7 @@ static inline void
cifs_reclassify_socket4(struct socket *sock)
{
struct sock *sk = sock->sk;
- BUG_ON(sock_owned_by_user(sk));
+ BUG_ON(!sock_allow_reclassification(sk));
sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
&cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
}
@@ -2927,7 +2927,7 @@ static inline void
cifs_reclassify_socket6(struct socket *sock)
{
struct sock *sk = sock->sk;
- BUG_ON(sock_owned_by_user(sk));
+ BUG_ON(!sock_allow_reclassification(sk));
sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
&cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
}
diff --git a/include/net/sock.h b/include/net/sock.h
index 81d6fecec0a2..baba58770ac5 100644
--- a/include/net/sock.h
+++ b/include/net/sock.h
@@ -1316,21 +1316,6 @@ static inline void sk_wmem_free_skb(struct sock *sk, struct sk_buff *skb)
__kfree_skb(skb);
}
-/* Used by processes to "lock" a socket state, so that
- * interrupts and bottom half handlers won't change it
- * from under us. It essentially blocks any incoming
- * packets, so that we won't get any new data or any
- * packets that change the state of the socket.
- *
- * While locked, BH processing will add new packets to
- * the backlog queue. This queue is processed by the
- * owner of the socket lock right before it is released.
- *
- * Since ~2.3.5 it is also exclusive sleep lock serializing
- * accesses from user process context.
- */
-#define sock_owned_by_user(sk) ((sk)->sk_lock.owned)
-
static inline void sock_release_ownership(struct sock *sk)
{
if (sk->sk_lock.owned) {
@@ -1403,6 +1388,35 @@ static inline void unlock_sock_fast(struct sock *sk, bool slow)
spin_unlock_bh(&sk->sk_lock.slock);
}
+/* Used by processes to "lock" a socket state, so that
+ * interrupts and bottom half handlers won't change it
+ * from under us. It essentially blocks any incoming
+ * packets, so that we won't get any new data or any
+ * packets that change the state of the socket.
+ *
+ * While locked, BH processing will add new packets to
+ * the backlog queue. This queue is processed by the
+ * owner of the socket lock right before it is released.
+ *
+ * Since ~2.3.5 it is also exclusive sleep lock serializing
+ * accesses from user process context.
+ */
+
+static inline bool sock_owned_by_user(const struct sock *sk)
+{
+#ifdef CONFIG_LOCKDEP
+ WARN_ON(!lockdep_sock_is_held(sk));
+#endif
+ return sk->sk_lock.owned;
+}
+
+/* no reclassification while locks are held */
+static inline bool sock_allow_reclassification(const struct sock *csk)
+{
+ struct sock *sk = (struct sock *)csk;
+
+ return !sk->sk_lock.owned && !spin_is_locked(&sk->sk_lock.slock);
+}
struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
struct proto *prot, int kern);
diff --git a/net/bluetooth/af_bluetooth.c b/net/bluetooth/af_bluetooth.c
index 955eda93e66f..3df7aefb7663 100644
--- a/net/bluetooth/af_bluetooth.c
+++ b/net/bluetooth/af_bluetooth.c
@@ -65,7 +65,7 @@ static const char *const bt_slock_key_strings[BT_MAX_PROTO] = {
void bt_sock_reclassify_lock(struct sock *sk, int proto)
{
BUG_ON(!sk);
- BUG_ON(sock_owned_by_user(sk));
+ BUG_ON(!sock_allow_reclassification(sk));
sock_lock_init_class_and_name(sk,
bt_slock_key_strings[proto], &bt_slock_key[proto],
diff --git a/net/llc/llc_proc.c b/net/llc/llc_proc.c
index 1a3c7e0f5d0d..29c509c54bb2 100644
--- a/net/llc/llc_proc.c
+++ b/net/llc/llc_proc.c
@@ -195,7 +195,7 @@ static int llc_seq_core_show(struct seq_file *seq, void *v)
timer_pending(&llc->pf_cycle_timer.timer),
timer_pending(&llc->rej_sent_timer.timer),
timer_pending(&llc->busy_state_timer.timer),
- !!sk->sk_backlog.tail, !!sock_owned_by_user(sk));
+ !!sk->sk_backlog.tail, !!sk->sk_lock.owned);
out:
return 0;
}
diff --git a/net/sunrpc/svcsock.c b/net/sunrpc/svcsock.c
index 71d6072664d2..dadfec66dbd8 100644
--- a/net/sunrpc/svcsock.c
+++ b/net/sunrpc/svcsock.c
@@ -85,8 +85,7 @@ static void svc_reclassify_socket(struct socket *sock)
{
struct sock *sk = sock->sk;
- WARN_ON_ONCE(sock_owned_by_user(sk));
- if (sock_owned_by_user(sk))
+ if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))
return;
switch (sk->sk_family) {
diff --git a/net/sunrpc/xprtsock.c b/net/sunrpc/xprtsock.c
index c1fc7b20bbc1..d0756ac5c0f2 100644
--- a/net/sunrpc/xprtsock.c
+++ b/net/sunrpc/xprtsock.c
@@ -1880,8 +1880,7 @@ static inline void xs_reclassify_socket6(struct socket *sock)
static inline void xs_reclassify_socket(int family, struct socket *sock)
{
- WARN_ON_ONCE(sock_owned_by_user(sock->sk));
- if (sock_owned_by_user(sock->sk))
+ if (WARN_ON_ONCE(!sock_allow_reclassification(sock->sk)))
return;
switch (family) {
]
|
| 27/2 |
2026/11/22 08:13 |
tool |
codesearch-definition-source |
0m
Args:
Results: map[SourceCode:1213: static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1214: int *err)
1215: {
1216: struct socket *sock;
1217:
1218: *err = 0;
1219: sock = sockfd_lookup(fd, err);
1220: if (!sock)
1221: return NULL;
1222:
1223: if (!sk_is_tcp(sock->sk) &&
1224: !sk_is_stream_unix(sock->sk)) {
1225: dev_err(disk_to_dev(nbd->disk), "Unsupported socket: should be TCP or UNIX.\n");
1226: *err = -EINVAL;
1227: sockfd_put(sock);
1228: return NULL;
1229: }
1230:
1231: if (sock->ops->shutdown == sock_no_shutdown) {
1232: dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1233: *err = -EINVAL;
1234: sockfd_put(sock);
1235: return NULL;
1236: }
1237:
1238: return sock;
1239: }
SourceFile:drivers/block/nbd.c]
|
| 28/2 |
2026/11/22 08:13 |
tool |
codesearch-definition-source |
0m
Args:
Results: map[SourceCode:1633: /* Must be called with config_lock held */
1634: static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1635: unsigned int cmd, unsigned long arg)
1636: {
1637: struct nbd_config *config = nbd->config;
1638: loff_t bytesize;
1639:
1640: switch (cmd) {
1641: case NBD_DISCONNECT:
1642: return nbd_disconnect(nbd);
1643: case NBD_CLEAR_SOCK:
1644: nbd_clear_sock_ioctl(nbd);
1645: return 0;
1646: case NBD_SET_SOCK:
1647: return nbd_add_socket(nbd, arg, false);
1648: case NBD_SET_BLKSIZE:
1649: return nbd_set_size(nbd, config->bytesize, arg);
1650: case NBD_SET_SIZE:
1651: return nbd_set_size(nbd, arg, nbd_blksize(config));
1652: case NBD_SET_SIZE_BLOCKS:
1653: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1654: return -EINVAL;
1655: return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1656: case NBD_SET_TIMEOUT:
1657: nbd_set_cmd_timeout(nbd, arg);
1658: return 0;
1659:
1660: case NBD_SET_FLAGS:
1661: config->flags = arg;
1662: return 0;
1663: case NBD_DO_IT:
1664: return nbd_start_device_ioctl(nbd);
1665: case NBD_CLEAR_QUE:
1666: /*
1667: * This is for compatibility only. The queue is always cleared
1668: * by NBD_DO_IT or NBD_CLEAR_SOCK.
1669: */
1670: return 0;
1671: case NBD_PRINT_DEBUG:
1672: /*
1673: * For compatibility only, we no longer keep a list of
1674: * outstanding requests.
1675: */
1676: return 0;
1677: }
1678: return -ENOTTY;
1679: }
SourceFile:drivers/block/nbd.c]
|
| 29/2 |
2026/11/22 08:13 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 23566
output: 89
thoughts: 1000
Thoughts: **My Journey Through the NBD Socket Reclassification Bug**
I've been deeply scrutinizing the `nbd_reclassify_socket()` function and its historical context to understand the root cause of a bug. My investigation started with commit `d532cddb6c60`, which introduced `nbd_reclassify_socket()` and its invocation within `nbd_add_socket()`.
My initial thought was to understand what exactly `d532cddb6c60` did. I found that it added the `nbd_reclassify_socket()` function itself, which included a call to `sock_allow_reclassification(sk)` followed by `sock_lock_init_class_and_name(sk, ...)`. This function was then called in `nbd_add_socket()` immediately after `nbd_get_socket()`.
This led me to ponder: how could `d532cddb6c60` have introduced this bug? Digging deeper, I realized that *before* this commit, NBD was not calling `sock_lock_init_class_and_name()` on the user-supplied socket at all. The problematic change in `d532cddb6c60` was that it introduced `sock_lock_init_class_and_name()` on a live, user-owned socket. Crucially, `sock_allow_reclassification(sk)` was called *without* holding any locks on the socket. Following this, `sock_lock_init_class_and_name()` was called, which performs `spin_lock_init(&sk->sk_lock.slock)`. This operation reinitializes the spinlock and resets its state, on a socket that could be concurrently accessed and locked by other threads. This could happen through various operations like `shutdown()`, `send()`, `recv()`, softirq handlers calling `bh_lock_sock()`, or even another NBD device attempting to use the same socket.
Even the `WARN_ON_ONCE(!sock_allow_reclassification(sk))` that was present in `d532cddb6c60` was insufficient. If `sock_allow_reclassification(sk)` happened to return `true` (meaning the socket wasn't locked *at that precise moment*), the warning would be suppressed, and `nbd_reclassify_socket()` would proceed. However, there was still a window of opportunity for a concurrent thread to acquire the `sk->sk_lock.slock` between the check and the `spin_lock_init()` call. When `spin_lock_init()` then executed, it would wipe the lock state while it was actually held by another thread, inevitably leading to a `BUG: spinlock already unlocked` when that other thread eventually attempted to unlock it.
Subsequently, commit `9280e6edf656` further modified the situation by removing the `WARN_ON_ONCE`. It changed the condition from `if (WARN_ON_ONCE(!sock_allow_reclassification(sk)))` to `if (!sock_allow_reclassification(sk))`. The rationale for this change, as I understand it, was that syzbot was encountering the `WARN_ON_ONCE` when the lock was *already* held during the `sock_allow_reclassification(sk)` check. However, this commit did *not* resolve the underlying Time-Of-Check-To-Time-Of-Use (TOCTOU) race condition or the fundamental issue of calling `sock_lock_init_class_and_name()` on a live socket without proper synchronization. The race condition and the unsafe initialization were already present in `d532cddb6c60` with the exact same mechanism.
To ensure I haven't missed anything, I'm also going to review the commit history for `drivers/block/nbd.c` and `include/net/sock.h`, and specifically examine `git-log` for `inet_shutdown` in `net/ipv4/af_inet.c` and `nbd_add_socket` in `drivers/block/nbd.c` to confirm there aren't any other relevant changes or complexities I've overlooked.
|
| 30/2 |
2026/11/22 08:13 |
tool |
git-log |
0m
Args: map[Count:10 SourcePath:drivers/block/nbd.c SymbolName:nbd_add_socket]
Results: map[Output:285908f554fe nbd: remove queue freeze in nbd_add_socket
04d8fb23e520 nbd: disallow NBD_SET_SOCK on an active device
d532cddb6c60 nbd: Reclassify sockets to avoid lockdep circular dependency
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
1e1a9cecfab3 block: force noio scope in blk_mq_freeze_queue
8337b029f788 nbd: fix partial sending
55793ea54d77 nbd: fix incomplete validation of ioctl arg
b98e762e3d71 nbd: freeze the queue while we're adding connections
579dd91ab3a5 nbd: Fix memory leak in nbd_add_socket
]
|
| 31/2 |
2026/11/22 08:13 |
tool |
git-log |
0m
Args: map[Count:10 SourcePath:net/ipv4/af_inet.c SymbolName:inet_shutdown]
Results: map[Output:e14cadfd80d7 tcp: add annotations around sk->sk_shutdown accesses
a8eceea84a3a inet: Use fallthrough;
a9a08845e9ac vfs: do bulk POLL* -> EPOLL* replacement
fcfd6dfab970 ipv4: mark expected switch fall-throughs
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 32/2 |
2026/11/22 08:13 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 25035
output: 87
thoughts: 64
Thoughts: **Examining the Commit History and Socket Reclassification**
My immediate thought is to meticulously verify that the commits identified by `04d8fb23e520` and `285908f554fe` have no bearing whatsoever on the race condition I'm investigating. I need to ensure these particular changes are truly orthogonal and don't inadvertently introduce or mask the problem. To achieve this, I'll be using `git show` on each of these hashes to get a detailed look at their diffs and commit messages. My goal is to confirm, with absolute certainty, that their scope is entirely separate from the area where the race is manifesting.
Concurrently, I want to explore the call sites of `nbd_reclassify_socket`. Understanding where and how this function is invoked will provide crucial context for its role in the system's operation, especially in relation to network device interactions. By examining its callers, I hope to identify any potential sequences of events or specific scenarios that might lead to the race condition. This dual approach – confirming the irrelevance of specific commits while deeply understanding the usage of a key function – feels like the most efficient way to narrow down the root cause of this race.
|
| 33/2 |
2026/11/22 08:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 04d8fb23e520419a283dd53c1d9cdfb7c5b1705e
Author: Yang Erkun <yangerkun@huawei.com>
Date: Wed Aug 5 20:29:24 2026 +0800
nbd: disallow NBD_SET_SOCK on an active device
We cannot add a socket to an already running nbd device, the reconfigure
for netlink can only active an inactive socket. But for ioctl path, we can
call NBD_SET_SOCK after NBD_DO_IT, reject this using nbd->pid which has
been setted when NBD_DO_IT. Besides, it is the root cause for commit
b98e762e3d71 ("nbd: freeze the queue while we're adding connections").
Reviewed-by: Yu Kuai <yukuai@fygo.io>
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Link: https://patch.msgid.link/20260805122930.57647-3-yangerkun@huawei.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index b1a5acd57426..7ec85f94f742 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -1278,6 +1278,13 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
/* Arg will be cast to int, check it to avoid overflow */
if (arg > INT_MAX)
return -EINVAL;
+
+ if (nbd->pid) {
+ dev_err(disk_to_dev(nbd->disk),
+ "Cannot add socket to a running device\n");
+ return -EBUSY;
+ }
+
sock = nbd_get_socket(nbd, arg, &err);
if (!sock)
return err;
]
|
| 34/2 |
2026/11/22 08:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 285908f554fe32d9ca7cb7c3a03a05144faeb461
Author: Yang Erkun <yangerkun@huawei.com>
Date: Wed Aug 5 20:29:26 2026 +0800
nbd: remove queue freeze in nbd_add_socket
nbd_add_socket() kreallocs config->socks, which a concurrent reader in
nbd_handle_cmd() could UAF; commit b98e762e3d71 ("nbd: freeze the queue
while we're adding connections")froze the queue to block that. But the
freeze costs an RCU grace period on every socket added, and setup adds
them one by one.
After the previous patch, nbd_add_socket() is rejected once nbd->pid is
set, so it only runs during setup. There the capacity is 0 and the
write cache is off (cleared on disconnect by the preceding patch, and
re-enabled only later in nbd_set_size), so submit_bio_noacct() rejects
every bio before it reaches the driver -- non-zero-sector ones via
bio_check_eod(), and flush-only ones via the !bdev_write_cache() branch.
No I/O is in flight, so the freeze is unnecessary.
Reviewed-by: Yu Kuai <yukuai@fygo.io>
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Link: https://patch.msgid.link/20260805122930.57647-5-yangerkun@huawei.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index 78df6f459da6..cb7c1f8502f4 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -1276,7 +1276,6 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
struct socket *sock;
struct nbd_sock **socks;
struct nbd_sock *nsock;
- unsigned int memflags;
int err;
/* Arg will be cast to int, check it to avoid overflow */
@@ -1294,12 +1293,6 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
return err;
nbd_reclassify_socket(sock);
- /*
- * We need to make sure we don't get any errant requests while we're
- * reallocating the ->socks array.
- */
- memflags = blk_mq_freeze_queue(nbd->disk->queue);
-
if (!netlink && !nbd->task_setup &&
!test_bit(NBD_RT_BOUND, &config->runtime_flags))
nbd->task_setup = current;
@@ -1339,12 +1332,10 @@ static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
INIT_WORK(&nsock->work, nbd_pending_cmd_work);
socks[config->num_connections++] = nsock;
atomic_inc(&config->live_connections);
- blk_mq_unfreeze_queue(nbd->disk->queue, memflags);
return 0;
put_socket:
- blk_mq_unfreeze_queue(nbd->disk->queue, memflags);
sockfd_put(sock);
return err;
}
]
|
| 35/2 |
2026/11/22 08:13 |
tool |
codesearch-find-references |
0m
Args: map[Name:nbd_reclassify_socket]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_add_socket SourceFile:drivers/block/nbd.c SourceLine:1299]] TruncatedOutput:false]
|
| 36/2 |
2026/11/22 08:13 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 26823
output: 57
thoughts: 618
Thoughts: **My In-Depth Analysis of the NBD Socket Reclassification Issue**
Having delved deeply into the source code and git history, I've arrived at a crystal-clear understanding of this NBD socket reclassification problem. My thought process has been guided by a direct, line-by-line verification of the commits and their implications.
First, my attention was drawn to commit `d532cddb6c6049ced414d64d83c6ce7149a6421a`, aptly titled "nbd: Reclassify sockets to avoid lockdep circular dependency." This commit is where the crux of the issue begins. It introduced a new function, `nbd_reclassify_socket()`, within `drivers/block/nbd.c`, and crucially, it's called from within `nbd_add_socket()`.
My next step was to dissect `nbd_reclassify_socket()` itself. I observed that its primary check is `!sock_allow_reclassification(sk)`. This check, critically, occurs *without* holding the `sk->sk_lock.slock`. It's an unlocked examination of `sk->sk_lock.owned` and a check via `spin_is_locked(&sk->sk_lock.slock)`. If this condition evaluates to true, meaning reclassification is deemed permissible, the function proceeds to call `sock_lock_init_class_and_name(sk, ...)`.
Tracing further, I examined `sock_lock_init_class_and_name()`, found in `include/net/sock.h`. This function is responsible for reinitializing several key components of the socket's lock structure: it sets `sk->sk_lock.owned = 0`, initializes the wait queue head with `init_waitqueue_head(&sk->sk_lock.wq)`, and, most importantly, reinitializes the spinlock itself using `spin_lock_init(&(sk)->sk_lock.slock)`. Alongside these modifications, it also updates the lockdep classes.
The problem, as I see it, stems from the distinct way NBD handles sockets compared to internal kernel sockets. Unlike sockets created via `sock_create_kern()`, NBD obtains a user-owned socket file descriptor through a sequence of calls: `nbd_get_socket()` followed by `sockfd_lookup()`. This user-owned nature means that other NBD devices, or even userspace itself, can concurrently interact with the same socket. For instance, operations like `inet_shutdown()` can invoke `lock_sock()` and `release_sock()`, which, in turn, acquire `spin_lock_bh(&sk->sk_lock.slock)`.
This concurrent access is where the race condition, or Time-of-Check to Time-of-Use (TOCTOU) vulnerability, becomes apparent. Because `sock_allow_reclassification(sk)` does *not* hold `sk->sk_lock.slock`, there's a window of opportunity. A concurrent thread could acquire `sk->sk_lock.slock` *after* the `sock_allow_reclassification(sk)` check has passed but *before* the `spin_lock_init(&sk->sk_lock.slock)` call within `sock_lock_init_class_and_name()` executes. This scenario leads to a corrupted spinlock state. The held spinlock is effectively reinitialized while another thread believes it owns it. Consequently, when `inet_shutdown()` or `release_sock()` attempts to unlock this spinlock, it triggers a `BUG: spinlock already unlocked` within `debug_spin_unlock()`.
Finally, I reviewed the follow-up commit, `9280e6edf65662b6aafc8b704ad065b54c08b519`, titled "nbd: don't warn when reclassifying a busy socket lock." My analysis shows that this commit merely removed a `WARN_ON_ONCE()` directive that was placed around the `!sock_allow_reclassification(sk)` check. It did not address the underlying TOCTOU race or the destructive nature of calling `spin_lock_init()` on an actively used socket. Therefore, this subsequent commit did not resolve the fundamental issue.
Given this comprehensive understanding, I am confident that the root cause of the problem lies within commit `d532cddb6c6049ced414d64d83c6ce7149a6421a`.
|
| 37/2 |
2026/11/22 08:13 |
tool |
set-results |
0m
Args: map[CandidateCommits:[d532cddb6c6049ced414d64d83c6ce7149a6421a]]
Results: map[CandidateCommits:[d532cddb6c6049ced414d64d83c6ce7149a6421a]]
|
| 38/2 |
2026/11/22 08:13 |
llm |
cause-finder |
0m
Model:
Tokens:
input: 27551
output: 1151
thoughts: 26
Thoughts: **Drafting the Final Summary: Consolidating Our Findings**
My immediate thought is to craft a final output that is not only clear and concise but also rigorously supported by the evidence from our bisection log. This means I need to meticulously review all the data points we've gathered, ensuring each conclusion drawn is directly and demonstrably linked to specific observations. The goal is to present a narrative that is both easy to follow and intellectually sound, leaving no room for ambiguity or doubt for an expert audience. I'm considering the most effective way to structure this summary, perhaps by outlining the initial hypothesis, detailing the iterative testing process, and then clearly articulating the findings that led us to our final resolution. The evidence is paramount; I want this summary to be a testament to the thoroughness of our work, showcasing how each step logically built upon the last to arrive at our conclusions.
|
| 39/1 |
2026/11/22 08:14 |
action |
format-bisect |
0m
Results: map[Commits:[map[AuthorEmail:edumazet@google.com AuthorName:Eric Dumazet Date:2026-06-13T04:26:19Z Hash:d532cddb6c6049ced414d64d83c6ce7149a6421a Recipients:[map[Email:axboe@kernel.dk Name: To:true] map[Email:edumazet@google.com Name: To:true]] Title:nbd: Reclassify sockets to avoid lockdep circular dependency]] IsRelease:false]
|