| 0/0 |
2026/05/10 02:30 |
flow |
patching |
1h37m
Error:
|
| 1/1 |
2026/05/10 02:30 |
action |
base-commit-picker |
0m
Results: map[KernelBranch:master KernelCommit:7fd2df204f342fc17d1a0bfcd474b24232fb0f32 KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git]
|
| 2/1 |
2026/05/10 02:30 |
action |
syz-repro-to-c-repro |
0m
Results: map[SimplifiedCRepro:// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1, (uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
unsigned long nb = a1;
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(nb % 10);
nb /= 10;
}
return open(buf, a2 & ~O_CREAT, 0);
}
}
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffffffff000ul, /*len=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000ul, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200001000000ul, /*len=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// openat$dir arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2e 2f 66 69 6c 65 31 00} (length 0x8)
// }
// flags: open_flags = 0x40042 (4 bytes)
// mode: open_mode = 0x0 (2 bytes)
// ]
// returns fd_dir
memcpy((void*)0x200000001a00, "./file1\000", 8);
syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000001a00ul, /*flags=O_NOATIME|O_CREAT|O_RDWR*/0x40042, /*mode=*/0);
// syz_open_dev$ndb arguments: [
// dev: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6e 62 64 23 00} (length 0xa)
// }
// id: proc = 0x0 (8 bytes)
// flags: open_flags = 0x80000 (8 bytes)
// ]
// returns fd_nbd
memcpy((void*)0x2000000000c0, "/dev/nbd#\000", 10);
res = -1;
res = syz_open_dev(/*dev=*/0x2000000000c0, /*id=*/0, /*flags=O_CLOEXEC*/0x80000);
if (res != -1)
r[0] = res;
// socket arguments: [
// domain: socket_domain = 0x2 (8 bytes)
// type: socket_type = 0x1 (8 bytes)
// proto: int32 = 0x0 (4 bytes)
// ]
// returns sock
res = syscall(__NR_socket, /*domain=AF_INET*/2ul, /*type=SOCK_STREAM*/1ul, /*proto=*/0);
if (res != -1)
r[1] = res;
// syz_open_dev$ndb arguments: [
// dev: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6e 62 64 23 00} (length 0xa)
// }
// id: proc = 0x0 (8 bytes)
// flags: open_flags = 0x0 (8 bytes)
// ]
// returns fd_nbd
memcpy((void*)0x200000000000, "/dev/nbd#\000", 10);
res = -1;
res = syz_open_dev(/*dev=*/0x200000000000, /*id=*/0, /*flags=*/0);
if (res != -1)
r[2] = res;
// ioctl$NBD_SET_SOCK arguments: [
// fd: fd_nbd (resource)
// cmd: const = 0xab00 (4 bytes)
// arg: sock_nbd_client (resource)
// ]
syscall(__NR_ioctl, /*fd=*/r[0], /*cmd=*/0xab00, /*arg=*/r[1]);
// ioctl$NBD_DO_IT arguments: [
// fd: fd_nbd (resource)
// cmd: const = 0xab03 (4 bytes)
// ]
syscall(__NR_ioctl, /*fd=*/r[2], /*cmd=*/0xab03, 0);
// mount arguments: [
// src: ptr[in, blockdev_filename] {
// union blockdev_filename {
// nbd: nbd_filename {
// prefix: buffer: {2f 64 65 76 2f 6e 62 64} (length 0x8)
// id: proc = 0x0 (1 bytes)
// z: const = 0x0 (1 bytes)
// }
// }
// }
// dst: ptr[in, buffer] {
// buffer: {2e 2f 66 69 6c 65 31 00} (length 0x8)
// }
// type: ptr[in, buffer] {
// buffer: {75 64 66 00} (length 0x4)
// }
// flags: mount_flags = 0x2008087 (8 bytes)
// data: nil
// ]
memcpy((void*)0x200000000000, "/dev/nbd", 8);
*(uint8_t*)0x200000000008 = 0x30;
*(uint8_t*)0x200000000009 = 0;
memcpy((void*)0x200000004a00, "./file1\000", 8);
memcpy((void*)0x200000000080, "udf\000", 4);
syscall(__NR_mount, /*src=*/0x200000000000ul, /*dst=*/0x200000004a00ul, /*type=*/0x200000000080ul, /*flags=MS_LAZYTIME|MS_SILENT|MS_RDONLY|MS_NOSUID|MS_NODEV|0x80*/0x2008087ul, /*data=*/0ul);
return 0;
}
]
|
| 3/1 |
2026/05/10 02:30 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/cbad7996b082969065ced471e435d1359c15f2ef]
|
| 4/1 |
2026/05/10 02:30 |
action |
kernel-builder |
13m
Results: map[KernelObj:/app/workdir/cache/build/d6ede34804fa567b30d5a1b11baf424ea4409960]
|
| 5/1 |
2026/05/10 02:44 |
action |
crash-reproducer |
1m
Results: map[ReproducedBugTitle:WARNING in bdev_getblk ReproducedCrashReport:------------[ cut here ]------------
WARNING: fs/buffer.c:1029 at __getblk_slow fs/buffer.c:1029 [inline], CPU#1: syz.5.22/6454
WARNING: fs/buffer.c:1029 at bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358, CPU#1: syz.5.22/6454
Modules linked in:
CPU: 1 UID: 0 PID: 6454 Comm: syz.5.22 Not tainted syzkaller #1 PREEMPT(full)
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
RIP: 0010:__getblk_slow fs/buffer.c:1029 [inline]
RIP: 0010:bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358
Code: eb cf e8 68 fa 6e ff 48 c7 c7 80 d4 9c 8b 48 c7 c6 f6 e3 c2 8d 4c 89 e2 48 8b 4c 24 10 e8 cd e9 d2 fe eb be e8 46 fa 6e ff 90 <0f> 0b 90 48 b8 00 00 00 00 00 fc ff df 41 80 3c 07 00 74 08 48 89
RSP: 0018:ffffc9000575f668 EFLAGS: 00010293
RAX: ffffffff8254b52a RBX: ffff8880424af318 RCX: ffff888023179d80
RDX: 0000000000000000 RSI: 0000000000000200 RDI: 0000000000000000
RBP: 0000000000000200 R08: ffffffff82217e1c R09: ffffffff8e67f1a0
R10: 0000000000000406 R11: 0000000000000000 R12: 0000000000000200
R13: 0000000000000400 R14: 0000000000000200 R15: 1ffff11008495e63
FS: 00007f7ef90ec6c0(0000) GS:ffff8880ebf32000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007fb010d456b8 CR3: 000000001feba000 CR4: 00000000000006f0
Call Trace:
<TASK>
__bread_gfp+0x89/0x3b0 fs/buffer.c:1412
sb_bread include/linux/buffer_head.h:346 [inline]
udf_read_tagged+0xab/0xe60 fs/udf/misc.c:199
udf_check_anchor_block+0x9f/0x560 fs/udf/super.c:1913
udf_scan_anchors fs/udf/super.c:1991 [inline]
udf_load_vrs+0xa91/0xfe0 fs/udf/super.c:2034
udf_fill_super+0x58b/0x1870 fs/udf/super.c:2202
get_tree_bdev_flags+0x431/0x4f0 fs/super.c:1694
vfs_get_tree+0x92/0x2a0 fs/super.c:1754
fc_mount fs/namespace.c:1193 [inline]
do_new_mount_fc fs/namespace.c:3758 [inline]
do_new_mount+0x341/0xd30 fs/namespace.c:3834
do_mount fs/namespace.c:4167 [inline]
__do_sys_mount fs/namespace.c:4383 [inline]
__se_sys_mount+0x31d/0x420 fs/namespace.c:4360
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f7ef819cdd9
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f7ef90ec028 EFLAGS: 00000246 ORIG_RAX: 00000000000000a5
RAX: ffffffffffffffda RBX: 00007f7ef8416090 RCX: 00007f7ef819cdd9
RDX: 0000200000000080 RSI: 0000200000004a00 RDI: 0000200000000000
RBP: 00007f7ef8232d69 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000002008087 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f7ef8416128 R14: 00007f7ef8416090 R15: 00007ffd283d4848
</TASK>
ReproducedFaultInjection:]
|
| 6/1 |
2026/05/10 02:46 |
action |
codesearch-prepare |
10m
Results: map[Index:codesearch-index]
|
| 7/1 |
2026/05/10 02:56 |
agent |
debugger |
13m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with debugging a kernel crash root cause.
You need to provide a detailed explanation of the root cause for another developer to be
able to write a fix for the bug based on your explanation. Include all relevant details
into the response: function/struct/field/etc names, code snippets, line numbers,
macro/enum values, etc.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
------------[ cut here ]------------
WARNING: fs/buffer.c:1029 at __getblk_slow fs/buffer.c:1029 [inline], CPU#1: syz.5.22/6454
WARNING: fs/buffer.c:1029 at bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358, CPU#1: syz.5.22/6454
Modules linked in:
CPU: 1 UID: 0 PID: 6454 Comm: syz.5.22 Not tainted syzkaller #1 PREEMPT(full)
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
RIP: 0010:__getblk_slow fs/buffer.c:1029 [inline]
RIP: 0010:bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358
Code: eb cf e8 68 fa 6e ff 48 c7 c7 80 d4 9c 8b 48 c7 c6 f6 e3 c2 8d 4c 89 e2 48 8b 4c 24 10 e8 cd e9 d2 fe eb be e8 46 fa 6e ff 90 <0f> 0b 90 48 b8 00 00 00 00 00 fc ff df 41 80 3c 07 00 74 08 48 89
RSP: 0018:ffffc9000575f668 EFLAGS: 00010293
RAX: ffffffff8254b52a RBX: ffff8880424af318 RCX: ffff888023179d80
RDX: 0000000000000000 RSI: 0000000000000200 RDI: 0000000000000000
RBP: 0000000000000200 R08: ffffffff82217e1c R09: ffffffff8e67f1a0
R10: 0000000000000406 R11: 0000000000000000 R12: 0000000000000200
R13: 0000000000000400 R14: 0000000000000200 R15: 1ffff11008495e63
FS: 00007f7ef90ec6c0(0000) GS:ffff8880ebf32000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007fb010d456b8 CR3: 000000001feba000 CR4: 00000000000006f0
Call Trace:
<TASK>
__bread_gfp+0x89/0x3b0 fs/buffer.c:1412
sb_bread include/linux/buffer_head.h:346 [inline]
udf_read_tagged+0xab/0xe60 fs/udf/misc.c:199
udf_check_anchor_block+0x9f/0x560 fs/udf/super.c:1913
udf_scan_anchors fs/udf/super.c:1991 [inline]
udf_load_vrs+0xa91/0xfe0 fs/udf/super.c:2034
udf_fill_super+0x58b/0x1870 fs/udf/super.c:2202
get_tree_bdev_flags+0x431/0x4f0 fs/super.c:1694
vfs_get_tree+0x92/0x2a0 fs/super.c:1754
fc_mount fs/namespace.c:1193 [inline]
do_new_mount_fc fs/namespace.c:3758 [inline]
do_new_mount+0x341/0xd30 fs/namespace.c:3834
do_mount fs/namespace.c:4167 [inline]
__do_sys_mount fs/namespace.c:4383 [inline]
__se_sys_mount+0x31d/0x420 fs/namespace.c:4360
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f7ef819cdd9
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f7ef90ec028 EFLAGS: 00000246 ORIG_RAX: 00000000000000a5
RAX: ffffffffffffffda RBX: 00007f7ef8416090 RCX: 00007f7ef819cdd9
RDX: 0000200000000080 RSI: 0000200000004a00 RDI: 0000200000000000
RBP: 00007f7ef8232d69 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000002008087 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f7ef8416128 R14: 00007f7ef8416090 R15: 00007ffd283d4848
</TASK>
The following C code is a draft of the vulnerable syscall sequence. Keep in mind that
it may lack the precise threading, sandboxing, and some arguments of a working reproducer:
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1, (uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
unsigned long nb = a1;
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(nb % 10);
nb /= 10;
}
return open(buf, a2 & ~O_CREAT, 0);
}
}
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffffffff000ul, /*len=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000ul, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200001000000ul, /*len=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// openat$dir arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2e 2f 66 69 6c 65 31 00} (length 0x8)
// }
// flags: open_flags = 0x40042 (4 bytes)
// mode: open_mode = 0x0 (2 bytes)
// ]
// returns fd_dir
memcpy((void*)0x200000001a00, "./file1\000", 8);
syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000001a00ul, /*flags=O_NOATIME|O_CREAT|O_RDWR*/0x40042, /*mode=*/0);
// syz_open_dev$ndb arguments: [
// dev: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6e 62 64 23 00} (length 0xa)
// }
// id: proc = 0x0 (8 bytes)
// flags: open_flags = 0x80000 (8 bytes)
// ]
// returns fd_nbd
memcpy((void*)0x2000000000c0, "/dev/nbd#\000", 10);
res = -1;
res = syz_open_dev(/*dev=*/0x2000000000c0, /*id=*/0, /*flags=O_CLOEXEC*/0x80000);
if (res != -1)
r[0] = res;
// socket arguments: [
// domain: socket_domain = 0x2 (8 bytes)
// type: socket_type = 0x1 (8 bytes)
// proto: int32 = 0x0 (4 bytes)
// ]
// returns sock
res = syscall(__NR_socket, /*domain=AF_INET*/2ul, /*type=SOCK_STREAM*/1ul, /*proto=*/0);
if (res != -1)
r[1] = res;
// syz_open_dev$ndb arguments: [
// dev: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 6e 62 64 23 00} (length 0xa)
// }
// id: proc = 0x0 (8 bytes)
// flags: open_flags = 0x0 (8 bytes)
// ]
// returns fd_nbd
memcpy((void*)0x200000000000, "/dev/nbd#\000", 10);
res = -1;
res = syz_open_dev(/*dev=*/0x200000000000, /*id=*/0, /*flags=*/0);
if (res != -1)
r[2] = res;
// ioctl$NBD_SET_SOCK arguments: [
// fd: fd_nbd (resource)
// cmd: const = 0xab00 (4 bytes)
// arg: sock_nbd_client (resource)
// ]
syscall(__NR_ioctl, /*fd=*/r[0], /*cmd=*/0xab00, /*arg=*/r[1]);
// ioctl$NBD_DO_IT arguments: [
// fd: fd_nbd (resource)
// cmd: const = 0xab03 (4 bytes)
// ]
syscall(__NR_ioctl, /*fd=*/r[2], /*cmd=*/0xab03, 0);
// mount arguments: [
// src: ptr[in, blockdev_filename] {
// union blockdev_filename {
// nbd: nbd_filename {
// prefix: buffer: {2f 64 65 76 2f 6e 62 64} (length 0x8)
// id: proc = 0x0 (1 bytes)
// z: const = 0x0 (1 bytes)
// }
// }
// }
// dst: ptr[in, buffer] {
// buffer: {2e 2f 66 69 6c 65 31 00} (length 0x8)
// }
// type: ptr[in, buffer] {
// buffer: {75 64 66 00} (length 0x4)
// }
// flags: mount_flags = 0x2008087 (8 bytes)
// data: nil
// ]
memcpy((void*)0x200000000000, "/dev/nbd", 8);
*(uint8_t*)0x200000000008 = 0x30;
*(uint8_t*)0x200000000009 = 0;
memcpy((void*)0x200000004a00, "./file1\000", 8);
memcpy((void*)0x200000000080, "udf\000", 4);
syscall(__NR_mount, /*src=*/0x200000000000ul, /*dst=*/0x200000004a00ul, /*type=*/0x200000000080ul, /*flags=MS_LAZYTIME|MS_SILENT|MS_RDONLY|MS_NOSUID|MS_NODEV|0x80*/0x2008087ul, /*data=*/0ul);
return 0;
}
Reply: The root cause of this crash is a Time-Of-Check to Time-Of-Use (TOCTOU) race condition between the VFS/filesystem mount process and the NBD (Network Block Device) driver.
The NBD driver allows changing the block device's `logical_block_size` concurrently while the device is being mounted or is already in use. This violates the VFS assumption that a block device's logical block size remains constant while it is exclusively claimed (e.g., by a filesystem).
### Detailed Sequence of Events
Although the provided C reproducer executes the syscalls sequentially, syzkaller often executes them in parallel threads to trigger race conditions. The crash happens when `mount` and `ioctl(NBD_DO_IT)` are executed concurrently:
1. **[Thread A - `mount`]**: The `mount` syscall enters the UDF filesystem's `udf_fill_super()`. Since no block size was explicitly provided in the mount options, UDF reads the block device's current logical block size to use as a starting point:
```c
// fs/udf/super.c : udf_fill_super()
uopt->blocksize = bdev_logical_block_size(sb->s_bdev);
```
At this point, the NBD device has not been started, so its `logical_block_size` is the default `512`. Thus, `uopt->blocksize` is set to `512`.
2. **[Thread A - `mount`]**: UDF calls `udf_load_vrs()`, which successfully sets the superblock's block size to `512` because it matches the block device's current logical block size:
```c
// fs/udf/super.c : udf_load_vrs()
if (!sb_set_blocksize(sb, uopt->blocksize)) { ... }
```
Now, `sb->s_blocksize` is `512`.
3. **[Thread B - `ioctl`]**: Concurrently, another thread executes the `NBD_DO_IT` ioctl (or `NBD_SET_BLKSIZE`) on the same NBD device. This calls `nbd_start_device()`, which configures the device and updates its queue limits via `nbd_set_size()`:
```c
// drivers/block/nbd.c : nbd_set_size()
lim.logical_block_size = blksize; // blksize is 1024 (1u << NBD_DEF_BLKSIZE_BITS)
lim.physical_block_size = blksize;
error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
```
The block device's `logical_block_size` is now changed to `1024` under the hood.
4. **[Thread A - `mount`]**: UDF continues the mounting process and attempts to read the Volume Recognition Sequence (VRS) from the disk using `sb_bread()`:
```c
// fs/udf/misc.c : udf_read_tagged()
bh = sb_bread(sb, block);
```
`sb_bread()` requests a buffer of size `sb->s_blocksize` (which is still `512`).
5. **[Thread A - `mount`]**: The read request reaches `__getblk_slow()`, which validates the requested size against the block device's *current* logical block size:
```c
// fs/buffer.c : __getblk_slow()
if (WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))) {
printk(KERN_ERR "getblk(): block size %d not aligned to logical block size %d\n",
size, bdev_logical_block_size(bdev));
return NULL;
}
```
Since the requested size is `512` but the block device's `logical_block_size` was concurrently changed to `1024` by Thread B, `IS_ALIGNED(512, 1024)` evaluates to false, triggering the `WARN_ON_ONCE`.
### Suggested Fix
The NBD driver should not be allowed to change the `logical_block_size` of the block device if it is already exclusively claimed (e.g., actively mounted by a filesystem).
A similar issue was previously fixed in the loop device driver (`drivers/block/loop.c : loop_set_block_size()`), which uses `bd_prepare_to_claim()` to ensure it has exclusive access before modifying the block size:
```c
/*
* If we don't hold exclusive handle for the device, upgrade to it
* here to avoid changing device under exclusive owner.
*/
if (!(mode & BLK_OPEN_EXCL)) {
err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
if (err)
return err;
}
```
Applying a similar exclusive claim check in `nbd_set_size()` (or preventing geometry changes when `disk_openers(nbd->disk) > 1`) would prevent this race condition and safely reject concurrent modifications while the device is mounted.
|
| 8/2 |
2026/05/10 02:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 7646
output: 20
thoughts: 161
Thoughts: **Analyzing a Block Device Crash**
Okay, so I've got a crash, and the kernel's flagged it as a WARNING. The report points directly to `fs/buffer.c:1029`, within the `__getblk_slow` function, specifically on CPU #1, process syz.5.22/6454. That's a pretty clear pointer to start with. The call stack indicates this function is being called from `bdev_getblk`.
My initial thought is to zoom in on `fs/buffer.c` around line 1029. Let's see what's happening in `__getblk_slow`. It's likely related to block allocation or retrieval, given the function name and the context of buffer management. The stack trace strongly hints that this is happening within the block device subsystem, which is not surprising. I'll need to understand the surrounding code, the data structures involved, and the conditions that might trigger this "slow" path to be hit. This could be anything from a race condition to a data corruption issue. Time to dig in and see what the code is telling me.
|
| 9/2 |
2026/05/10 02:56 |
tool |
read-file |
0m
Args:
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0-only
/*
* linux/fs/buffer.c
*
* Copyright (C) 1991, 1992, 2002 Linus Torvalds
*/
/*
* Start bdflush() with kernel_thread not syscall - Paul Gortmaker, 12/95
*
* Removed a lot of unnecessary code and simplified things now that
* the buffer cache isn't our primary cache - Andrew Tridgell 12/96
*
* Speed up hash, lru, and free list operations. Use gfp() for allocating
* hash table, use SLAB cache for buffer heads. SMP threading. -DaveM
*
* Added 32k buffer block sizes - these are required older ARM systems. - RMK
*
* async buffer flushing, 1999 Andrea Arcangeli <andrea@suse.de>
*/
#include <linux/kernel.h>
#include <linux/sched/signal.h>
#include <linux/syscalls.h>
#include <linux/fs.h>
#include <linux/iomap.h>
#include <linux/mm.h>
#include <linux/percpu.h>
#include <linux/slab.h>
#include <linux/capability.h>
#include <linux/blkdev.h>
#include <linux/blk-crypto.h>
#include <linux/file.h>
#include <linux/quotaops.h>
#include <linux/highmem.h>
#include <linux/export.h>
#include <linux/backing-dev.h>
#include <linux/writeback.h>
#include <linux/hash.h>
#include <linux/suspend.h>
#include <linux/buffer_head.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/bio.h>
#include <linux/cpu.h>
#include <linux/bitops.h>
#include <linux/mpage.h>
#include <linux/bit_spinlock.h>
#include <linux/folio_batch.h>
#include <linux/sched/mm.h>
#include <trace/events/block.h>
#include <linux/fscrypt.h>
#include <linux/fsverity.h>
#include <linux/sched/isolation.h>
#include "internal.h"
static void submit_bh_wbc(blk_opf_t opf, struct buffer_head *bh,
enum rw_hint hint, struct writeback_control *wbc);
#define BH_ENTRY(list) list_entry((list), struct buffer_head, b_assoc_buffers)
inline void touch_buffer(struct buffer_head *bh)
{
trace_block_touch_buffer(bh);
folio_mark_accessed(bh->b_folio);
}
EXPORT_SYMBOL(touch_buffer);
void __lock_buffer(struct buffer_head *bh)
{
wait_on_bit_lock_io(&bh->b_state, BH_Lock, TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(__lock_buffer);
void unlock_buffer(struct buffer_head *bh)
{
clear_bit_unlock(BH_Lock, &bh->b_state);
smp_mb__after_atomic();
wake_up_bit(&bh->b_state, BH_Lock);
}
EXPORT_SYMBOL(unlock_buffer);
/*
* Returns if the folio has dirty or writeback buffers. If all the buffers
* are unlocked and clean then the folio_test_dirty information is stale. If
* any of the buffers are locked, it is assumed they are locked for IO.
*/
void buffer_check_dirty_writeback(struct folio *folio,
bool *dirty, bool *writeback)
{
struct buffer_head *head, *bh;
*dirty = false;
*writeback = false;
BUG_ON(!folio_test_locked(folio));
head = folio_buffers(folio);
if (!head)
return;
if (folio_test_writeback(folio))
*writeback = true;
bh = head;
do {
if (buffer_locked(bh))
*writeback = true;
if (buffer_dirty(bh))
*dirty = true;
bh = bh->b_this_page;
} while (bh != head);
}
/*
* Block until a buffer comes unlocked. This doesn't stop it
* from becoming locked again - you have to lock it yourself
* if you want to preserve its state.
*/
void __wait_on_buffer(struct buffer_head * bh)
{
wait_on_bit_io(&bh->b_state, BH_Lock, TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(__wait_on_buffer);
static void buffer_io_error(struct buffer_head *bh, char *msg)
{
if (!test_bit(BH_Quiet, &bh->b_state))
printk_ratelimited(KERN_ERR
"Buffer I/O error on dev %pg, logical block %llu%s\n",
bh->b_bdev, (unsigned long long)bh->b_blocknr, msg);
}
/*
* End-of-IO handler helper function which does not touch the bh after
* unlocking it.
* Note: unlock_buffer() sort-of does touch the bh after unlocking it, but
* a race there is benign: unlock_buffer() only use the bh's address for
* hashing after unlocking the buffer, so it doesn't actually touch the bh
* itself.
*/
static void __end_buffer_read_notouch(struct buffer_head *bh, int uptodate)
{
if (uptodate) {
set_buffer_uptodate(bh);
} else {
/* This happens, due to failed read-ahead attempts. */
clear_buffer_uptodate(bh);
}
unlock_buffer(bh);
}
/*
* Default synchronous end-of-IO handler.. Just mark it up-to-date and
* unlock the buffer.
*/
void end_buffer_read_sync(struct buffer_head *bh, int uptodate)
{
put_bh(bh);
__end_buffer_read_notouch(bh, uptodate);
}
EXPORT_SYMBOL(end_buffer_read_sync);
void end_buffer_write_sync(struct buffer_head *bh, int uptodate)
{
if (uptodate) {
set_buffer_uptodate(bh);
} else {
buffer_io_error(bh, ", lost sync page write");
mark_buffer_write_io_error(bh);
clear_buffer_uptodate(bh);
}
unlock_buffer(bh);
put_bh(bh);
}
EXPORT_SYMBOL(end_buffer_write_sync);
static struct buffer_head *
__find_get_block_slow(struct block_device *bdev, sector_t block, bool atomic)
{
struct address_space *bd_mapping = bdev->bd_mapping;
const int blkbits = bd_mapping->host->i_blkbits;
struct buffer_head *ret = NULL;
pgoff_t index;
struct buffer_head *bh;
struct buffer_head *head;
struct folio *folio;
int all_mapped = 1;
static DEFINE_RATELIMIT_STATE(last_warned, HZ, 1);
index = ((loff_t)block << blkbits) / PAGE_SIZE;
folio = __filemap_get_folio(bd_mapping, index, FGP_ACCESSED, 0);
if (IS_ERR(folio))
goto out;
/*
* Folio lock protects the buffers. Callers that cannot block
* will fallback to serializing vs try_to_free_buffers() via
* the i_private_lock.
*/
if (atomic)
spin_lock(&bd_mapping->i_private_lock);
else
folio_lock(folio);
head = folio_buffers(folio);
if (!head)
goto out_unlock;
/*
* Upon a noref migration, the folio lock serializes here;
* otherwise bail.
*/
if (test_bit_acquire(BH_Migrate, &head->b_state)) {
WARN_ON(!atomic);
goto out_unlock;
}
bh = head;
do {
if (!buffer_mapped(bh))
all_mapped = 0;
else if (bh->b_blocknr == block) {
ret = bh;
get_bh(bh);
goto out_unlock;
}
bh = bh->b_this_page;
} while (bh != head);
/* we might be here because some of the buffers on this page are
* not mapped. This is due to various races between
* file io on the block device and getblk. It gets dealt with
* elsewhere, don't buffer_error if we had some unmapped buffers
*/
ratelimit_set_flags(&last_warned, RATELIMIT_MSG_ON_RELEASE);
if (all_mapped && __ratelimit(&last_warned)) {
printk("__find_get_block_slow() failed. block=%llu, "
"b_blocknr=%llu, b_state=0x%08lx, b_size=%zu, "
"device %pg blocksize: %d\n",
(unsigned long long)block,
(unsigned long long)bh->b_blocknr,
bh->b_state, bh->b_size, bdev,
1 << blkbits);
}
out_unlock:
if (atomic)
spin_unlock(&bd_mapping->i_private_lock);
else
folio_unlock(folio);
folio_put(folio);
out:
return ret;
}
static void end_buffer_async_read(struct buffer_head *bh, int uptodate)
{
unsigned long flags;
struct buffer_head *first;
struct buffer_head *tmp;
struct folio *folio;
int folio_uptodate = 1;
BUG_ON(!buffer_async_read(bh));
folio = bh->b_folio;
if (uptodate) {
set_buffer_uptodate(bh);
} else {
clear_buffer_uptodate(bh);
buffer_io_error(bh, ", async page read");
}
/*
* Be _very_ careful from here on. Bad things can happen if
* two buffer heads end IO at almost the same time and both
* decide that the page is now completely done.
*/
first = folio_buffers(folio);
spin_lock_irqsave(&first->b_uptodate_lock, flags);
clear_buffer_async_read(bh);
unlock_buffer(bh);
tmp = bh;
do {
if (!buffer_uptodate(tmp))
folio_uptodate = 0;
if (buffer_async_read(tmp)) {
BUG_ON(!buffer_locked(tmp));
goto still_busy;
}
tmp = tmp->b_this_page;
} while (tmp != bh);
spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
folio_end_read(folio, folio_uptodate);
return;
still_busy:
spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
}
struct postprocess_bh_ctx {
struct work_struct work;
struct buffer_head *bh;
struct fsverity_info *vi;
};
static void verify_bh(struct work_struct *work)
{
struct postprocess_bh_ctx *ctx =
container_of(work, struct postprocess_bh_ctx, work);
struct buffer_head *bh = ctx->bh;
bool valid;
valid = fsverity_verify_blocks(ctx->vi, bh->b_folio, bh->b_size,
bh_offset(bh));
end_buffer_async_read(bh, valid);
kfree(ctx);
}
static void decrypt_bh(struct work_struct *work)
{
struct postprocess_bh_ctx *ctx =
container_of(work, struct postprocess_bh_ctx, work);
struct buffer_head *bh = ctx->bh;
int err;
err = fscrypt_decrypt_pagecache_blocks(bh->b_folio, bh->b_size,
bh_offset(bh));
if (err == 0 && ctx->vi) {
/*
* We use different work queues for decryption and for verity
* because verity may require reading metadata pages that need
* decryption, and we shouldn't recurse to the same workqueue.
*/
INIT_WORK(&ctx->work, verify_bh);
fsverity_enqueue_verify_work(&ctx->work);
return;
}
end_buffer_async_read(bh, err == 0);
kfree(ctx);
}
/*
* I/O completion handler for block_read_full_folio() - pages
* which come unlocked at the end of I/O.
*/
static void end_buffer_async_read_io(struct buffer_head *bh, int uptodate)
{
struct inode *inode = bh->b_folio->mapping->host;
bool decrypt = fscrypt_inode_uses_fs_layer_crypto(inode);
struct fsverity_info *vi = NULL;
/* needed by ext4 */
if (bh->b_folio->index < DIV_ROUND_UP(inode->i_size, PAGE_SIZE))
vi = fsverity_get_info(inode);
/* Decrypt (with fscrypt) and/or verify (with fsverity) if needed. */
if (uptodate && (decrypt || vi)) {
struct postprocess_bh_ctx *ctx = kmalloc_obj(*ctx, GFP_ATOMIC);
if (ctx) {
ctx->bh = bh;
ctx->vi = vi;
if (decrypt) {
INIT_WORK(&ctx->work, decrypt_bh);
fscrypt_enqueue_decrypt_work(&ctx->work);
} else {
INIT_WORK(&ctx->work, verify_bh);
fsverity_enqueue_verify_work(&ctx->work);
}
return;
}
uptodate = 0;
}
end_buffer_async_read(bh, uptodate);
}
/*
* Completion handler for block_write_full_folio() - folios which are unlocked
* during I/O, and which have the writeback flag cleared upon I/O completion.
*/
static void end_buffer_async_write(struct buffer_head *bh, int uptodate)
{
unsigned long flags;
struct buffer_head *first;
struct buffer_head *tmp;
struct folio *folio;
BUG_ON(!buffer_async_write(bh));
folio = bh->b_folio;
if (uptodate) {
set_buffer_uptodate(bh);
} else {
buffer_io_error(bh, ", lost async page write");
mark_buffer_write_io_error(bh);
clear_buffer_uptodate(bh);
}
first = folio_buffers(folio);
spin_lock_irqsave(&first->b_uptodate_lock, flags);
clear_buffer_async_write(bh);
unlock_buffer(bh);
tmp = bh->b_this_page;
while (tmp != bh) {
if (buffer_async_write(tmp)) {
BUG_ON(!buffer_locked(tmp));
goto still_busy;
}
tmp = tmp->b_this_page;
}
spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
folio_end_writeback(folio);
return;
still_busy:
spin_unlock_irqrestore(&first->b_uptodate_lock, flags);
}
/*
* If a page's buffers are under async readin (end_buffer_async_read
* completion) then there is a possibility that another thread of
* control could lock one of the buffers after it has completed
* but while some of the other buffers have not completed. This
* locked buffer would confuse end_buffer_async_read() into not unlocking
* the page. So the absence of BH_Async_Read tells end_buffer_async_read()
* that this buffer is not under async I/O.
*
* The page comes unlocked when it has no locked buffer_async buffers
* left.
*
* PageLocked prevents anyone starting new async I/O reads any of
* the buffers.
*
* PageWriteback is used to prevent simultaneous writeout of the same
* page.
*
* PageLocked prevents anyone from starting writeback of a page which is
* under read I/O (PageWriteback is only ever set against a locked page).
*/
static void mark_buffer_async_read(struct buffer_head *bh)
{
bh->b_end_io = end_buffer_async_read_io;
set_buffer_async_read(bh);
}
static void mark_buffer_async_write_endio(struct buffer_head *bh,
bh_end_io_t *handler)
{
bh->b_end_io = handler;
set_buffer_async_write(bh);
}
void mark_buffer_async_write(struct buffer_head *bh)
{
mark_buffer_async_write_endio(bh, end_buffer_async_write);
}
EXPORT_SYMBOL(mark_buffer_async_write);
/*
* fs/buffer.c contains helper functions for buffer-backed address space's
* fsync functions. A common requirement for buffer-based filesystems is
* that certain data from the backing blockdev needs to be written out for
* a successful fsync(). For example, ext2 indirect blocks need to be
* written back and waited upon before fsync() returns.
*
* The functions mmb_mark_buffer_dirty(), mmb_sync(), mmb_has_buffers()
* and mmb_invalidate() are provided for the management of a list of dependent
* buffers in mapping_metadata_bhs struct.
*
* The locking is a little subtle: The list of buffer heads is protected by
* the lock in mapping_metadata_bhs so functions coming from bdev mapping
* (such as try_to_free_buffers()) need to safely get to mapping_metadata_bhs
* using RCU, grab the lock, verify we didn't race with somebody detaching the
* bh / moving it to different inode and only then proceeding.
*/
void mmb_init(struct mapping_metadata_bhs *mmb, struct address_space *mapping)
{
spin_lock_init(&mmb->lock);
INIT_LIST_HEAD(&mmb->list);
mmb->mapping = mapping;
}
EXPORT_SYMBOL(mmb_init);
static void __remove_assoc_queue(struct mapping_metadata_bhs *mmb,
struct buffer_head *bh)
{
lockdep_assert_held(&mmb->lock);
list_del_init(&bh->b_assoc_buffers);
WARN_ON(!bh->b_mmb);
bh->b_mmb = NULL;
}
static void remove_assoc_queue(struct buffer_head *bh)
{
struct mapping_metadata_bhs *mmb;
/*
* The locking dance is ugly here. We need to acquire the lock
* protecting the metadata bh list while possibly racing with bh
* being removed from the list or moved to a different one. We
* use RCU to pin mapping_metadata_bhs in memory to
* opportunistically acquire the lock and then recheck the bh
* didn't move under us.
*/
while (bh->b_mmb) {
rcu_read_lock();
mmb = READ_ONCE(bh->b_mmb);
if (mmb) {
spin_lock(&mmb->lock);
if (bh->b_mmb == mmb)
__remove_assoc_queue(mmb, bh);
spin_unlock(&mmb->lock);
}
rcu_read_unlock();
}
}
bool mmb_has_buffers(struct mapping_metadata_bhs *mmb)
{
return !list_empty(&mmb->list);
}
EXPORT_SYMBOL_GPL(mmb_has_buffers);
/**
* mmb_sync - write out & wait upon all buffers in a list
* @mmb: the list of buffers to write
*
* Starts I/O against the buffers in the given list and waits upon
* that I/O. Basically, this is a convenience function for fsync(). @mmb is
* for a file or directory which needs those buffers to be written for a
* successful fsync().
*
* We have conflicting pressures: we want to make sure that all
* initially dirty buffers get waited on, but that any subsequently
* dirtied buffers don't. After all, we don't want fsync to last
* forever if somebody is actively writing to the file.
*
* Do this in two main stages: first we copy dirty buffers to a
* temporary inode list, queueing the writes as we go. Then we clean
* up, waiting for those writes to complete. mark_buffer_dirty_inode()
* doesn't touch b_assoc_buffers list if b_mmb is not NULL so we are sure the
* buffer stays on our list until IO completes (at which point it can be
* reaped).
*/
int mmb_sync(struct mapping_metadata_bhs *mmb)
{
struct buffer_head *bh;
int err = 0;
struct blk_plug plug;
LIST_HEAD(tmp);
if (!mmb_has_buffers(mmb))
return 0;
blk_start_plug(&plug);
spin_lock(&mmb->lock);
while (!list_empty(&mmb->list)) {
bh = BH_ENTRY(mmb->list.next);
WARN_ON_ONCE(bh->b_mmb != mmb);
__remove_assoc_queue(mmb, bh);
/* Avoid race with mark_buffer_dirty_inode() which does
* a lockless check and we rely on seeing the dirty bit */
smp_mb();
if (buffer_dirty(bh) || buffer_locked(bh)) {
list_add(&bh->b_assoc_buffers, &tmp);
bh->b_mmb = mmb;
if (buffer_dirty(bh)) {
get_bh(bh);
spin_unlock(&mmb->lock);
/*
* Ensure any pending I/O completes so that
* write_dirty_buffer() actually writes the
* current contents - it is a noop if I/O is
* still in flight on potentially older
* contents.
*/
write_dirty_buffer(bh, REQ_SYNC);
/*
* Kick off IO for the previous mapping. Note
* that we will not run the very last mapping,
* wait_on_buffer() will do that for us
* through sync_buffer().
*/
brelse(bh);
spin_lock(&mmb->lock);
}
}
}
spin_unlock(&mmb->lock);
blk_finish_plug(&plug);
spin_lock(&mmb->lock);
while (!list_empty(&tmp)) {
bh = BH_ENTRY(tmp.prev);
get_bh(bh);
__remove_assoc_queue(mmb, bh);
/* Avoid race with mark_buffer_dirty_inode() which does
* a lockless check and we rely on seeing the dirty bit */
smp_mb();
if (buffer_dirty(bh)) {
list_add(&bh->b_assoc_buffers, &mmb->list);
bh->b_mmb = mmb;
}
spin_unlock(&mmb->lock);
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
err = -EIO;
brelse(bh);
spin_lock(&mmb->lock);
}
spin_unlock(&mmb->lock);
return err;
}
EXPORT_SYMBOL(mmb_sync);
/**
* mmb_fsync_noflush - fsync implementation for simple filesystems with
* metadata buffers list
*
* @file: file to synchronize
* @mmb: list of metadata bhs to flush
* @start: start offset in bytes
* @end: end offset in bytes (inclusive)
* @datasync: only synchronize essential metadata if true
*
* This is an implementation of the fsync method for simple filesystems which
* track all non-inode metadata in the buffers list hanging off the @mmb
* structure.
*/
int mmb_fsync_noflush(struct file *file, struct mapping_metadata_bhs *mmb,
loff_t start, loff_t end, bool datasync)
{
struct inode *inode = file->f_mapping->host;
int err;
int ret = 0;
err = file_write_and_wait_range(file, start, end);
if (err)
return err;
if (mmb)
ret = mmb_sync(mmb);
if (!(inode_state_read_once(inode) & I_DIRTY_ALL))
goto out;
if (datasync && !(inode_state_read_once(inode) & I_DIRTY_DATASYNC))
goto out;
err = sync_inode_metadata(inode, 1);
if (ret == 0)
ret = err;
out:
/* check and advance again to catch errors after syncing out buffers */
err = file_check_and_advance_wb_err(file);
if (ret == 0)
ret = err;
return ret;
}
EXPORT_SYMBOL(mmb_fsync_noflush);
/**
* mmb_fsync - fsync implementation for simple filesystems with metadata
* buffers list
*
* @file: file to synchronize
* @mmb: list of metadata bhs to flush
* @start: start offset in bytes
* @end: end offset in bytes (inclusive)
* @datasync: only synchronize essential metadata if true
*
* This is an implementation of the fsync method for simple filesystems which
* track all non-inode metadata in the buffers list hanging off the @mmb
* structure. This also makes sure that a device cache flush operation is
* called at the end.
*/
int mmb_fsync(struct file *file, struct mapping_metadata_bhs *mmb,
loff_t start, loff_t end, bool datasync)
{
struct inode *inode = file->f_mapping->host;
int ret;
ret = mmb_fsync_noflush(file, mmb, start, end, datasync);
if (!ret)
ret = blkdev_issue_flush(inode->i_sb->s_bdev);
return ret;
}
EXPORT_SYMBOL(mmb_fsync);
/*
* Called when we've recently written block `bblock', and it is known that
* `bblock' was for a buffer_boundary() buffer. This means that the block at
* `bblock + 1' is probably a dirty indirect block. Hunt it down and, if it's
* dirty, schedule it for IO. So that indirects merge nicely with their data.
*/
void write_boundary_block(struct block_device *bdev,
sector_t bblock, unsigned blocksize)
{
struct buffer_head *bh;
bh = __find_get_block_nonatomic(bdev, bblock + 1, blocksize);
if (bh) {
if (buffer_dirty(bh))
write_dirty_buffer(bh, 0);
put_bh(bh);
}
}
void mmb_mark_buffer_dirty(struct buffer_head *bh,
struct mapping_metadata_bhs *mmb)
{
mark_buffer_dirty(bh);
if (!bh->b_mmb) {
spin_lock(&mmb->lock);
/*
* For a corrupted filesystem with multiply claimed blocks this
* can fail. Avoid corrupting the linked list in that case.
*/
if (cmpxchg(&bh->b_mmb, NULL, mmb) != NULL) {
spin_unlock(&mmb->lock);
return;
}
list_move_tail(&bh->b_assoc_buffers, &mmb->list);
spin_unlock(&mmb->lock);
}
}
EXPORT_SYMBOL(mmb_mark_buffer_dirty);
/**
* block_dirty_folio - Mark a folio as dirty.
* @mapping: The address space containing this folio.
* @folio: The folio to mark dirty.
*
* Filesystems which use buffer_heads can use this function as their
* ->dirty_folio implementation. Some filesystems need to do a little
* work before calling this function. Filesystems which do not use
* buffer_heads should call filemap_dirty_folio() instead.
*
* If the folio has buffers, the uptodate buffers are set dirty, to
* preserve dirty-state coherency between the folio and the buffers.
* Buffers added to a dirty folio are created dirty.
*
* The buffers are dirtied before the folio is dirtied. There's a small
* race window in which writeback may see the folio cleanness but not the
* buffer dirtiness. That's fine. If this code were to set the folio
* dirty before the buffers, writeback could clear the folio dirty flag,
* see a bunch of clean buffers and we'd end up with dirty buffers/clean
* folio on the dirty folio list.
*
* We use i_private_lock to lock against try_to_free_buffers() while
* using the folio's buffer list. This also prevents clean buffers
* being added to the folio after it was set dirty.
*
* Context: May only be called from process context. Does not sleep.
* Caller must ensure that @folio cannot be truncated during this call,
* typically by holding the folio lock or having a page in the folio
* mapped and holding the page table lock.
*
* Return: True if the folio was dirtied; false if it was already dirtied.
*/
bool block_dirty_folio(struct address_space *mapping, struct folio *folio)
{
struct buffer_head *head;
bool newly_dirty;
spin_lock(&mapping->i_private_lock);
head = folio_buffers(folio);
if (head) {
struct buffer_head *bh = head;
do {
set_buffer_dirty(bh);
bh = bh->b_this_page;
} while (bh != head);
}
/*
* Lock out page's memcg migration to keep PageDirty
* synchronized with per-memcg dirty page counters.
*/
newly_dirty = !folio_test_set_dirty(folio);
spin_unlock(&mapping->i_private_lock);
if (newly_dirty)
__folio_mark_dirty(folio, mapping, 1);
if (newly_dirty)
__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
return newly_dirty;
}
EXPORT_SYMBOL(block_dirty_folio);
/*
* Invalidate any and all dirty buffers on a given buffers list. We are
* probably unmounting the fs, but that doesn't mean we have already
* done a sync(). Just drop the buffers from the inode list.
*/
void mmb_invalidate(struct mapping_metadata_bhs *mmb)
{
if (mmb_has_buffers(mmb)) {
spin_lock(&mmb->lock);
while (!list_empty(&mmb->list))
__remove_assoc_queue(mmb, BH_ENTRY(mmb->list.next));
spin_unlock(&mmb->lock);
}
}
EXPORT_SYMBOL(mmb_invalidate);
/*
* Create the appropriate buffers when given a folio for data area and
* the size of each buffer.. Use the bh->b_this_page linked list to
* follow the buffers created. Return NULL if unable to create more
* buffers.
*
* The retry flag is used to differentiate async IO (paging, swapping)
* which may not fail from ordinary buffer allocations.
*/
struct buffer_head *folio_alloc_buffers(struct folio *folio, unsigned long size,
gfp_t gfp)
{
struct buffer_head *bh, *head;
long offset;
struct mem_cgroup *memcg, *old_memcg;
memcg = get_mem_cgroup_from_folio(folio);
old_memcg = set_active_memcg(memcg);
head = NULL;
offset = folio_size(folio);
while ((offset -= size) >= 0) {
bh = alloc_buffer_head(gfp);
if (!bh)
goto no_grow;
bh->b_this_page = head;
bh->b_blocknr = -1;
head = bh;
bh->b_size = size;
/* Link the buffer to its folio */
folio_set_bh(bh, folio, offset);
}
out:
set_active_memcg(old_memcg);
mem_cgroup_put(memcg);
return head;
/*
* In case anything failed, we just free everything we got.
*/
no_grow:
if (head) {
do {
bh = head;
head = head->b_this_page;
free_buffer_head(bh);
} while (head);
}
goto out;
}
EXPORT_SYMBOL_GPL(folio_alloc_buffers);
struct buffer_head *alloc_page_buffers(struct page *page, unsigned long size)
{
gfp_t gfp = GFP_NOFS | __GFP_ACCOUNT;
return folio_alloc_buffers(page_folio(page), size, gfp);
}
EXPORT_SYMBOL_GPL(alloc_page_buffers);
static inline void link_dev_buffers(struct folio *folio,
struct buffer_head *head)
{
struct buffer_head *bh, *tail;
bh = head;
do {
tail = bh;
bh = bh->b_this_page;
} while (bh);
tail->b_this_page = head;
folio_attach_private(folio, head);
}
static sector_t blkdev_max_block(struct block_device *bdev, unsigned int size)
{
sector_t retval = ~((sector_t)0);
loff_t sz = bdev_nr_bytes(bdev);
if (sz) {
unsigned int sizebits = blksize_bits(size);
retval = (sz >> sizebits);
}
return retval;
}
/*
* Initialise the state of a blockdev folio's buffers.
*/
static sector_t folio_init_buffers(struct folio *folio,
struct block_device *bdev, unsigned size)
{
struct buffer_head *head = folio_buffers(folio);
struct buffer_head *bh = head;
bool uptodate = folio_test_uptodate(folio);
sector_t block = div_u64(folio_pos(folio), size);
sector_t end_block = blkdev_max_block(bdev, size);
do {
if (!buffer_mapped(bh)) {
bh->b_end_io = NULL;
bh->b_private = NULL;
bh->b_bdev = bdev;
bh->b_blocknr = block;
if (uptodate)
set_buffer_uptodate(bh);
if (block < end_block)
set_buffer_mapped(bh);
}
block++;
bh = bh->b_this_page;
} while (bh != head);
/*
* Caller needs to validate requested block against end of device.
*/
return end_block;
}
/*
* Create the page-cache folio that contains the requested block.
*
* This is used purely for blockdev mappings.
*
* Returns false if we have a failure which cannot be cured by retrying
* without sleeping. Returns true if we succeeded, or the caller should retry.
*/
static bool grow_dev_folio(struct block_device *bdev, sector_t block,
pgoff_t index, unsigned size, gfp_t gfp)
{
struct address_space *mapping = bdev->bd_mapping;
struct folio *folio;
struct buffer_head *bh;
sector_t end_block = 0;
folio = __filemap_get_folio(mapping, index,
FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
if (IS_ERR(folio))
return false;
bh = folio_buffers(folio);
if (bh) {
if (bh->b_size == size) {
end_block = folio_init_buffers(folio, bdev, size);
goto unlock;
}
/*
* Retrying may succeed; for example the folio may finish
* writeback, or buffers may be cleaned. This should not
* happen very often; maybe we have old buffers attached to
* this blockdev's page cache and we're trying to change
* the block size?
*/
if (!try_to_free_buffers(folio)) {
end_block = ~0ULL;
goto unlock;
}
}
bh = folio_alloc_buffers(folio, size, gfp | __GFP_ACCOUNT);
if (!bh)
goto unlock;
/*
* Link the folio to the buffers and initialise them. Take the
* lock to be atomic wrt __find_get_block(), which does not
* run under the folio lock.
*/
spin_lock(&mapping->i_private_lock);
link_dev_buffers(folio, bh);
end_block = folio_init_buffers(folio, bdev, size);
spin_unlock(&mapping->i_private_lock);
unlock:
folio_unlock(folio);
folio_put(folio);
return block < end_block;
}
/*
* Create buffers for the specified block device block's folio. If
* that folio was dirty, the buffers are set dirty also. Returns false
* if we've hit a permanent error.
*/
static bool grow_buffers(struct block_device *bdev, sector_t block,
unsigned size, gfp_t gfp)
{
loff_t pos;
/*
* Check for a block which lies outside our maximum possible
* pagecache index.
*/
if (check_mul_overflow(block, (sector_t)size, &pos) || pos > MAX_LFS_FILESIZE) {
printk(KERN_ERR "%s: requested out-of-range block %llu for device %pg\n",
__func__, (unsigned long long)block,
bdev);
return false;
}
/* Create a folio with the proper size buffers */
return grow_dev_folio(bdev, block, pos / PAGE_SIZE, size, gfp);
}
static struct buffer_head *
__getblk_slow(struct block_device *bdev, sector_t block,
unsigned size, gfp_t gfp)
{
bool blocking = gfpflags_allow_blocking(gfp);
if (WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))) {
printk(KERN_ERR "getblk(): block size %d not aligned to logical block size %d\n",
size, bdev_logical_block_size(bdev));
return NULL;
}
for (;;) {
struct buffer_head *bh;
if (!grow_buffers(bdev, block, size, gfp))
return NULL;
if (blocking)
bh = __find_get_block_nonatomic(bdev, block, size);
else
bh = __find_get_block(bdev, block, size);
if (bh)
return bh;
}
}
/*
* The relationship between dirty buffers and dirty pages:
*
* Whenever a page has any dirty buffers, the page's dirty bit is set, and
* the page is tagged dirty in the page cache.
*
* At all times, the dirtiness of the buffers represents the dirtiness of
* subsections of the page. If the page has buffers, the page dirty bit is
* merely a hint about the true dirty state.
*
* When a page is set dirty in its entirety, all its buffers are marked dirty
* (if the page has buffers).
*
* When a buffer is marked dirty, its page is dirtied, but the page's other
* buffers are not.
*
* Also. When blockdev buffers are explicitly read with bread(), they
* individually become uptodate. But their backing page remains not
* uptodate - even if all of its buffers are uptodate. A subsequent
* block_read_full_folio() against that folio will discover all the uptodate
* buffers, will set the folio uptodate and will perform no I/O.
*/
/**
* mark_buffer_dirty - mark a buffer_head as needing writeout
* @bh: the buffer_head to mark dirty
*
* mark_buffer_dirty() will set the dirty bit against the buffer, then set
* its backing page dirty, then tag the page as dirty in the page cache
* and then attach the address_space's inode to its superblock's dirty
* inode list.
*
* mark_buffer_dirty() is atomic. It takes bh->b_folio->mapping->i_private_lock,
* i_pages lock and mapping->host->i_lock.
*/
void mark_buffer_dirty(struct buffer_head *bh)
{
WARN_ON_ONCE(!buffer_uptodate(bh));
trace_block_dirty_buffer(bh);
/*
* Very *carefully* optimize the it-is-already-dirty case.
*
* Don't let the final "is it dirty" escape to before we
* perhaps modified the buffer.
*/
if (buffer_dirty(bh)) {
smp_mb();
if (buffer_dirty(bh))
return;
}
if (!test_set_buffer_dirty(bh)) {
struct folio *folio = bh->b_folio;
struct address_space *mapping = NULL;
if (!folio_test_set_dirty(folio)) {
mapping = folio->mapping;
if (mapping)
__folio_mark_dirty(folio, mapping, 0);
}
if (mapping)
__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
}
}
EXPORT_SYMBOL(mark_buffer_dirty);
void mark_buffer_write_io_error(struct buffer_head *bh)
{
set_buffer_write_io_error(bh);
/* FIXME: do we need to set this in both places? */
if (bh->b_folio && bh->b_folio->mapping)
mapping_set_error(bh->b_folio->mapping, -EIO);
if (bh->b_mmb)
mapping_set_error(bh->b_mmb->mapping, -EIO);
}
EXPORT_SYMBOL(mark_buffer_write_io_error);
/**
* __brelse - Release a buffer.
* @bh: The buffer to release.
*
* This variant of brelse() can be called if @bh is guaranteed to not be NULL.
*/
void __brelse(struct buffer_head *bh)
{
if (atomic_read(&bh->b_count)) {
put_bh(bh);
return;
}
WARN(1, KERN_ERR "VFS: brelse: Trying to free free buffer\n");
}
EXPORT_SYMBOL(__brelse);
/**
* __bforget - Discard any dirty data in a buffer.
* @bh: The buffer to forget.
*
* This variant of bforget() can be called if @bh is guaranteed to not
* be NULL.
*/
void __bforget(struct buffer_head *bh)
{
clear_buffer_dirty(bh);
remove_assoc_queue(bh);
__brelse(bh);
}
EXPORT_SYMBOL(__bforget);
static struct buffer_head *__bread_slow(struct buffer_head *bh)
{
lock_buffer(bh);
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
return bh;
} else {
get_bh(bh);
bh->b_end_io = end_buffer_read_sync;
submit_bh(REQ_OP_READ, bh);
wait_on_buffer(bh);
if (buffer_uptodate(bh))
return bh;
}
brelse(bh);
return NULL;
}
/*
* Per-cpu buffer LRU implementation. To reduce the cost of __find_get_block().
* The bhs[] array is sorted - newest buffer is at bhs[0]. Buffers have their
* refcount elevated by one when they're in an LRU. A buffer can only appear
* once in a particular CPU's LRU. A single buffer can be present in multiple
* CPU's LRUs at the same time.
*
* This is a transparent caching front-end to sb_bread(), sb_getblk() and
* sb_find_get_block().
*
* The LRUs themselves only need locking against invalidate_bh_lrus. We use
* a local interrupt disable for that.
*/
#define BH_LRU_SIZE 16
struct bh_lru {
struct buffer_head *bhs[BH_LRU_SIZE];
};
static DEFINE_PER_CPU(struct bh_lru, bh_lrus) = {{ NULL }};
#ifdef CONFIG_SMP
#define bh_lru_lock() local_irq_disable()
#define bh_lru_unlock() local_irq_enable()
#else
#define bh_lru_lock() preempt_disable()
#define bh_lru_unlock() preempt_enable()
#endif
static inline void check_irqs_on(void)
{
#ifdef irqs_disabled
BUG_ON(irqs_disabled());
#endif
}
/*
* Install a buffer_head into this cpu's LRU. If not already in the LRU, it is
* inserted at the front, and the buffer_head at the back if any is evicted.
* Or, if already in the LRU it is moved to the front.
*/
static void bh_lru_install(struct buffer_head *bh)
{
struct buffer_head *evictee = bh;
struct bh_lru *b;
int i;
check_irqs_on();
bh_lru_lock();
/*
* the refcount of buffer_head in bh_lru prevents dropping the
* attached page(i.e., try_to_free_buffers) so it could cause
* failing page migration.
* Skip putting upcoming bh into bh_lru until migration is done.
*/
if (lru_cache_disabled() || cpu_is_isolated(smp_processor_id())) {
bh_lru_unlock();
return;
}
b = this_cpu_ptr(&bh_lrus);
for (i = 0; i < BH_LRU_SIZE; i++) {
swap(evictee, b->bhs[i]);
if (evictee == bh) {
bh_lru_unlock();
return;
}
}
get_bh(bh);
bh_lru_unlock();
brelse(evictee);
}
/*
* Look up the bh in this cpu's LRU. If it's there, move it to the head.
*/
static struct buffer_head *
lookup_bh_lru(struct block_device *bdev, sector_t block, unsigned size)
{
struct buffer_head *ret = NULL;
unsigned int i;
check_irqs_on();
bh_lru_lock();
if (cpu_is_isolated(smp_processor_id())) {
bh_lru_unlock();
return NULL;
}
for (i = 0; i < BH_LRU_SIZE; i++) {
struct buffer_head *bh = __this_cpu_read(bh_lrus.bhs[i]);
if (bh && bh->b_blocknr == block && bh->b_bdev == bdev &&
bh->b_size == size) {
if (i) {
while (i) {
__this_cpu_write(bh_lrus.bhs[i],
__this_cpu_read(bh_lrus.bhs[i - 1]));
i--;
}
__this_cpu_write(bh_lrus.bhs[0], bh);
}
get_bh(bh);
ret = bh;
break;
}
}
bh_lru_unlock();
return ret;
}
/*
* Perform a pagecache lookup for the matching buffer. If it's there, refresh
* it in the LRU and mark it as accessed. If it is not present then return
* NULL. Atomic context callers may also return NULL if the buffer is being
* migrated; similarly the page is not marked accessed either.
*/
static struct buffer_head *
find_get_block_common(struct block_device *bdev, sector_t block,
unsigned size, bool atomic)
{
struct buffer_head *bh = lookup_bh_lru(bdev, block, size);
if (bh == NULL) {
/* __find_get_block_slow will mark the page accessed */
bh = __find_get_block_slow(bdev, block, atomic);
if (bh)
bh_lru_install(bh);
} else
touch_buffer(bh);
return bh;
}
struct buffer_head *
__find_get_block(struct block_device *bdev, sector_t block, unsigned size)
{
return find_get_block_common(bdev, block, size, true);
}
EXPORT_SYMBOL(__find_get_block);
/* same as __find_get_block() but allows sleeping contexts */
struct buffer_head *
__find_get_block_nonatomic(struct block_device *bdev, sector_t block,
unsigned size)
{
return find_get_block_common(bdev, block, size, false);
}
EXPORT_SYMBOL(__find_get_block_nonatomic);
/**
* bdev_getblk - Get a buffer_head in a block device's buffer cache.
* @bdev: The block device.
* @block: The block number.
* @size: The size of buffer_heads for this @bdev.
* @gfp: The memory allocation flags to use.
*
* The returned buffer head has its reference count incremented, but is
* not locked. The caller should call brelse() when it has finished
* with the buffer. The buffer may not be uptodate. If needed, the
* caller can bring it uptodate either by reading it or overwriting it.
*
* Return: The buffer head, or NULL if memory could not be allocated.
*/
struct buffer_head *bdev_getblk(struct block_device *bdev, sector_t block,
unsigned size, gfp_t gfp)
{
struct buffer_head *bh;
if (gfpflags_allow_blocking(gfp))
bh = __find_get_block_nonatomic(bdev, block, size);
else
bh = __find_get_block(bdev, block, size);
might_alloc(gfp);
if (bh)
return bh;
return __getblk_slow(bdev, block, size, gfp);
}
EXPORT_SYMBOL(bdev_getblk);
/*
* Do async read-ahead on a buffer..
*/
void __breadahead(struct block_device *bdev, sector_t block, unsigned size)
{
struct buffer_head *bh = bdev_getblk(bdev, block, size,
GFP_NOWAIT | __GFP_MOVABLE);
if (likely(bh)) {
bh_readahead(bh, REQ_RAHEAD);
brelse(bh);
}
}
EXPORT_SYMBOL(__breadahead);
/**
* __bread_gfp() - Read a block.
* @bdev: The block device to read from.
* @block: Block number in units of block size.
* @size: The block size of this device in bytes.
* @gfp: Not page allocation flags; see below.
*
* You are not expected to call this function. You should use one of
* sb_bread(), sb_bread_unmovable() or __bread().
*
* Read a specified block, and return the buffer head that refers to it.
* If @gfp is 0, the memory will be allocated using the block device's
* default GFP flags. If @gfp is __GFP_MOVABLE, the memory may be
* allocated from a movable area. Do not pass in a complete set of
* GFP flags.
*
* The returned buffer head has its refcount increased. The caller should
* call brelse() when it has finished with the buffer.
*
* Context: May sleep waiting for I/O.
* Return: NULL if the block was unreadable.
*/
struct buffer_head *__bread_gfp(struct block_device *bdev, sector_t block,
unsigned size, gfp_t gfp)
{
struct buffer_head *bh;
gfp |= mapping_gfp_constraint(bdev->bd_mapping, ~__GFP_FS);
/*
* Prefer looping in the allocator rather than here, at least that
* code knows what it's doing.
*/
gfp |= __GFP_NOFAIL;
bh = bdev_getblk(bdev, block, size, gfp);
if (likely(bh) && !buffer_uptodate(bh))
bh = __bread_slow(bh);
return bh;
}
EXPORT_SYMBOL(__bread_gfp);
static void __invalidate_bh_lrus(struct bh_lru *b)
{
int i;
for (i = 0; i < BH_LRU_SIZE; i++) {
brelse(b->bhs[i]);
b->bhs[i] = NULL;
}
}
/*
* invalidate_bh_lrus() is called rarely - but not only at unmount.
* This doesn't race because it runs in each cpu either in irq
* or with preempt disabled.
*/
static void invalidate_bh_lru(void *arg)
{
struct bh_lru *b = &get_cpu_var(bh_lrus);
__invalidate_bh_lrus(b);
put_cpu_var(bh_lrus);
}
bool has_bh_in_lru(int cpu, void *dummy)
{
struct bh_lru *b = per_cpu_ptr(&bh_lrus, cpu);
int i;
for (i = 0; i < BH_LRU_SIZE; i++) {
if (b->bhs[i])
return true;
}
return false;
}
void invalidate_bh_lrus(void)
{
on_each_cpu_cond(has_bh_in_lru, invalidate_bh_lru, NULL, 1);
}
EXPORT_SYMBOL_GPL(invalidate_bh_lrus);
/*
* It's called from workqueue context so we need a bh_lru_lock to close
* the race with preemption/irq.
*/
void invalidate_bh_lrus_cpu(void)
{
struct bh_lru *b;
bh_lru_lock();
b = this_cpu_ptr(&bh_lrus);
__invalidate_bh_lrus(b);
bh_lru_unlock();
}
void folio_set_bh(struct buffer_head *bh, struct folio *folio,
unsigned long offset)
{
bh->b_folio = folio;
BUG_ON(offset >= folio_size(folio));
if (folio_test_highmem(folio))
/*
* This catches illegal uses and preserves the offset:
*/
bh->b_data = (char *)(0 + offset);
else
bh->b_data = folio_address(folio) + offset;
}
EXPORT_SYMBOL(folio_set_bh);
/*
* Called when truncating a buffer on a page completely.
*/
/* Bits that are cleared during an invalidate */
#define BUFFER_FLAGS_DISCARD \
(1 << BH_Mapped | 1 << BH_New | 1 << BH_Req | \
1 << BH_Delay | 1 << BH_Unwritten)
static void discard_buffer(struct buffer_head * bh)
{
unsigned long b_state;
lock_buffer(bh);
clear_buffer_dirty(bh);
bh->b_bdev = NULL;
b_state = READ_ONCE(bh->b_state);
do {
} while (!try_cmpxchg_relaxed(&bh->b_state, &b_state,
b_state & ~BUFFER_FLAGS_DISCARD));
unlock_buffer(bh);
}
/**
* block_invalidate_folio - Invalidate part or all of a buffer-backed folio.
* @folio: The folio which is affected.
* @offset: start of the range to invalidate
* @length: length of the range to invalidate
*
* block_invalidate_folio() is called when all or part of the folio has been
* invalidated by a truncate operation.
*
* block_invalidate_folio() does not have to release all buffers, but it must
* ensure that no dirty buffer is left outside @offset and that no I/O
* is underway against any of the blocks which are outside the truncation
* point. Because the caller is about to free (and possibly reuse) those
* blocks on-disk.
*/
void block_invalidate_folio(struct folio *folio, size_t offset, size_t length)
{
struct buffer_head *head, *bh, *next;
size_t curr_off = 0;
size_t stop = length + offset;
BUG_ON(!folio_test_locked(folio));
/*
* Check for overflow
*/
BUG_ON(stop > folio_size(folio) || stop < length);
head = folio_buffers(folio);
if (!head)
return;
bh = head;
do {
size_t next_off = curr_off + bh->b_size;
next = bh->b_this_page;
/*
* Are we still fully in range ?
*/
if (next_off > stop)
goto out;
/*
* is this block fully invalidated?
*/
if (offset <= curr_off)
discard_buffer(bh);
curr_off = next_off;
bh = next;
} while (bh != head);
/*
* We release buffers only if the entire folio is being invalidated.
* The get_block cached value has been unconditionally invalidated,
* so real IO is not possible anymore.
*/
if (length == folio_size(folio))
filemap_release_folio(folio, 0);
out:
folio_clear_mappedtodisk(folio);
}
EXPORT_SYMBOL(block_invalidate_folio);
/*
* We attach and possibly dirty the buffers atomically wrt
* block_dirty_folio() via i_private_lock. try_to_free_buffers
* is already excluded via the folio lock.
*/
struct buffer_head *create_empty_buffers(struct folio *folio,
unsigned long blocksize, unsigned long b_state)
{
struct buffer_head *bh, *head, *tail;
gfp_t gfp = GFP_NOFS | __GFP_ACCOUNT | __GFP_NOFAIL;
head = folio_alloc_buffers(folio, blocksize, gfp);
bh = head;
do {
bh->b_state |= b_state;
tail = bh;
bh = bh->b_this_page;
} while (bh);
tail->b_this_page = head;
spin_lock(&folio->mapping->i_private_lock);
if (folio_test_uptodate(folio) || folio_test_dirty(folio)) {
bh = head;
do {
if (folio_test_dirty(folio))
set_buffer_dirty(bh);
if (folio_test_uptodate(folio))
set_buffer_uptodate(bh);
bh = bh->b_this_page;
} while (bh != head);
}
folio_attach_private(folio, head);
spin_unlock(&folio->mapping->i_private_lock);
return head;
}
EXPORT_SYMBOL(create_empty_buffers);
/**
* clean_bdev_aliases: clean a range of buffers in block device
* @bdev: Block device to clean buffers in
* @block: Start of a range of blocks to clean
* @len: Number of blocks to clean
*
* We are taking a range of blocks for data and we don't want writeback of any
* buffer-cache aliases starting from return from this function and until the
* moment when something will explicitly mark the buffer dirty (hopefully that
* will not happen until we will free that block ;-) We don't even need to mark
* it not-uptodate - nobody can expect anything from a newly allocated buffer
* anyway. We used to use unmap_buffer() for such invalidation, but that was
* wrong. We definitely don't want to mark the alias unmapped, for example - it
* would confuse anyone who might pick it with bread() afterwards...
*
* Also.. Note that bforget() doesn't lock the buffer. So there can be
* writeout I/O going on against recently-freed buffers. We don't wait on that
* I/O in bforget() - it's more efficient to wait on the I/O only if we really
* need to. That happens here.
*/
void clean_bdev_aliases(struct block_device *bdev, sector_t block, sector_t len)
{
struct address_space *bd_mapping = bdev->bd_mapping;
const int blkbits = bd_mapping->host->i_blkbits;
struct folio_batch fbatch;
pgoff_t index = ((loff_t)block << blkbits) / PAGE_SIZE;
pgoff_t end;
int i, count;
struct buffer_head *bh;
struct buffer_head *head;
end = ((loff_t)(block + len - 1) << blkbits) / PAGE_SIZE;
folio_batch_init(&fbatch);
while (filemap_get_folios(bd_mapping, &index, end, &fbatch)) {
count = folio_batch_count(&fbatch);
for (i = 0; i < count; i++) {
struct folio *folio = fbatch.folios[i];
if (!folio_buffers(folio))
continue;
/*
* We use folio lock instead of bd_mapping->i_private_lock
* to pin buffers here since we can afford to sleep and
* it scales better than a global spinlock lock.
*/
folio_lock(folio);
/* Recheck when the folio is locked which pins bhs */
head = folio_buffers(folio);
if (!head)
goto unlock_page;
bh = head;
do {
if (!buffer_mapped(bh) || (bh->b_blocknr < block))
goto next;
if (bh->b_blocknr >= block + len)
break;
clear_buffer_dirty(bh);
wait_on_buffer(bh);
clear_buffer_req(bh);
next:
bh = bh->b_this_page;
} while (bh != head);
unlock_page:
folio_unlock(folio);
}
folio_batch_release(&fbatch);
cond_resched();
/* End of range already reached? */
if (index > end || !index)
break;
}
}
EXPORT_SYMBOL(clean_bdev_aliases);
static struct buffer_head *folio_create_buffers(struct folio *folio,
struct inode *inode,
unsigned int b_state)
{
struct buffer_head *bh;
BUG_ON(!folio_test_locked(folio));
bh = folio_buffers(folio);
if (!bh)
bh = create_empty_buffers(folio,
1 << READ_ONCE(inode->i_blkbits), b_state);
return bh;
}
/*
* NOTE! All mapped/uptodate combinations are valid:
*
* Mapped Uptodate Meaning
*
* No No "unknown" - must do get_block()
* No Yes "hole" - zero-filled
* Yes No "allocated" - allocated on disk, not read in
* Yes Yes "valid" - allocated and up-to-date in memory.
*
* "Dirty" is valid only with the last case (mapped+uptodate).
*/
/*
* While block_write_full_folio is writing back the dirty buffers under
* the page lock, whoever dirtied the buffers may decide to clean them
* again at any time. We handle that by only looking at the buffer
* state inside lock_buffer().
*
* If block_write_full_folio() is called for regular writeback
* (wbc->sync_mode == WB_SYNC_NONE) then it will redirty a page which has a
* locked buffer. This only can happen if someone has written the buffer
* directly, with submit_bh(). At the address_space level PageWriteback
* prevents this contention from occurring.
*
* If block_write_full_folio() is called with wbc->sync_mode ==
* WB_SYNC_ALL, the writes are posted using REQ_SYNC; this
* causes the writes to be flagged as synchronous writes.
*/
int __block_write_full_folio(struct inode *inode, struct folio *folio,
get_block_t *get_block, struct writeback_control *wbc)
{
int err;
sector_t block;
sector_t last_block;
struct buffer_head *bh, *head;
size_t blocksize;
int nr_underway = 0;
blk_opf_t write_flags = wbc_to_write_flags(wbc);
head = folio_create_buffers(folio, inode,
(1 << BH_Dirty) | (1 << BH_Uptodate));
/*
* Be very careful. We have no exclusion from block_dirty_folio
* here, and the (potentially unmapped) buffers may become dirty at
* any time. If a buffer becomes dirty here after we've inspected it
* then we just miss that fact, and the folio stays dirty.
*
* Buffers outside i_size may be dirtied by block_dirty_folio;
* handle that here by just cleaning them.
*/
bh = head;
blocksize = bh->b_size;
block = div_u64(folio_pos(folio), blocksize);
last_block = div_u64(i_size_read(inode) - 1, blocksize);
/*
* Get all the dirty buffers mapped to disk addresses and
* handle any aliases from the underlying blockdev's mapping.
*/
do {
if (block > last_block) {
/*
* mapped buffers outside i_size will occur, because
* this folio can be outside i_size when there is a
* truncate in progress.
*/
/*
* The buffer was zeroed by block_write_full_folio()
*/
clear_buffer_dirty(bh);
set_buffer_uptodate(bh);
} else if ((!buffer_mapped(bh) || buffer_delay(bh)) &&
buffer_dirty(bh)) {
WARN_ON(bh->b_size != blocksize);
err = get_block(inode, block, bh, 1);
if (err)
goto recover;
clear_buffer_delay(bh);
if (buffer_new(bh)) {
/* blockdev mappings never come here */
clear_buffer_new(bh);
clean_bdev_bh_alias(bh);
}
}
bh = bh->b_this_page;
block++;
} while (bh != head);
do {
if (!buffer_mapped(bh))
continue;
/*
* If it's a fully non-blocking write attempt and we cannot
* lock the buffer then redirty the folio. Note that this can
* potentially cause a busy-wait loop from writeback threads
* and kswapd activity, but those code paths have their own
* higher-level throttling.
*/
if (wbc->sync_mode != WB_SYNC_NONE) {
lock_buffer(bh);
} else if (!trylock_buffer(bh)) {
folio_redirty_for_writepage(wbc, folio);
continue;
}
if (test_clear_buffer_dirty(bh)) {
mark_buffer_async_write_endio(bh,
end_buffer_async_write);
} else {
unlock_buffer(bh);
}
} while ((bh = bh->b_this_page) != head);
/*
* The folio and its buffers are protected by the writeback flag,
* so we can drop the bh refcounts early.
*/
BUG_ON(folio_test_writeback(folio));
folio_start_writeback(folio);
do {
struct buffer_head *next = bh->b_this_page;
if (buffer_async_write(bh)) {
submit_bh_wbc(REQ_OP_WRITE | write_flags, bh,
inode->i_write_hint, wbc);
nr_underway++;
}
bh = next;
} while (bh != head);
folio_unlock(folio);
err = 0;
done:
if (nr_underway == 0) {
/*
* The folio was marked dirty, but the buffers were
* clean. Someone wrote them back by hand with
* write_dirty_buffer/submit_bh. A rare case.
*/
folio_end_writeback(folio);
/*
* The folio and buffer_heads can be released at any time from
* here on.
*/
}
return err;
recover:
/*
* ENOSPC, or some other error. We may already have added some
* blocks to the file, so we need to write these out to avoid
* exposing stale data.
* The folio is currently locked and not marked for writeback
*/
bh = head;
/* Recovery: lock and submit the mapped buffers */
do {
if (buffer_mapped(bh) && buffer_dirty(bh) &&
!buffer_delay(bh)) {
lock_buffer(bh);
mark_buffer_async_write_endio(bh,
end_buffer_async_write);
} else {
/*
* The buffer may have been set dirty during
* attachment to a dirty folio.
*/
clear_buffer_dirty(bh);
}
} while ((bh = bh->b_this_page) != head);
BUG_ON(folio_test_writeback(folio));
mapping_set_error(folio->mapping, err);
folio_start_writeback(folio);
do {
struct buffer_head *next = bh->b_this_page;
if (buffer_async_write(bh)) {
clear_buffer_dirty(bh);
submit_bh_wbc(REQ_OP_WRITE | write_flags, bh,
inode->i_write_hint, wbc);
nr_underway++;
}
bh = next;
} while (bh != head);
folio_unlock(folio);
goto done;
}
EXPORT_SYMBOL(__block_write_full_folio);
/*
* If a folio has any new buffers, zero them out here, and mark them uptodate
* and dirty so they'll be written out (in order to prevent uninitialised
* block data from leaking). And clear the new bit.
*/
void folio_zero_new_buffers(struct folio *folio, size_t from, size_t to)
{
size_t block_start, block_end;
struct buffer_head *head, *bh;
BUG_ON(!folio_test_locked(folio));
head = folio_buffers(folio);
if (!head)
return;
bh = head;
block_start = 0;
do {
block_end = block_start + bh->b_size;
if (buffer_new(bh)) {
if (block_end > from && block_start < to) {
if (!folio_test_uptodate(folio)) {
size_t start, xend;
start = max(from, block_start);
xend = min(to, block_end);
folio_zero_segment(folio, start, xend);
set_buffer_uptodate(bh);
}
clear_buffer_new(bh);
mark_buffer_dirty(bh);
}
}
block_start = block_end;
bh = bh->b_this_page;
} while (bh != head);
}
EXPORT_SYMBOL(folio_zero_new_buffers);
static int
iomap_to_bh(struct inode *inode, sector_t block, struct buffer_head *bh,
const struct iomap *iomap)
{
loff_t offset = (loff_t)block << inode->i_blkbits;
bh->b_bdev = iomap->bdev;
/*
* Block points to offset in file we need to map, iomap contains
* the offset at which the map starts. If the map ends before the
* current block, then do not map the buffer and let the caller
* handle it.
*/
if (offset >= iomap->offset + iomap->length)
return -EIO;
switch (iomap->type) {
case IOMAP_HOLE:
/*
* If the buffer is not up to date or beyond the current EOF,
* we need to mark it as new to ensure sub-block zeroing is
* executed if necessary.
*/
if (!buffer_uptodate(bh) ||
(offset >= i_size_read(inode)))
set_buffer_new(bh);
return 0;
case IOMAP_DELALLOC:
if (!buffer_uptodate(bh) ||
(offset >= i_size_read(inode)))
set_buffer_new(bh);
set_buffer_uptodate(bh);
set_buffer_mapped(bh);
set_buffer_delay(bh);
return 0;
case IOMAP_UNWRITTEN:
/*
* For unwritten regions, we always need to ensure that regions
* in the block we are not writing to are zeroed. Mark the
* buffer as new to ensure this.
*/
set_buffer_new(bh);
set_buffer_unwritten(bh);
fallthrough;
case IOMAP_MAPPED:
if ((iomap->flags & IOMAP_F_NEW) ||
offset >= i_size_read(inode)) {
/*
* This can happen if truncating the block device races
* with the check in the caller as i_size updates on
* block devices aren't synchronized by i_rwsem for
* block devices.
*/
if (S_ISBLK(inode->i_mode))
return -EIO;
set_buffer_new(bh);
}
bh->b_blocknr = (iomap->addr + offset - iomap->offset) >>
inode->i_blkbits;
set_buffer_mapped(bh);
return 0;
default:
WARN_ON_ONCE(1);
return -EIO;
}
}
int __block_write_begin_int(struct folio *folio, loff_t pos, unsigned len,
get_block_t *get_block, const struct iomap *iomap)
{
size_t from = offset_in_folio(folio, pos);
size_t to = from + len;
struct inode *inode = folio->mapping->host;
size_t block_start, block_end;
sector_t block;
int err = 0;
size_t blocksize;
struct buffer_head *bh, *head, *wait[2], **wait_bh=wait;
BUG_ON(!folio_test_locked(folio));
BUG_ON(to > folio_size(folio));
BUG_ON(from > to);
head = folio_create_buffers(folio, inode, 0);
blocksize = head->b_size;
block = div_u64(folio_pos(folio), blocksize);
for (bh = head, block_start = 0; bh != head || !block_start;
block++, block_start=block_end, bh = bh->b_this_page) {
block_end = block_start + blocksize;
if (block_end <= from || block_start >= to) {
if (folio_test_uptodate(folio)) {
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
}
continue;
}
if (buffer_new(bh))
clear_buffer_new(bh);
if (!buffer_mapped(bh)) {
WARN_ON(bh->b_size != blocksize);
if (get_block)
err = get_block(inode, block, bh, 1);
else
err = iomap_to_bh(inode, block, bh, iomap);
if (err)
break;
if (buffer_new(bh)) {
clean_bdev_bh_alias(bh);
if (folio_test_uptodate(folio)) {
clear_buffer_new(bh);
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
continue;
}
if (block_end > to || block_start < from)
folio_zero_segments(folio,
to, block_end,
block_start, from);
continue;
}
}
if (folio_test_uptodate(folio)) {
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
continue;
}
if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
!buffer_unwritten(bh) &&
(block_start < from || block_end > to)) {
bh_read_nowait(bh, 0);
*wait_bh++=bh;
}
}
/*
* If we issued read requests - let them complete.
*/
while(wait_bh > wait) {
wait_on_buffer(*--wait_bh);
if (!buffer_uptodate(*wait_bh))
err = -EIO;
}
if (unlikely(err))
folio_zero_new_buffers(folio, from, to);
return err;
}
int __block_write_begin(struct folio *folio, loff_t pos, unsigned len,
get_block_t *get_block)
{
return __block_write_begin_int(folio, pos, len, get_block, NULL);
}
EXPORT_SYMBOL(__block_write_begin);
void block_commit_write(struct folio *folio, size_t from, size_t to)
{
size_t block_start, block_end;
bool partial = false;
unsigned blocksize;
struct buffer_head *bh, *head;
bh = head = folio_buffers(folio);
if (!bh)
return;
blocksize = bh->b_size;
block_start = 0;
do {
block_end = block_start + blocksize;
if (block_end <= from || block_start >= to) {
if (!buffer_uptodate(bh))
partial = true;
} else {
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
}
if (buffer_new(bh))
clear_buffer_new(bh);
block_start = block_end;
bh = bh->b_this_page;
} while (bh != head);
/*
* If this is a partial write which happened to make all buffers
* uptodate then we can optimize away a bogus read_folio() for
* the next read(). Here we 'discover' whether the folio went
* uptodate as a result of this (potentially partial) write.
*/
if (!partial)
folio_mark_uptodate(folio);
}
EXPORT_SYMBOL(block_commit_write);
/*
* block_write_begin takes care of the basic task of block allocation and
* bringing partial write blocks uptodate first.
*
* The filesystem needs to handle block truncation upon failure.
*/
int block_write_begin(struct address_space *mapping, loff_t pos, unsigned len,
struct folio **foliop, get_block_t *get_block)
{
pgoff_t index = pos >> PAGE_SHIFT;
struct folio *folio;
int status;
folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
mapping_gfp_mask(mapping));
if (IS_ERR(folio))
return PTR_ERR(folio);
status = __block_write_begin_int(folio, pos, len, get_block, NULL);
if (unlikely(status)) {
folio_unlock(folio);
folio_put(folio);
folio = NULL;
}
*foliop = folio;
return status;
}
EXPORT_SYMBOL(block_write_begin);
int block_write_end(loff_t pos, unsigned len, unsigned copied,
struct folio *folio)
{
size_t start = pos - folio_pos(folio);
if (unlikely(copied < len)) {
/*
* The buffers that were written will now be uptodate, so
* we don't have to worry about a read_folio reading them
* and overwriting a partial write. However if we have
* encountered a short write and only partially written
* into a buffer, it will not be marked uptodate, so a
* read_folio might come in and destroy our partial write.
*
* Do the simplest thing, and just treat any short write to a
* non uptodate folio as a zero-length write, and force the
* caller to redo the whole thing.
*/
if (!folio_test_uptodate(folio))
copied = 0;
folio_zero_new_buffers(folio, start+copied, start+len);
}
flush_dcache_folio(folio);
/* This could be a short (even 0-length) commit */
block_commit_write(folio, start, start + copied);
return copied;
}
EXPORT_SYMBOL(block_write_end);
int generic_write_end(const struct kiocb *iocb, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct folio *folio, void *fsdata)
{
struct inode *inode = mapping->host;
loff_t old_size = inode->i_size;
bool i_size_changed = false;
copied = block_write_end(pos, len, copied, folio);
/*
* No need to use i_size_read() here, the i_size cannot change under us
* because we hold i_rwsem.
*
* But it's important to update i_size while still holding folio lock:
* page writeout could otherwise come in and zero beyond i_size.
*/
if (pos + copied > inode->i_size) {
i_size_write(inode, pos + copied);
i_size_changed = true;
}
folio_unlock(folio);
folio_put(folio);
if (old_size < pos)
pagecache_isize_extended(inode, old_size, pos);
/*
* Don't mark the inode dirty under page lock. First, it unnecessarily
* makes the holding time of page lock longer. Second, it forces lock
* ordering of page lock and transaction start for journaling
* filesystems.
*/
if (i_size_changed)
mark_inode_dirty(inode);
return copied;
}
EXPORT_SYMBOL(generic_write_end);
/*
* block_is_partially_uptodate checks whether buffers within a folio are
* uptodate or not.
*
* Returns true if all buffers which correspond to the specified part
* of the folio are uptodate.
*/
bool block_is_partially_uptodate(struct folio *folio, size_t from, size_t count)
{
unsigned block_start, block_end, blocksize;
unsigned to;
struct buffer_head *bh, *head;
bool ret = true;
head = folio_buffers(folio);
if (!head)
return false;
blocksize = head->b_size;
to = min(folio_size(folio) - from, count);
to = from + to;
if (from < blocksize && to > folio_size(folio) - blocksize)
return false;
bh = head;
block_start = 0;
do {
block_end = block_start + blocksize;
if (block_end > from && block_start < to) {
if (!buffer_uptodate(bh)) {
ret = false;
break;
}
if (block_end >= to)
break;
}
block_start = block_end;
bh = bh->b_this_page;
} while (bh != head);
return ret;
}
EXPORT_SYMBOL(block_is_partially_uptodate);
/*
* Generic "read_folio" function for block devices that have the normal
* get_block functionality. This is most of the block device filesystems.
* Reads the folio asynchronously --- the unlock_buffer() and
* set/clear_buffer_uptodate() functions propagate buffer state into the
* folio once IO has completed.
*/
int block_read_full_folio(struct folio *folio, get_block_t *get_block)
{
struct inode *inode = folio->mapping->host;
sector_t iblock, lblock;
struct buffer_head *bh, *head, *prev = NULL;
size_t blocksize;
int fully_mapped = 1;
bool page_error = false;
loff_t limit = i_size_read(inode);
/* This is needed for ext4. */
if (IS_ENABLED(CONFIG_FS_VERITY) && IS_VERITY(inode))
limit = inode->i_sb->s_maxbytes;
head = folio_create_buffers(folio, inode, 0);
blocksize = head->b_size;
iblock = div_u64(folio_pos(folio), blocksize);
lblock = div_u64(limit + blocksize - 1, blocksize);
bh = head;
do {
if (buffer_uptodate(bh))
continue;
if (!buffer_mapped(bh)) {
int err = 0;
fully_mapped = 0;
if (iblock < lblock) {
WARN_ON(bh->b_size != blocksize);
err = get_block(inode, iblock, bh, 0);
if (err)
page_error = true;
}
if (!buffer_mapped(bh)) {
folio_zero_range(folio, bh_offset(bh),
blocksize);
if (!err)
set_buffer_uptodate(bh);
continue;
}
/*
* get_block() might have updated the buffer
* synchronously
*/
if (buffer_uptodate(bh))
continue;
}
lock_buffer(bh);
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
continue;
}
mark_buffer_async_read(bh);
if (prev)
submit_bh(REQ_OP_READ, prev);
prev = bh;
} while (iblock++, (bh = bh->b_this_page) != head);
if (fully_mapped)
folio_set_mappedtodisk(folio);
/*
* All buffers are uptodate or get_block() returned an error
* when trying to map them - we must finish the read because
* end_buffer_async_read() will never be called on any buffer
* in this folio.
*/
if (prev)
submit_bh(REQ_OP_READ, prev);
else
folio_end_read(folio, !page_error);
return 0;
}
EXPORT_SYMBOL(block_read_full_folio);
/* utility function for filesystems that need to do work on expanding
* truncates. Uses filesystem pagecache writes to allow the filesystem to
* deal with the hole.
*/
int generic_cont_expand_simple(struct inode *inode, loff_t size)
{
struct address_space *mapping = inode->i_mapping;
const struct address_space_operations *aops = mapping->a_ops;
struct folio *folio;
void *fsdata = NULL;
int err;
err = inode_newsize_ok(inode, size);
if (err)
goto out;
err = aops->write_begin(NULL, mapping, size, 0, &folio, &fsdata);
if (err)
goto out;
err = aops->write_end(NULL, mapping, size, 0, 0, folio, fsdata);
BUG_ON(err > 0);
out:
return err;
}
EXPORT_SYMBOL(generic_cont_expand_simple);
static int cont_expand_zero(const struct kiocb *iocb,
struct address_space *mapping,
loff_t pos, loff_t *bytes)
{
struct inode *inode = mapping->host;
const struct address_space_operations *aops = mapping->a_ops;
unsigned int blocksize = i_blocksize(inode);
struct folio *folio;
void *fsdata = NULL;
pgoff_t index, curidx;
loff_t curpos;
unsigned zerofrom, offset, len;
int err = 0;
index = pos >> PAGE_SHIFT;
offset = pos & ~PAGE_MASK;
while (index > (curidx = (curpos = *bytes)>>PAGE_SHIFT)) {
zerofrom = curpos & ~PAGE_MASK;
if (zerofrom & (blocksize-1)) {
*bytes |= (blocksize-1);
(*bytes)++;
}
len = PAGE_SIZE - zerofrom;
err = aops->write_begin(iocb, mapping, curpos, len,
&folio, &fsdata);
if (err)
goto out;
folio_zero_range(folio, offset_in_folio(folio, curpos), len);
err = aops->write_end(iocb, mapping, curpos, len, len,
folio, fsdata);
if (err < 0)
goto out;
BUG_ON(err != len);
err = 0;
balance_dirty_pages_ratelimited(mapping);
if (fatal_signal_pending(current)) {
err = -EINTR;
goto out;
}
}
/* page covers the boundary, find the boundary offset */
if (index == curidx) {
zerofrom = curpos & ~PAGE_MASK;
/* if we will expand the thing last block will be filled */
if (offset <= zerofrom) {
goto out;
}
if (zerofrom & (blocksize-1)) {
*bytes |= (blocksize-1);
(*bytes)++;
}
len = offset - zerofrom;
err = aops->write_begin(iocb, mapping, curpos, len,
&folio, &fsdata);
if (err)
goto out;
folio_zero_range(folio, offset_in_folio(folio, curpos), len);
err = aops->write_end(iocb, mapping, curpos, len, len,
folio, fsdata);
if (err < 0)
goto out;
BUG_ON(err != len);
err = 0;
}
out:
return err;
}
/*
* For moronic filesystems that do not allow holes in file.
* We may have to extend the file.
*/
int cont_write_begin(const struct kiocb *iocb, struct address_space *mapping,
loff_t pos, unsigned len, struct folio **foliop,
void **fsdata, get_block_t *get_block, loff_t *bytes)
{
struct inode *inode = mapping->host;
unsigned int blocksize = i_blocksize(inode);
unsigned int zerofrom;
int err;
err = cont_expand_zero(iocb, mapping, pos, bytes);
if (err)
return err;
zerofrom = *bytes & ~PAGE_MASK;
if (pos+len > *bytes && zerofrom & (blocksize-1)) {
*bytes |= (blocksize-1);
(*bytes)++;
}
return block_write_begin(mapping, pos, len, foliop, get_block);
}
EXPORT_SYMBOL(cont_write_begin);
/*
* block_page_mkwrite() is not allowed to change the file size as it gets
* called from a page fault handler when a page is first dirtied. Hence we must
* be careful to check for EOF conditions here. We set the page up correctly
* for a written page which means we get ENOSPC checking when writing into
* holes and correct delalloc and unwritten extent mapping on filesystems that
* support these features.
*
* We are not allowed to take the i_rwsem here so we have to play games to
* protect against truncate races as the page could now be beyond EOF. Because
* truncate writes the inode size before removing pages, once we have the
* page lock we can determine safely if the page is beyond EOF. If it is not
* beyond EOF, then the page is guaranteed safe against truncation until we
* unlock the page.
*
* Direct callers of this function should protect against filesystem freezing
* using sb_start_pagefault() - sb_end_pagefault() functions.
*/
int block_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf,
get_block_t get_block)
{
struct folio *folio = page_folio(vmf->page);
struct inode *inode = file_inode(vma->vm_file);
unsigned long end;
loff_t size;
int ret;
folio_lock(folio);
size = i_size_read(inode);
if ((folio->mapping != inode->i_mapping) ||
(folio_pos(folio) >= size)) {
/* We overload EFAULT to mean page got truncated */
ret = -EFAULT;
goto out_unlock;
}
end = folio_size(folio);
/* folio is wholly or partially inside EOF */
if (folio_pos(folio) + end > size)
end = size - folio_pos(folio);
ret = __block_write_begin_int(folio, 0, end, get_block, NULL);
if (unlikely(ret))
goto out_unlock;
block_commit_write(folio, 0, end);
folio_mark_dirty(folio);
folio_wait_stable(folio);
return 0;
out_unlock:
folio_unlock(folio);
return ret;
}
EXPORT_SYMBOL(block_page_mkwrite);
int block_truncate_page(struct address_space *mapping,
loff_t from, get_block_t *get_block)
{
pgoff_t index = from >> PAGE_SHIFT;
unsigned blocksize;
sector_t iblock;
size_t offset, length, pos;
struct inode *inode = mapping->host;
struct folio *folio;
struct buffer_head *bh;
int err = 0;
blocksize = i_blocksize(inode);
length = from & (blocksize - 1);
/* Block boundary? Nothing to do */
if (!length)
return 0;
length = blocksize - length;
iblock = ((loff_t)index * PAGE_SIZE) >> inode->i_blkbits;
folio = filemap_grab_folio(mapping, index);
if (IS_ERR(folio))
return PTR_ERR(folio);
bh = folio_buffers(folio);
if (!bh)
bh = create_empty_buffers(folio, blocksize, 0);
/* Find the buffer that contains "offset" */
offset = offset_in_folio(folio, from);
pos = blocksize;
while (offset >= pos) {
bh = bh->b_this_page;
iblock++;
pos += blocksize;
}
if (!buffer_mapped(bh)) {
WARN_ON(bh->b_size != blocksize);
err = get_block(inode, iblock, bh, 0);
if (err)
goto unlock;
/* unmapped? It's a hole - nothing to do */
if (!buffer_mapped(bh))
goto unlock;
}
/* Ok, it's mapped. Make sure it's up-to-date */
if (folio_test_uptodate(folio))
set_buffer_uptodate(bh);
if (!buffer_uptodate(bh) && !buffer_delay(bh) && !buffer_unwritten(bh)) {
err = bh_read(bh, 0);
/* Uhhuh. Read error. Complain and punt. */
if (err < 0)
goto unlock;
}
folio_zero_range(folio, offset, length);
mark_buffer_dirty(bh);
unlock:
folio_unlock(folio);
folio_put(folio);
return err;
}
EXPORT_SYMBOL(block_truncate_page);
/*
* The generic write folio function for buffer-backed address_spaces
*/
int block_write_full_folio(struct folio *folio, struct writeback_control *wbc,
void *get_block)
{
struct inode * const inode = folio->mapping->host;
loff_t i_size = i_size_read(inode);
/* Is the folio fully inside i_size? */
if (folio_next_pos(folio) <= i_size)
return __block_write_full_folio(inode, folio, get_block, wbc);
/* Is the folio fully outside i_size? (truncate in progress) */
if (folio_pos(folio) >= i_size) {
folio_unlock(folio);
return 0; /* don't care */
}
/*
* The folio straddles i_size. It must be zeroed out on each and every
* writeback invocation because it may be mmapped. "A file is mapped
* in multiples of the page size. For a file that is not a multiple of
* the page size, the remaining memory is zeroed when mapped, and
* writes to that region are not written out to the file."
*/
folio_zero_segment(folio, offset_in_folio(folio, i_size),
folio_size(folio));
return __block_write_full_folio(inode, folio, get_block, wbc);
}
sector_t generic_block_bmap(struct address_space *mapping, sector_t block,
get_block_t *get_block)
{
struct inode *inode = mapping->host;
struct buffer_head tmp = {
.b_size = i_blocksize(inode),
};
get_block(inode, block, &tmp, 0);
return tmp.b_blocknr;
}
EXPORT_SYMBOL(generic_block_bmap);
static void end_bio_bh_io_sync(struct bio *bio)
{
struct buffer_head *bh = bio->bi_private;
if (unlikely(bio_flagged(bio, BIO_QUIET)))
set_bit(BH_Quiet, &bh->b_state);
bh->b_end_io(bh, !bio->bi_status);
bio_put(bio);
}
static void buffer_set_crypto_ctx(struct bio *bio, const struct buffer_head *bh,
gfp_t gfp_mask)
{
const struct address_space *mapping = folio_mapping(bh->b_folio);
/*
* The ext4 journal (jbd2) can submit a buffer_head it directly created
* for a non-pagecache page. fscrypt doesn't care about these.
*/
if (!mapping)
return;
fscrypt_set_bio_crypt_ctx(bio, mapping->host,
folio_pos(bh->b_folio) + bh_offset(bh), gfp_mask);
}
static void submit_bh_wbc(blk_opf_t opf, struct buffer_head *bh,
enum rw_hint write_hint,
struct writeback_control *wbc)
{
const enum req_op op = opf & REQ_OP_MASK;
struct bio *bio;
BUG_ON(!buffer_locked(bh));
BUG_ON(!buffer_mapped(bh));
BUG_ON(!bh->b_end_io);
BUG_ON(buffer_delay(bh));
BUG_ON(buffer_unwritten(bh));
/*
* Only clear out a write error when rewriting
*/
if (test_set_buffer_req(bh) && (op == REQ_OP_WRITE))
clear_buffer_write_io_error(bh);
if (buffer_meta(bh))
opf |= REQ_META;
if (buffer_prio(bh))
opf |= REQ_PRIO;
bio = bio_alloc(bh->b_bdev, 1, opf, GFP_NOIO);
if (IS_ENABLED(CONFIG_FS_ENCRYPTION))
buffer_set_crypto_ctx(bio, bh, GFP_NOIO);
bio->bi_iter.bi_sector = bh->b_blocknr * (bh->b_size >> 9);
bio->bi_write_hint = write_hint;
bio_add_folio_nofail(bio, bh->b_folio, bh->b_size, bh_offset(bh));
bio->bi_end_io = end_bio_bh_io_sync;
bio->bi_private = bh;
/* Take care of bh's that straddle the end of the device */
guard_bio_eod(bio);
if (wbc) {
wbc_init_bio(wbc, bio);
wbc_account_cgroup_owner(wbc, bh->b_folio, bh->b_size);
}
blk_crypto_submit_bio(bio);
}
void submit_bh(blk_opf_t opf, struct buffer_head *bh)
{
submit_bh_wbc(opf, bh, WRITE_LIFE_NOT_SET, NULL);
}
EXPORT_SYMBOL(submit_bh);
void write_dirty_buffer(struct buffer_head *bh, blk_opf_t op_flags)
{
lock_buffer(bh);
if (!test_clear_buffer_dirty(bh)) {
unlock_buffer(bh);
return;
}
bh->b_end_io = end_buffer_write_sync;
get_bh(bh);
submit_bh(REQ_OP_WRITE | op_flags, bh);
}
EXPORT_SYMBOL(write_dirty_buffer);
/*
* For a data-integrity writeout, we need to wait upon any in-progress I/O
* and then start new I/O and then wait upon it. The caller must have a ref on
* the buffer_head.
*/
int __sync_dirty_buffer(struct buffer_head *bh, blk_opf_t op_flags)
{
WARN_ON(atomic_read(&bh->b_count) < 1);
lock_buffer(bh);
if (test_clear_buffer_dirty(bh)) {
/*
* The bh should be mapped, but it might not be if the
* device was hot-removed. Not much we can do but fail the I/O.
*/
if (!buffer_mapped(bh)) {
unlock_buffer(bh);
return -EIO;
}
get_bh(bh);
bh->b_end_io = end_buffer_write_sync;
submit_bh(REQ_OP_WRITE | op_flags, bh);
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
return -EIO;
} else {
unlock_buffer(bh);
}
return 0;
}
EXPORT_SYMBOL(__sync_dirty_buffer);
int sync_dirty_buffer(struct buffer_head *bh)
{
return __sync_dirty_buffer(bh, REQ_SYNC);
}
EXPORT_SYMBOL(sync_dirty_buffer);
static inline int buffer_busy(struct buffer_head *bh)
{
return atomic_read(&bh->b_count) |
(bh->b_state & ((1 << BH_Dirty) | (1 << BH_Lock)));
}
static bool
drop_buffers(struct folio *folio, struct buffer_head **buffers_to_free)
{
struct buffer_head *head = folio_buffers(folio);
struct buffer_head *bh;
bh = head;
do {
if (buffer_busy(bh))
goto failed;
bh = bh->b_this_page;
} while (bh != head);
do {
struct buffer_head *next = bh->b_this_page;
remove_assoc_queue(bh);
bh = next;
} while (bh != head);
*buffers_to_free = head;
folio_detach_private(folio);
return true;
failed:
return false;
}
/**
* try_to_free_buffers - Release buffers attached to this folio.
* @folio: The folio.
*
* If any buffers are in use (dirty, under writeback, elevated refcount),
* no buffers will be freed.
*
* If the folio is dirty but all the buffers are clean then we need to
* be sure to mark the folio clean as well. This is because the folio
* may be against a block device, and a later reattachment of buffers
* to a dirty folio will set *all* buffers dirty. Which would corrupt
* filesystem data on the same device.
*
* The same applies to regular filesystem folios: if all the buffers are
* clean then we set the folio clean and proceed. To do that, we require
* total exclusion from block_dirty_folio(). That is obtained with
* i_private_lock.
*
* Exclusion against try_to_free_buffers may be obtained by either
* locking the folio or by holding its mapping's i_private_lock.
*
* Context: Process context. @folio must be locked. Will not sleep.
* Return: true if all buffers attached to this folio were freed.
*/
bool try_to_free_buffers(struct folio *folio)
{
struct address_space * const mapping = folio->mapping;
struct buffer_head *buffers_to_free = NULL;
bool ret = 0;
BUG_ON(!folio_test_locked(folio));
if (folio_test_writeback(folio))
return false;
/* Misconfigured folio check */
if (WARN_ON_ONCE(!folio_buffers(folio)))
return true;
if (mapping == NULL) { /* can this still happen? */
ret = drop_buffers(folio, &buffers_to_free);
goto out;
}
spin_lock(&mapping->i_private_lock);
ret = drop_buffers(folio, &buffers_to_free);
/*
* If the filesystem writes its buffers by hand (eg ext3)
* then we can have clean buffers against a dirty folio. We
* clean the folio here; otherwise the VM will never notice
* that the filesystem did any IO at all.
*
* Also, during truncate, discard_buffer will have marked all
* the folio's buffers clean. We discover that here and clean
* the folio also.
*
* i_private_lock must be held over this entire operation in order
* to synchronise against block_dirty_folio and prevent the
* dirty bit from being lost.
*/
if (ret)
folio_cancel_dirty(folio);
spin_unlock(&mapping->i_private_lock);
out:
if (buffers_to_free) {
struct buffer_head *bh = buffers_to_free;
do {
struct buffer_head *next = bh->b_this_page;
free_buffer_head(bh);
bh = next;
} while (bh != buffers_to_free);
}
return ret;
}
EXPORT_SYMBOL(try_to_free_buffers);
/*
* Buffer-head allocation
*/
static struct kmem_cache *bh_cachep __ro_after_init;
/*
* Once the number of bh's in the machine exceeds this level, we start
* stripping them in writeback.
*/
static unsigned long max_buffer_heads __ro_after_init;
int buffer_heads_over_limit;
struct bh_accounting {
int nr; /* Number of live bh's */
int ratelimit; /* Limit cacheline bouncing */
};
static DEFINE_PER_CPU(struct bh_accounting, bh_accounting) = {0, 0};
static void recalc_bh_state(void)
{
int i;
int tot = 0;
if (__this_cpu_inc_return(bh_accounting.ratelimit) - 1 < 4096)
return;
__this_cpu_write(bh_accounting.ratelimit, 0);
for_each_online_cpu(i)
tot += per_cpu(bh_accounting, i).nr;
buffer_heads_over_limit = (tot > max_buffer_heads);
}
struct buffer_head *alloc_buffer_head(gfp_t gfp_flags)
{
struct buffer_head *ret = kmem_cache_zalloc(bh_cachep, gfp_flags);
if (ret) {
INIT_LIST_HEAD(&ret->b_assoc_buffers);
spin_lock_init(&ret->b_uptodate_lock);
preempt_disable();
__this_cpu_inc(bh_accounting.nr);
recalc_bh_state();
preempt_enable();
}
return ret;
}
EXPORT_SYMBOL(alloc_buffer_head);
void free_buffer_head(struct buffer_head *bh)
{
BUG_ON(!list_empty(&bh->b_assoc_buffers));
kmem_cache_free(bh_cachep, bh);
preempt_disable();
__this_cpu_dec(bh_accounting.nr);
recalc_bh_state();
preempt_enable();
}
EXPORT_SYMBOL(free_buffer_head);
static int buffer_exit_cpu_dead(unsigned int cpu)
{
int i;
struct bh_lru *b = &per_cpu(bh_lrus, cpu);
for (i = 0; i < BH_LRU_SIZE; i++) {
brelse(b->bhs[i]);
b->bhs[i] = NULL;
}
this_cpu_add(bh_accounting.nr, per_cpu(bh_accounting, cpu).nr);
per_cpu(bh_accounting, cpu).nr = 0;
return 0;
}
/**
* bh_uptodate_or_lock - Test whether the buffer is uptodate
* @bh: struct buffer_head
*
* Return true if the buffer is up-to-date and false,
* with the buffer locked, if not.
*/
int bh_uptodate_or_lock(struct buffer_head *bh)
{
if (!buffer_uptodate(bh)) {
lock_buffer(bh);
if (!buffer_uptodate(bh))
return 0;
unlock_buffer(bh);
}
return 1;
}
EXPORT_SYMBOL(bh_uptodate_or_lock);
/**
* __bh_read - Submit read for a locked buffer
* @bh: struct buffer_head
* @op_flags: appending REQ_OP_* flags besides REQ_OP_READ
* @wait: wait until reading finish
*
* Returns zero on success or don't wait, and -EIO on error.
*/
int __bh_read(struct buffer_head *bh, blk_opf_t op_flags, bool wait)
{
int ret = 0;
BUG_ON(!buffer_locked(bh));
get_bh(bh);
bh->b_end_io = end_buffer_read_sync;
submit_bh(REQ_OP_READ | op_flags, bh);
if (wait) {
wait_on_buffer(bh);
if (!buffer_uptodate(bh))
ret = -EIO;
}
return ret;
}
EXPORT_SYMBOL(__bh_read);
/**
* __bh_read_batch - Submit read for a batch of unlocked buffers
* @nr: entry number of the buffer batch
* @bhs: a batch of struct buffer_head
* @op_flags: appending REQ_OP_* flags besides REQ_OP_READ
* @force_lock: force to get a lock on the buffer if set, otherwise drops any
* buffer that cannot lock.
*
* Returns zero on success or don't wait, and -EIO on error.
*/
void __bh_read_batch(int nr, struct buffer_head *bhs[],
blk_opf_t op_flags, bool force_lock)
{
int i;
for (i = 0; i < nr; i++) {
struct buffer_head *bh = bhs[i];
if (buffer_uptodate(bh))
continue;
if (force_lock)
lock_buffer(bh);
else
if (!trylock_buffer(bh))
continue;
if (buffer_uptodate(bh)) {
unlock_buffer(bh);
continue;
}
bh->b_end_io = end_buffer_read_sync;
get_bh(bh);
submit_bh(REQ_OP_READ | op_flags, bh);
}
}
EXPORT_SYMBOL(__bh_read_batch);
void __init buffer_init(void)
{
unsigned long nrpages;
int ret;
bh_cachep = KMEM_CACHE(buffer_head,
SLAB_RECLAIM_ACCOUNT|SLAB_PANIC);
/*
* Limit the bh occupancy to 10% of ZONE_NORMAL
*/
nrpages = (nr_free_buffer_pages() * 10) / 100;
max_buffer_heads = nrpages * (PAGE_SIZE / sizeof(struct buffer_head));
ret = cpuhp_setup_state_nocalls(CPUHP_FS_BUFF_DEAD, "fs/buffer:dead",
NULL, buffer_exit_cpu_dead);
WARN_ON(ret < 0);
}
]
|
| 10/2 |
2026/05/10 02:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 36898
output: 23
thoughts: 585
Thoughts: **Analyzing a Kernel Crash in `fs/buffer.c`**
Okay, so I've got a crash report here, and it's pointing me directly to `fs/buffer.c` at line 1029. The error message is clear: "block size not aligned to logical block size." That's usually a pretty straightforward alignment issue, and from the provided call trace, I'm thinking I need to investigate how it's being triggered.
Line 1029 itself is the `WARN_ON_ONCE` check that triggers the warning when the `size` isn't properly aligned with the logical block size of the block device. It's good that it's a `WARN_ON_ONCE`, as this indicates it's a debug warning and not a hard crash, but we still need to fix the alignment issue.
The backtrace tells me the execution path: `__bread_gfp` calls `sb_bread`, which then points me to `udf_read_tagged`, and then to `udf_check_anchor_block` and `udf_scan_anchors`, ultimately ending up in `udf_load_vrs` and then `udf_fill_super`. It's pretty clear this is a UDF filesystem issue. I'm going to jump into `fs/udf/super.c` and focus on those functions around the lines mentioned. I'll start with `udf_check_anchor_block`, then move on to `udf_scan_anchors`, `udf_load_vrs`, and `udf_fill_super` to see where the misaligned block size is being used. I need to figure out what's reading a block of an incorrect size and how it's getting past the various checks, since `__getblk_slow` should have caught the misalignment.
|
| 11/2 |
2026/05/10 02:56 |
tool |
read-file |
0m
Args:
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0-only
/*
* super.c
*
* PURPOSE
* Super block routines for the OSTA-UDF(tm) filesystem.
*
* DESCRIPTION
* OSTA-UDF(tm) = Optical Storage Technology Association
* Universal Disk Format.
*
* This code is based on version 2.00 of the UDF specification,
* and revision 3 of the ECMA 167 standard [equivalent to ISO 13346].
* http://www.osta.org/
* https://www.ecma.ch/
* https://www.iso.org/
*
* COPYRIGHT
* (C) 1998 Dave Boynton
* (C) 1998-2004 Ben Fennema
* (C) 2000 Stelias Computing Inc
*
* HISTORY
*
* 09/24/98 dgb changed to allow compiling outside of kernel, and
* added some debugging.
* 10/01/98 dgb updated to allow (some) possibility of compiling w/2.0.34
* 10/16/98 attempting some multi-session support
* 10/17/98 added freespace count for "df"
* 11/11/98 gr added novrs option
* 11/26/98 dgb added fileset,anchor mount options
* 12/06/98 blf really hosed things royally. vat/sparing support. sequenced
* vol descs. rewrote option handling based on isofs
* 12/20/98 find the free space bitmap (if it exists)
*/
#include "udfdecl.h"
#include <linux/blkdev.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/stat.h>
#include <linux/cdrom.h>
#include <linux/nls.h>
#include <linux/vfs.h>
#include <linux/vmalloc.h>
#include <linux/errno.h>
#include <linux/seq_file.h>
#include <linux/bitmap.h>
#include <linux/crc-itu-t.h>
#include <linux/log2.h>
#include <asm/byteorder.h>
#include <linux/iversion.h>
#include <linux/fs_context.h>
#include <linux/fs_parser.h>
#include "udf_sb.h"
#include "udf_i.h"
#include <linux/init.h>
#include <linux/uaccess.h>
enum {
VDS_POS_PRIMARY_VOL_DESC,
VDS_POS_UNALLOC_SPACE_DESC,
VDS_POS_LOGICAL_VOL_DESC,
VDS_POS_IMP_USE_VOL_DESC,
VDS_POS_LENGTH
};
#define VSD_FIRST_SECTOR_OFFSET 32768
#define VSD_MAX_SECTOR_OFFSET 0x800000
/*
* Maximum number of Terminating Descriptor / Logical Volume Integrity
* Descriptor redirections. The chosen numbers are arbitrary - just that we
* hopefully don't limit any real use of rewritten inode on write-once media
* but avoid looping for too long on corrupted media.
*/
#define UDF_MAX_TD_NESTING 64
#define UDF_MAX_LVID_NESTING 1000
enum { UDF_MAX_LINKS = 0xffff };
/*
* We limit filesize to 4TB. This is arbitrary as the on-disk format supports
* more but because the file space is described by a linked list of extents,
* each of which can have at most 1GB, the creation and handling of extents
* gets unusably slow beyond certain point...
*/
#define UDF_MAX_FILESIZE (1ULL << 42)
/* These are the "meat" - everything else is stuffing */
static int udf_fill_super(struct super_block *sb, struct fs_context *fc);
static void udf_put_super(struct super_block *);
static int udf_sync_fs(struct super_block *, int);
static void udf_load_logicalvolint(struct super_block *, struct kernel_extent_ad);
static void udf_open_lvid(struct super_block *);
static void udf_close_lvid(struct super_block *);
static unsigned int udf_count_free(struct super_block *);
static int udf_statfs(struct dentry *, struct kstatfs *);
static int udf_show_options(struct seq_file *, struct dentry *);
static int udf_init_fs_context(struct fs_context *fc);
static int udf_parse_param(struct fs_context *fc, struct fs_parameter *param);
static int udf_reconfigure(struct fs_context *fc);
static void udf_free_fc(struct fs_context *fc);
static const struct fs_parameter_spec udf_param_spec[];
struct logicalVolIntegrityDescImpUse *udf_sb_lvidiu(struct super_block *sb)
{
struct logicalVolIntegrityDesc *lvid;
unsigned int partnum;
unsigned int offset;
if (!UDF_SB(sb)->s_lvid_bh)
return NULL;
lvid = (struct logicalVolIntegrityDesc *)UDF_SB(sb)->s_lvid_bh->b_data;
partnum = le32_to_cpu(lvid->numOfPartitions);
/* The offset is to skip freeSpaceTable and sizeTable arrays */
offset = partnum * 2 * sizeof(uint32_t);
return (struct logicalVolIntegrityDescImpUse *)
(((uint8_t *)(lvid + 1)) + offset);
}
/* UDF filesystem type */
static int udf_get_tree(struct fs_context *fc)
{
return get_tree_bdev(fc, udf_fill_super);
}
static const struct fs_context_operations udf_context_ops = {
.parse_param = udf_parse_param,
.get_tree = udf_get_tree,
.reconfigure = udf_reconfigure,
.free = udf_free_fc,
};
static struct file_system_type udf_fstype = {
.owner = THIS_MODULE,
.name = "udf",
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
.init_fs_context = udf_init_fs_context,
.parameters = udf_param_spec,
};
MODULE_ALIAS_FS("udf");
static struct kmem_cache *udf_inode_cachep;
static struct inode *udf_alloc_inode(struct super_block *sb)
{
struct udf_inode_info *ei;
ei = alloc_inode_sb(sb, udf_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
ei->i_unique = 0;
ei->i_lenExtents = 0;
ei->i_lenStreams = 0;
ei->i_next_alloc_block = 0;
ei->i_next_alloc_goal = 0;
ei->i_strat4096 = 0;
ei->i_streamdir = 0;
ei->i_hidden = 0;
init_rwsem(&ei->i_data_sem);
ei->cached_extent.lstart = -1;
spin_lock_init(&ei->i_extent_cache_lock);
inode_set_iversion(&ei->vfs_inode, 1);
mmb_init(&ei->i_metadata_bhs, &ei->vfs_inode.i_data);
return &ei->vfs_inode;
}
static void udf_free_in_core_inode(struct inode *inode)
{
kmem_cache_free(udf_inode_cachep, UDF_I(inode));
}
static void init_once(void *foo)
{
struct udf_inode_info *ei = foo;
ei->i_data = NULL;
inode_init_once(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
udf_inode_cachep = kmem_cache_create("udf_inode_cache",
sizeof(struct udf_inode_info),
0, (SLAB_RECLAIM_ACCOUNT |
SLAB_ACCOUNT),
init_once);
if (!udf_inode_cachep)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(udf_inode_cachep);
}
/* Superblock operations */
static const struct super_operations udf_sb_ops = {
.alloc_inode = udf_alloc_inode,
.free_inode = udf_free_in_core_inode,
.write_inode = udf_write_inode,
.evict_inode = udf_evict_inode,
.put_super = udf_put_super,
.sync_fs = udf_sync_fs,
.statfs = udf_statfs,
.show_options = udf_show_options,
};
struct udf_options {
unsigned int blocksize;
unsigned int session;
unsigned int lastblock;
unsigned int anchor;
unsigned int flags;
umode_t umask;
kgid_t gid;
kuid_t uid;
umode_t fmode;
umode_t dmode;
struct nls_table *nls_map;
};
/*
* UDF has historically preserved prior mount options across
* a remount, so copy those here if remounting, otherwise set
* initial mount defaults.
*/
static void udf_init_options(struct fs_context *fc, struct udf_options *uopt)
{
if (fc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
struct super_block *sb = fc->root->d_sb;
struct udf_sb_info *sbi = UDF_SB(sb);
uopt->flags = sbi->s_flags;
uopt->uid = sbi->s_uid;
uopt->gid = sbi->s_gid;
uopt->umask = sbi->s_umask;
uopt->fmode = sbi->s_fmode;
uopt->dmode = sbi->s_dmode;
uopt->nls_map = NULL;
} else {
uopt->flags = (1 << UDF_FLAG_USE_AD_IN_ICB) |
(1 << UDF_FLAG_STRICT);
/*
* By default we'll use overflow[ug]id when UDF
* inode [ug]id == -1
*/
uopt->uid = make_kuid(current_user_ns(), overflowuid);
uopt->gid = make_kgid(current_user_ns(), overflowgid);
uopt->umask = 0;
uopt->fmode = UDF_INVALID_MODE;
uopt->dmode = UDF_INVALID_MODE;
uopt->nls_map = NULL;
uopt->session = 0xFFFFFFFF;
}
}
static int udf_init_fs_context(struct fs_context *fc)
{
struct udf_options *uopt;
uopt = kzalloc_obj(*uopt);
if (!uopt)
return -ENOMEM;
udf_init_options(fc, uopt);
fc->fs_private = uopt;
fc->ops = &udf_context_ops;
return 0;
}
static void udf_free_fc(struct fs_context *fc)
{
struct udf_options *uopt = fc->fs_private;
unload_nls(uopt->nls_map);
kfree(fc->fs_private);
}
static int __init init_udf_fs(void)
{
int err;
err = init_inodecache();
if (err)
goto out1;
err = register_filesystem(&udf_fstype);
if (err)
goto out;
return 0;
out:
destroy_inodecache();
out1:
return err;
}
static void __exit exit_udf_fs(void)
{
unregister_filesystem(&udf_fstype);
destroy_inodecache();
}
static int udf_sb_alloc_partition_maps(struct super_block *sb, u32 count)
{
struct udf_sb_info *sbi = UDF_SB(sb);
sbi->s_partmaps = kzalloc_objs(*sbi->s_partmaps, count);
if (!sbi->s_partmaps) {
sbi->s_partitions = 0;
return -ENOMEM;
}
sbi->s_partitions = count;
return 0;
}
static void udf_sb_free_bitmap(struct udf_bitmap *bitmap)
{
int i;
int nr_groups = bitmap->s_nr_groups;
for (i = 0; i < nr_groups; i++)
if (!IS_ERR_OR_NULL(bitmap->s_block_bitmap[i]))
brelse(bitmap->s_block_bitmap[i]);
kvfree(bitmap);
}
static void udf_free_partition(struct udf_part_map *map)
{
int i;
struct udf_meta_data *mdata;
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE)
iput(map->s_uspace.s_table);
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP)
udf_sb_free_bitmap(map->s_uspace.s_bitmap);
if (map->s_partition_type == UDF_SPARABLE_MAP15)
for (i = 0; i < 4; i++)
brelse(map->s_type_specific.s_sparing.s_spar_map[i]);
else if (map->s_partition_type == UDF_METADATA_MAP25) {
mdata = &map->s_type_specific.s_metadata;
iput(mdata->s_metadata_fe);
mdata->s_metadata_fe = NULL;
iput(mdata->s_mirror_fe);
mdata->s_mirror_fe = NULL;
iput(mdata->s_bitmap_fe);
mdata->s_bitmap_fe = NULL;
}
}
static void udf_sb_free_partitions(struct super_block *sb)
{
struct udf_sb_info *sbi = UDF_SB(sb);
int i;
if (!sbi->s_partmaps)
return;
for (i = 0; i < sbi->s_partitions; i++)
udf_free_partition(&sbi->s_partmaps[i]);
kfree(sbi->s_partmaps);
sbi->s_partmaps = NULL;
}
static int udf_show_options(struct seq_file *seq, struct dentry *root)
{
struct super_block *sb = root->d_sb;
struct udf_sb_info *sbi = UDF_SB(sb);
if (!UDF_QUERY_FLAG(sb, UDF_FLAG_STRICT))
seq_puts(seq, ",nostrict");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_BLOCKSIZE_SET))
seq_printf(seq, ",bs=%lu", sb->s_blocksize);
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNHIDE))
seq_puts(seq, ",unhide");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNDELETE))
seq_puts(seq, ",undelete");
if (!UDF_QUERY_FLAG(sb, UDF_FLAG_USE_AD_IN_ICB))
seq_puts(seq, ",noadinicb");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_USE_SHORT_AD))
seq_puts(seq, ",shortad");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_FORGET))
seq_puts(seq, ",uid=forget");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_FORGET))
seq_puts(seq, ",gid=forget");
if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_SET))
seq_printf(seq, ",uid=%u", from_kuid(&init_user_ns, sbi->s_uid));
if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_SET))
seq_printf(seq, ",gid=%u", from_kgid(&init_user_ns, sbi->s_gid));
if (sbi->s_umask != 0)
seq_printf(seq, ",umask=%ho", sbi->s_umask);
if (sbi->s_fmode != UDF_INVALID_MODE)
seq_printf(seq, ",mode=%ho", sbi->s_fmode);
if (sbi->s_dmode != UDF_INVALID_MODE)
seq_printf(seq, ",dmode=%ho", sbi->s_dmode);
if (UDF_QUERY_FLAG(sb, UDF_FLAG_SESSION_SET))
seq_printf(seq, ",session=%d", sbi->s_session);
if (UDF_QUERY_FLAG(sb, UDF_FLAG_LASTBLOCK_SET))
seq_printf(seq, ",lastblock=%u", sbi->s_last_block);
if (sbi->s_anchor != 0)
seq_printf(seq, ",anchor=%u", sbi->s_anchor);
if (sbi->s_nls_map)
seq_printf(seq, ",iocharset=%s", sbi->s_nls_map->charset);
else
seq_puts(seq, ",iocharset=utf8");
return 0;
}
/*
* udf_parse_param
*
* PURPOSE
* Parse mount options.
*
* DESCRIPTION
* The following mount options are supported:
*
* gid= Set the default group.
* umask= Set the default umask.
* mode= Set the default file permissions.
* dmode= Set the default directory permissions.
* uid= Set the default user.
* bs= Set the block size.
* unhide Show otherwise hidden files.
* undelete Show deleted files in lists.
* adinicb Embed data in the inode (default)
* noadinicb Don't embed data in the inode
* shortad Use short ad's
* longad Use long ad's (default)
* nostrict Unset strict conformance
* iocharset= Set the NLS character set
*
* The remaining are for debugging and disaster recovery:
*
* novrs Skip volume sequence recognition
*
* The following expect a offset from 0.
*
* session= Set the CDROM session (default= last session)
* anchor= Override standard anchor location. (default= 256)
* volume= Override the VolumeDesc location. (unused)
* partition= Override the PartitionDesc location. (unused)
* lastblock= Set the last block of the filesystem/
*
* The following expect a offset from the partition root.
*
* fileset= Override the fileset block location. (unused)
* rootdir= Override the root directory location. (unused)
* WARNING: overriding the rootdir to a non-directory may
* yield highly unpredictable results.
*
* PRE-CONDITIONS
* fc fs_context with pointer to mount options variable.
* param Pointer to fs_parameter being parsed.
*
* POST-CONDITIONS
* <return> 0 Mount options parsed okay.
* <return> errno Error parsing mount options.
*
* HISTORY
* July 1, 1997 - Andrew E. Mileski
* Written, tested, and released.
*/
enum {
Opt_novrs, Opt_nostrict, Opt_bs, Opt_unhide, Opt_undelete,
Opt_noadinicb, Opt_adinicb, Opt_shortad, Opt_longad,
Opt_gid, Opt_uid, Opt_umask, Opt_session, Opt_lastblock,
Opt_anchor, Opt_volume, Opt_partition, Opt_fileset,
Opt_rootdir, Opt_utf8, Opt_iocharset, Opt_err, Opt_fmode, Opt_dmode
};
static const struct fs_parameter_spec udf_param_spec[] = {
fsparam_flag ("novrs", Opt_novrs),
fsparam_flag ("nostrict", Opt_nostrict),
fsparam_u32 ("bs", Opt_bs),
fsparam_flag ("unhide", Opt_unhide),
fsparam_flag ("undelete", Opt_undelete),
fsparam_flag_no ("adinicb", Opt_adinicb),
fsparam_flag ("shortad", Opt_shortad),
fsparam_flag ("longad", Opt_longad),
fsparam_string ("gid", Opt_gid),
fsparam_string ("uid", Opt_uid),
fsparam_u32 ("umask", Opt_umask),
fsparam_u32 ("session", Opt_session),
fsparam_u32 ("lastblock", Opt_lastblock),
fsparam_u32 ("anchor", Opt_anchor),
fsparam_u32 ("volume", Opt_volume),
fsparam_u32 ("partition", Opt_partition),
fsparam_u32 ("fileset", Opt_fileset),
fsparam_u32 ("rootdir", Opt_rootdir),
fsparam_flag ("utf8", Opt_utf8),
fsparam_string ("iocharset", Opt_iocharset),
fsparam_u32 ("mode", Opt_fmode),
fsparam_u32 ("dmode", Opt_dmode),
{}
};
static int udf_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
unsigned int uv;
unsigned int n;
struct udf_options *uopt = fc->fs_private;
struct fs_parse_result result;
int token;
bool remount = (fc->purpose & FS_CONTEXT_FOR_RECONFIGURE);
token = fs_parse(fc, udf_param_spec, param, &result);
if (token < 0)
return token;
switch (token) {
case Opt_novrs:
uopt->flags |= (1 << UDF_FLAG_NOVRS);
break;
case Opt_bs:
n = result.uint_32;
if (n != 512 && n != 1024 && n != 2048 && n != 4096)
return -EINVAL;
uopt->blocksize = n;
uopt->flags |= (1 << UDF_FLAG_BLOCKSIZE_SET);
break;
case Opt_unhide:
uopt->flags |= (1 << UDF_FLAG_UNHIDE);
break;
case Opt_undelete:
uopt->flags |= (1 << UDF_FLAG_UNDELETE);
break;
case Opt_adinicb:
if (result.negated)
uopt->flags &= ~(1 << UDF_FLAG_USE_AD_IN_ICB);
else
uopt->flags |= (1 << UDF_FLAG_USE_AD_IN_ICB);
break;
case Opt_shortad:
uopt->flags |= (1 << UDF_FLAG_USE_SHORT_AD);
break;
case Opt_longad:
uopt->flags &= ~(1 << UDF_FLAG_USE_SHORT_AD);
break;
case Opt_gid:
if (kstrtoint(param->string, 10, &uv) == 0) {
kgid_t gid = make_kgid(current_user_ns(), uv);
if (!gid_valid(gid))
return -EINVAL;
uopt->gid = gid;
uopt->flags |= (1 << UDF_FLAG_GID_SET);
} else if (!strcmp(param->string, "forget")) {
uopt->flags |= (1 << UDF_FLAG_GID_FORGET);
} else if (!strcmp(param->string, "ignore")) {
/* this option is superseded by gid=<number> */
;
} else {
return -EINVAL;
}
break;
case Opt_uid:
if (kstrtoint(param->string, 10, &uv) == 0) {
kuid_t uid = make_kuid(current_user_ns(), uv);
if (!uid_valid(uid))
return -EINVAL;
uopt->uid = uid;
uopt->flags |= (1 << UDF_FLAG_UID_SET);
} else if (!strcmp(param->string, "forget")) {
uopt->flags |= (1 << UDF_FLAG_UID_FORGET);
} else if (!strcmp(param->string, "ignore")) {
/* this option is superseded by uid=<number> */
;
} else {
return -EINVAL;
}
break;
case Opt_umask:
uopt->umask = result.uint_32;
break;
case Opt_nostrict:
uopt->flags &= ~(1 << UDF_FLAG_STRICT);
break;
case Opt_session:
uopt->session = result.uint_32;
if (!remount)
uopt->flags |= (1 << UDF_FLAG_SESSION_SET);
break;
case Opt_lastblock:
uopt->lastblock = result.uint_32;
if (!remount)
uopt->flags |= (1 << UDF_FLAG_LASTBLOCK_SET);
break;
case Opt_anchor:
uopt->anchor = result.uint_32;
break;
case Opt_volume:
case Opt_partition:
case Opt_fileset:
case Opt_rootdir:
/* Ignored (never implemented properly) */
break;
case Opt_utf8:
if (!remount) {
unload_nls(uopt->nls_map);
uopt->nls_map = NULL;
}
break;
case Opt_iocharset:
if (!remount) {
unload_nls(uopt->nls_map);
uopt->nls_map = NULL;
}
/* When nls_map is not loaded then UTF-8 is used */
if (!remount && strcmp(param->string, "utf8") != 0) {
uopt->nls_map = load_nls(param->string);
if (!uopt->nls_map) {
errorf(fc, "iocharset %s not found",
param->string);
return -EINVAL;
}
}
break;
case Opt_fmode:
uopt->fmode = result.uint_32 & 0777;
break;
case Opt_dmode:
uopt->dmode = result.uint_32 & 0777;
break;
default:
return -EINVAL;
}
return 0;
}
static int udf_reconfigure(struct fs_context *fc)
{
struct udf_options *uopt = fc->fs_private;
struct super_block *sb = fc->root->d_sb;
struct udf_sb_info *sbi = UDF_SB(sb);
int readonly = fc->sb_flags & SB_RDONLY;
int error = 0;
if (!readonly && UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
return -EACCES;
sync_filesystem(sb);
write_lock(&sbi->s_cred_lock);
sbi->s_flags = uopt->flags;
sbi->s_uid = uopt->uid;
sbi->s_gid = uopt->gid;
sbi->s_umask = uopt->umask;
sbi->s_fmode = uopt->fmode;
sbi->s_dmode = uopt->dmode;
write_unlock(&sbi->s_cred_lock);
if (readonly == sb_rdonly(sb))
goto out_unlock;
if (readonly)
udf_close_lvid(sb);
else
udf_open_lvid(sb);
out_unlock:
return error;
}
/*
* Check VSD descriptor. Returns -1 in case we are at the end of volume
* recognition area, 0 if the descriptor is valid but non-interesting, 1 if
* we found one of NSR descriptors we are looking for.
*/
static int identify_vsd(const struct volStructDesc *vsd)
{
int ret = 0;
if (!memcmp(vsd->stdIdent, VSD_STD_ID_CD001, VSD_STD_ID_LEN)) {
switch (vsd->structType) {
case 0:
udf_debug("ISO9660 Boot Record found\n");
break;
case 1:
udf_debug("ISO9660 Primary Volume Descriptor found\n");
break;
case 2:
udf_debug("ISO9660 Supplementary Volume Descriptor found\n");
break;
case 3:
udf_debug("ISO9660 Volume Partition Descriptor found\n");
break;
case 255:
udf_debug("ISO9660 Volume Descriptor Set Terminator found\n");
break;
default:
udf_debug("ISO9660 VRS (%u) found\n", vsd->structType);
break;
}
} else if (!memcmp(vsd->stdIdent, VSD_STD_ID_BEA01, VSD_STD_ID_LEN))
; /* ret = 0 */
else if (!memcmp(vsd->stdIdent, VSD_STD_ID_NSR02, VSD_STD_ID_LEN))
ret = 1;
else if (!memcmp(vsd->stdIdent, VSD_STD_ID_NSR03, VSD_STD_ID_LEN))
ret = 1;
else if (!memcmp(vsd->stdIdent, VSD_STD_ID_BOOT2, VSD_STD_ID_LEN))
; /* ret = 0 */
else if (!memcmp(vsd->stdIdent, VSD_STD_ID_CDW02, VSD_STD_ID_LEN))
; /* ret = 0 */
else {
/* TEA01 or invalid id : end of volume recognition area */
ret = -1;
}
return ret;
}
/*
* Check Volume Structure Descriptors (ECMA 167 2/9.1)
* We also check any "CD-ROM Volume Descriptor Set" (ECMA 167 2/8.3.1)
* @return 1 if NSR02 or NSR03 found,
* -1 if first sector read error, 0 otherwise
*/
static int udf_check_vsd(struct super_block *sb)
{
struct volStructDesc *vsd = NULL;
loff_t sector = VSD_FIRST_SECTOR_OFFSET;
int sectorsize;
struct buffer_head *bh = NULL;
int nsr = 0;
struct udf_sb_info *sbi;
loff_t session_offset;
sbi = UDF_SB(sb);
if (sb->s_blocksize < sizeof(struct volStructDesc))
sectorsize = sizeof(struct volStructDesc);
else
sectorsize = sb->s_blocksize;
session_offset = (loff_t)sbi->s_session << sb->s_blocksize_bits;
sector += session_offset;
udf_debug("Starting at sector %u (%lu byte sectors)\n",
(unsigned int)(sector >> sb->s_blocksize_bits),
sb->s_blocksize);
/* Process the sequence (if applicable). The hard limit on the sector
* offset is arbitrary, hopefully large enough so that all valid UDF
* filesystems will be recognised. There is no mention of an upper
* bound to the size of the volume recognition area in the standard.
* The limit will prevent the code to read all the sectors of a
* specially crafted image (like a bluray disc full of CD001 sectors),
* potentially causing minutes or even hours of uninterruptible I/O
* activity. This actually happened with uninitialised SSD partitions
* (all 0xFF) before the check for the limit and all valid IDs were
* added */
for (; !nsr && sector < VSD_MAX_SECTOR_OFFSET; sector += sectorsize) {
/* Read a block */
bh = sb_bread(sb, sector >> sb->s_blocksize_bits);
if (!bh)
break;
vsd = (struct volStructDesc *)(bh->b_data +
(sector & (sb->s_blocksize - 1)));
nsr = identify_vsd(vsd);
/* Found NSR or end? */
if (nsr) {
brelse(bh);
break;
}
/*
* Special handling for improperly formatted VRS (e.g., Win10)
* where components are separated by 2048 bytes even though
* sectors are 4K
*/
if (sb->s_blocksize == 4096) {
nsr = identify_vsd(vsd + 1);
/* Ignore unknown IDs... */
if (nsr < 0)
nsr = 0;
}
brelse(bh);
}
if (nsr > 0)
return 1;
else if (!bh && sector - session_offset == VSD_FIRST_SECTOR_OFFSET)
return -1;
else
return 0;
}
static int udf_verify_domain_identifier(struct super_block *sb,
struct regid *ident, char *dname)
{
struct domainIdentSuffix *suffix;
if (memcmp(ident->ident, UDF_ID_COMPLIANT, strlen(UDF_ID_COMPLIANT))) {
udf_warn(sb, "Not OSTA UDF compliant %s descriptor.\n", dname);
goto force_ro;
}
if (ident->flags & ENTITYID_FLAGS_DIRTY) {
udf_warn(sb, "Possibly not OSTA UDF compliant %s descriptor.\n",
dname);
goto force_ro;
}
suffix = (struct domainIdentSuffix *)ident->identSuffix;
if ((suffix->domainFlags & DOMAIN_FLAGS_HARD_WRITE_PROTECT) ||
(suffix->domainFlags & DOMAIN_FLAGS_SOFT_WRITE_PROTECT)) {
if (!sb_rdonly(sb)) {
udf_warn(sb, "Descriptor for %s marked write protected."
" Forcing read only mount.\n", dname);
}
goto force_ro;
}
return 0;
force_ro:
if (!sb_rdonly(sb))
return -EACCES;
UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
return 0;
}
static int udf_load_fileset(struct super_block *sb, struct fileSetDesc *fset,
struct kernel_lb_addr *root)
{
int ret;
ret = udf_verify_domain_identifier(sb, &fset->domainIdent, "file set");
if (ret < 0)
return ret;
*root = lelb_to_cpu(fset->rootDirectoryICB.extLocation);
UDF_SB(sb)->s_serial_number = le16_to_cpu(fset->descTag.tagSerialNum);
udf_debug("Rootdir at block=%u, partition=%u\n",
root->logicalBlockNum, root->partitionReferenceNum);
return 0;
}
static int udf_find_fileset(struct super_block *sb,
struct kernel_lb_addr *fileset,
struct kernel_lb_addr *root)
{
struct buffer_head *bh;
uint16_t ident;
int ret;
if (fileset->logicalBlockNum == 0xFFFFFFFF &&
fileset->partitionReferenceNum == 0xFFFF)
return -EINVAL;
bh = udf_read_ptagged(sb, fileset, 0, &ident);
if (!bh)
return -EIO;
if (ident != TAG_IDENT_FSD) {
brelse(bh);
return -EINVAL;
}
udf_debug("Fileset at block=%u, partition=%u\n",
fileset->logicalBlockNum, fileset->partitionReferenceNum);
UDF_SB(sb)->s_partition = fileset->partitionReferenceNum;
ret = udf_load_fileset(sb, (struct fileSetDesc *)bh->b_data, root);
brelse(bh);
return ret;
}
/*
* Load primary Volume Descriptor Sequence
*
* Return <0 on error, 0 on success. -EAGAIN is special meaning next sequence
* should be tried.
*/
static int udf_load_pvoldesc(struct super_block *sb, sector_t block)
{
struct primaryVolDesc *pvoldesc;
uint8_t *outstr;
struct buffer_head *bh;
uint16_t ident;
int ret;
struct timestamp *ts;
outstr = kzalloc(128, GFP_KERNEL);
if (!outstr)
return -ENOMEM;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh) {
ret = -EAGAIN;
goto out2;
}
if (ident != TAG_IDENT_PVD) {
ret = -EIO;
goto out_bh;
}
pvoldesc = (struct primaryVolDesc *)bh->b_data;
udf_disk_stamp_to_time(&UDF_SB(sb)->s_record_time,
pvoldesc->recordingDateAndTime);
ts = &pvoldesc->recordingDateAndTime;
udf_debug("recording time %04u/%02u/%02u %02u:%02u (%x)\n",
le16_to_cpu(ts->year), ts->month, ts->day, ts->hour,
ts->minute, le16_to_cpu(ts->typeAndTimezone));
ret = udf_dstrCS0toChar(sb, outstr, 31, pvoldesc->volIdent, 32);
if (ret < 0) {
strscpy_pad(UDF_SB(sb)->s_volume_ident, "InvalidName");
pr_warn("incorrect volume identification, setting to "
"'InvalidName'\n");
} else {
strscpy_pad(UDF_SB(sb)->s_volume_ident, outstr);
}
udf_debug("volIdent[] = '%s'\n", UDF_SB(sb)->s_volume_ident);
ret = udf_dstrCS0toChar(sb, outstr, 127, pvoldesc->volSetIdent, 128);
if (ret < 0) {
ret = 0;
goto out_bh;
}
outstr[ret] = 0;
udf_debug("volSetIdent[] = '%s'\n", outstr);
ret = 0;
out_bh:
brelse(bh);
out2:
kfree(outstr);
return ret;
}
struct inode *udf_find_metadata_inode_efe(struct super_block *sb,
u32 meta_file_loc, u32 partition_ref)
{
struct kernel_lb_addr addr;
struct inode *metadata_fe;
addr.logicalBlockNum = meta_file_loc;
addr.partitionReferenceNum = partition_ref;
metadata_fe = udf_iget_special(sb, &addr);
if (IS_ERR(metadata_fe)) {
udf_warn(sb, "metadata inode efe not found\n");
return metadata_fe;
}
if (UDF_I(metadata_fe)->i_alloc_type != ICBTAG_FLAG_AD_SHORT) {
udf_warn(sb, "metadata inode efe does not have short allocation descriptors!\n");
iput(metadata_fe);
return ERR_PTR(-EIO);
}
return metadata_fe;
}
static int udf_load_metadata_files(struct super_block *sb, int partition,
int type1_index)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct udf_part_map *map;
struct udf_meta_data *mdata;
struct kernel_lb_addr addr;
struct inode *fe;
map = &sbi->s_partmaps[partition];
mdata = &map->s_type_specific.s_metadata;
mdata->s_phys_partition_ref = type1_index;
/* metadata address */
udf_debug("Metadata file location: block = %u part = %u\n",
mdata->s_meta_file_loc, mdata->s_phys_partition_ref);
fe = udf_find_metadata_inode_efe(sb, mdata->s_meta_file_loc,
mdata->s_phys_partition_ref);
if (IS_ERR(fe)) {
/* mirror file entry */
udf_debug("Mirror metadata file location: block = %u part = %u\n",
mdata->s_mirror_file_loc, mdata->s_phys_partition_ref);
fe = udf_find_metadata_inode_efe(sb, mdata->s_mirror_file_loc,
mdata->s_phys_partition_ref);
if (IS_ERR(fe)) {
udf_err(sb, "Both metadata and mirror metadata inode efe can not found\n");
return PTR_ERR(fe);
}
mdata->s_mirror_fe = fe;
} else
mdata->s_metadata_fe = fe;
/*
* bitmap file entry
* Note:
* Load only if bitmap file location differs from 0xFFFFFFFF (DCN-5102)
*/
if (mdata->s_bitmap_file_loc != 0xFFFFFFFF) {
addr.logicalBlockNum = mdata->s_bitmap_file_loc;
addr.partitionReferenceNum = mdata->s_phys_partition_ref;
udf_debug("Bitmap file location: block = %u part = %u\n",
addr.logicalBlockNum, addr.partitionReferenceNum);
fe = udf_iget_special(sb, &addr);
if (IS_ERR(fe)) {
if (sb_rdonly(sb))
udf_warn(sb, "bitmap inode efe not found but it's ok since the disc is mounted read-only\n");
else {
udf_err(sb, "bitmap inode efe not found and attempted read-write mount\n");
return PTR_ERR(fe);
}
} else
mdata->s_bitmap_fe = fe;
}
udf_debug("udf_load_metadata_files Ok\n");
return 0;
}
int udf_compute_nr_groups(struct super_block *sb, u32 partition)
{
struct udf_part_map *map = &UDF_SB(sb)->s_partmaps[partition];
return DIV_ROUND_UP(map->s_partition_len +
(sizeof(struct spaceBitmapDesc) << 3),
sb->s_blocksize * 8);
}
static struct udf_bitmap *udf_sb_alloc_bitmap(struct super_block *sb, u32 index)
{
struct udf_bitmap *bitmap;
int nr_groups = udf_compute_nr_groups(sb, index);
bitmap = kvzalloc_flex(*bitmap, s_block_bitmap, nr_groups);
if (!bitmap)
return NULL;
bitmap->s_nr_groups = nr_groups;
return bitmap;
}
static int check_partition_desc(struct super_block *sb,
struct partitionDesc *p,
struct udf_part_map *map)
{
bool umap, utable, fmap, ftable;
struct partitionHeaderDesc *phd;
switch (le32_to_cpu(p->accessType)) {
case PD_ACCESS_TYPE_READ_ONLY:
case PD_ACCESS_TYPE_WRITE_ONCE:
case PD_ACCESS_TYPE_NONE:
goto force_ro;
}
/* No Partition Header Descriptor? */
if (strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR02) &&
strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR03))
goto force_ro;
phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
utable = phd->unallocSpaceTable.extLength;
umap = phd->unallocSpaceBitmap.extLength;
ftable = phd->freedSpaceTable.extLength;
fmap = phd->freedSpaceBitmap.extLength;
/* No allocation info? */
if (!utable && !umap && !ftable && !fmap)
goto force_ro;
/* We don't support blocks that require erasing before overwrite */
if (ftable || fmap)
goto force_ro;
/* UDF 2.60: 2.3.3 - no mixing of tables & bitmaps, no VAT. */
if (utable && umap)
goto force_ro;
if (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
map->s_partition_type == UDF_VIRTUAL_MAP20 ||
map->s_partition_type == UDF_METADATA_MAP25)
goto force_ro;
return 0;
force_ro:
if (!sb_rdonly(sb))
return -EACCES;
UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
return 0;
}
static int udf_fill_partdesc_info(struct super_block *sb,
struct partitionDesc *p, int p_index)
{
struct udf_part_map *map;
struct udf_sb_info *sbi = UDF_SB(sb);
struct partitionHeaderDesc *phd;
u32 sum;
int err;
map = &sbi->s_partmaps[p_index];
map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */
map->s_partition_root = le32_to_cpu(p->partitionStartingLocation);
if (check_add_overflow(map->s_partition_root, map->s_partition_len,
&sum)) {
udf_err(sb, "Partition %d has invalid location %u + %u\n",
p_index, map->s_partition_root, map->s_partition_len);
return -EFSCORRUPTED;
}
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY))
map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY;
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE))
map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE;
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE))
map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE;
if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE))
map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE;
udf_debug("Partition (%d type %x) starts at physical %u, block length %u\n",
p_index, map->s_partition_type,
map->s_partition_root, map->s_partition_len);
err = check_partition_desc(sb, p, map);
if (err)
return err;
/*
* Skip loading allocation info it we cannot ever write to the fs.
* This is a correctness thing as we may have decided to force ro mount
* to avoid allocation info we don't support.
*/
if (UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
return 0;
phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
if (phd->unallocSpaceTable.extLength) {
struct kernel_lb_addr loc = {
.logicalBlockNum = le32_to_cpu(
phd->unallocSpaceTable.extPosition),
.partitionReferenceNum = p_index,
};
struct inode *inode;
inode = udf_iget_special(sb, &loc);
if (IS_ERR(inode)) {
udf_debug("cannot load unallocSpaceTable (part %d)\n",
p_index);
return PTR_ERR(inode);
}
map->s_uspace.s_table = inode;
map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE;
udf_debug("unallocSpaceTable (part %d) @ %llu\n",
p_index, map->s_uspace.s_table->i_ino);
}
if (phd->unallocSpaceBitmap.extLength) {
struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
if (!bitmap)
return -ENOMEM;
map->s_uspace.s_bitmap = bitmap;
bitmap->s_extPosition = le32_to_cpu(
phd->unallocSpaceBitmap.extPosition);
map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP;
/* Check whether math over bitmap won't overflow. */
if (check_add_overflow(map->s_partition_len,
sizeof(struct spaceBitmapDesc) << 3,
&sum)) {
udf_err(sb, "Partition %d is too long (%u)\n", p_index,
map->s_partition_len);
return -EFSCORRUPTED;
}
udf_debug("unallocSpaceBitmap (part %d) @ %u\n",
p_index, bitmap->s_extPosition);
}
return 0;
}
static void udf_find_vat_block(struct super_block *sb, int p_index,
int type1_index, sector_t start_block)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct udf_part_map *map = &sbi->s_partmaps[p_index];
sector_t vat_block;
struct kernel_lb_addr ino;
struct inode *inode;
/*
* VAT file entry is in the last recorded block. Some broken disks have
* it a few blocks before so try a bit harder...
*/
ino.partitionReferenceNum = type1_index;
for (vat_block = start_block;
vat_block >= map->s_partition_root &&
vat_block >= start_block - 3; vat_block--) {
ino.logicalBlockNum = vat_block - map->s_partition_root;
inode = udf_iget_special(sb, &ino);
if (!IS_ERR(inode)) {
sbi->s_vat_inode = inode;
break;
}
}
}
static int udf_load_vat(struct super_block *sb, int p_index, int type1_index)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct udf_part_map *map = &sbi->s_partmaps[p_index];
struct buffer_head *bh = NULL;
struct udf_inode_info *vati;
struct virtualAllocationTable20 *vat20;
sector_t blocks = sb_bdev_nr_blocks(sb);
udf_find_vat_block(sb, p_index, type1_index, sbi->s_last_block);
if (!sbi->s_vat_inode &&
sbi->s_last_block != blocks - 1) {
pr_notice("Failed to read VAT inode from the last recorded block (%lu), retrying with the last block of the device (%lu).\n",
(unsigned long)sbi->s_last_block,
(unsigned long)blocks - 1);
udf_find_vat_block(sb, p_index, type1_index, blocks - 1);
}
if (!sbi->s_vat_inode)
return -EIO;
if (map->s_partition_type == UDF_VIRTUAL_MAP15) {
map->s_type_specific.s_virtual.s_start_offset = 0;
map->s_type_specific.s_virtual.s_num_entries =
(sbi->s_vat_inode->i_size - 36) >> 2;
} else if (map->s_partition_type == UDF_VIRTUAL_MAP20) {
vati = UDF_I(sbi->s_vat_inode);
if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
int err = 0;
bh = udf_bread(sbi->s_vat_inode, 0, 0, &err);
if (!bh) {
if (!err)
err = -EFSCORRUPTED;
return err;
}
vat20 = (struct virtualAllocationTable20 *)bh->b_data;
} else {
vat20 = (struct virtualAllocationTable20 *)
vati->i_data;
}
map->s_type_specific.s_virtual.s_start_offset =
le16_to_cpu(vat20->lengthHeader);
map->s_type_specific.s_virtual.s_num_entries =
(sbi->s_vat_inode->i_size -
map->s_type_specific.s_virtual.
s_start_offset) >> 2;
brelse(bh);
}
return 0;
}
/*
* Load partition descriptor block
*
* Returns <0 on error, 0 on success, -EAGAIN is special - try next descriptor
* sequence.
*/
static int udf_load_partdesc(struct super_block *sb, sector_t block)
{
struct buffer_head *bh;
struct partitionDesc *p;
struct udf_part_map *map;
struct udf_sb_info *sbi = UDF_SB(sb);
int i, type1_idx;
uint16_t partitionNumber;
uint16_t ident;
int ret;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return -EAGAIN;
if (ident != TAG_IDENT_PD) {
ret = 0;
goto out_bh;
}
p = (struct partitionDesc *)bh->b_data;
partitionNumber = le16_to_cpu(p->partitionNumber);
/* First scan for TYPE1 and SPARABLE partitions */
for (i = 0; i < sbi->s_partitions; i++) {
map = &sbi->s_partmaps[i];
udf_debug("Searching map: (%u == %u)\n",
map->s_partition_num, partitionNumber);
if (map->s_partition_num == partitionNumber &&
(map->s_partition_type == UDF_TYPE1_MAP15 ||
map->s_partition_type == UDF_SPARABLE_MAP15))
break;
}
if (i >= sbi->s_partitions) {
udf_debug("Partition (%u) not found in partition map\n",
partitionNumber);
ret = 0;
goto out_bh;
}
ret = udf_fill_partdesc_info(sb, p, i);
if (ret < 0)
goto out_bh;
/*
* Now rescan for VIRTUAL or METADATA partitions when SPARABLE and
* PHYSICAL partitions are already set up
*/
type1_idx = i;
map = NULL; /* supress 'maybe used uninitialized' warning */
for (i = 0; i < sbi->s_partitions; i++) {
map = &sbi->s_partmaps[i];
if (map->s_partition_num == partitionNumber &&
(map->s_partition_type == UDF_VIRTUAL_MAP15 ||
map->s_partition_type == UDF_VIRTUAL_MAP20 ||
map->s_partition_type == UDF_METADATA_MAP25))
break;
}
if (i >= sbi->s_partitions) {
ret = 0;
goto out_bh;
}
ret = udf_fill_partdesc_info(sb, p, i);
if (ret < 0)
goto out_bh;
if (map->s_partition_type == UDF_METADATA_MAP25) {
ret = udf_load_metadata_files(sb, i, type1_idx);
if (ret < 0) {
udf_err(sb, "error loading MetaData partition map %d\n",
i);
goto out_bh;
}
} else {
/*
* If we have a partition with virtual map, we don't handle
* writing to it (we overwrite blocks instead of relocating
* them).
*/
if (!sb_rdonly(sb)) {
ret = -EACCES;
goto out_bh;
}
UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
ret = udf_load_vat(sb, i, type1_idx);
if (ret < 0)
goto out_bh;
}
ret = 0;
out_bh:
/* In case loading failed, we handle cleanup in udf_fill_super */
brelse(bh);
return ret;
}
static int udf_load_sparable_map(struct super_block *sb,
struct udf_part_map *map,
struct sparablePartitionMap *spm)
{
uint32_t loc;
uint16_t ident;
struct sparingTable *st;
struct udf_sparing_data *sdata = &map->s_type_specific.s_sparing;
int i;
struct buffer_head *bh;
map->s_partition_type = UDF_SPARABLE_MAP15;
sdata->s_packet_len = le16_to_cpu(spm->packetLength);
if (!is_power_of_2(sdata->s_packet_len)) {
udf_err(sb, "error loading logical volume descriptor: "
"Invalid packet length %u\n",
(unsigned)sdata->s_packet_len);
return -EIO;
}
if (spm->numSparingTables > 4) {
udf_err(sb, "error loading logical volume descriptor: "
"Too many sparing tables (%d)\n",
(int)spm->numSparingTables);
return -EIO;
}
if (le32_to_cpu(spm->sizeSparingTable) > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Too big sparing table size (%u)\n",
le32_to_cpu(spm->sizeSparingTable));
return -EIO;
}
for (i = 0; i < spm->numSparingTables; i++) {
loc = le32_to_cpu(spm->locSparingTable[i]);
bh = udf_read_tagged(sb, loc, loc, &ident);
if (!bh)
continue;
st = (struct sparingTable *)bh->b_data;
if (ident != 0 ||
strncmp(st->sparingIdent.ident, UDF_ID_SPARING,
strlen(UDF_ID_SPARING)) ||
sizeof(*st) + le16_to_cpu(st->reallocationTableLen) >
sb->s_blocksize) {
brelse(bh);
continue;
}
sdata->s_spar_map[i] = bh;
}
map->s_partition_func = udf_get_pblock_spar15;
return 0;
}
static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len, part_map_count;
int ret;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return -EAGAIN;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (table_len > sb->s_blocksize - sizeof(*lvd)) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
ret = -EIO;
goto out_bh;
}
ret = udf_verify_domain_identifier(sb, &lvd->domainIdent,
"logical volume");
if (ret)
goto out_bh;
part_map_count = le32_to_cpu(lvd->numPartitionMaps);
if (part_map_count > table_len / sizeof(struct genericPartitionMap1)) {
udf_err(sb, "error loading logical volume descriptor: "
"Too many partition maps (%u > %u)\n", part_map_count,
table_len / (unsigned)sizeof(struct genericPartitionMap1));
ret = -EIO;
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, part_map_count);
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
ret = udf_load_sparable_map(sb, map,
(struct sparablePartitionMap *)gpm);
if (ret < 0)
goto out_bh;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %u id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%u\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%u\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%u\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%u\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%u\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %u\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%u) type %u on volume %u\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%u, partition=%u\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
ret = 0;
if (!sbi->s_lvid_bh) {
/* We can't generate unique IDs without a valid LVID */
if (sb_rdonly(sb)) {
UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
} else {
udf_warn(sb, "Damaged or missing LVID, forcing "
"readonly mount\n");
ret = -EACCES;
}
}
out_bh:
brelse(bh);
return ret;
}
static bool udf_lvid_valid(struct super_block *sb,
struct logicalVolIntegrityDesc *lvid)
{
u32 parts, impuselen;
parts = le32_to_cpu(lvid->numOfPartitions);
impuselen = le32_to_cpu(lvid->lengthOfImpUse);
if (parts >= sb->s_blocksize || impuselen >= sb->s_blocksize ||
sizeof(struct logicalVolIntegrityDesc) + impuselen +
2 * parts * sizeof(u32) > sb->s_blocksize)
return false;
return true;
}
/*
* Find the prevailing Logical Volume Integrity Descriptor.
*/
static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_ad loc)
{
struct buffer_head *bh, *final_bh;
uint16_t ident;
struct udf_sb_info *sbi = UDF_SB(sb);
struct logicalVolIntegrityDesc *lvid;
int indirections = 0;
while (++indirections <= UDF_MAX_LVID_NESTING) {
final_bh = NULL;
while (loc.extLength > 0 &&
(bh = udf_read_tagged(sb, loc.extLocation,
loc.extLocation, &ident))) {
if (ident != TAG_IDENT_LVID) {
brelse(bh);
break;
}
brelse(final_bh);
final_bh = bh;
loc.extLength -= sb->s_blocksize;
loc.extLocation++;
}
if (!final_bh)
return;
lvid = (struct logicalVolIntegrityDesc *)final_bh->b_data;
if (udf_lvid_valid(sb, lvid)) {
brelse(sbi->s_lvid_bh);
sbi->s_lvid_bh = final_bh;
} else {
udf_warn(sb, "Corrupted LVID (parts=%u, impuselen=%u), "
"ignoring.\n",
le32_to_cpu(lvid->numOfPartitions),
le32_to_cpu(lvid->lengthOfImpUse));
}
if (lvid->nextIntegrityExt.extLength == 0)
return;
loc = leea_to_cpu(lvid->nextIntegrityExt);
}
udf_warn(sb, "Too many LVID indirections (max %u), ignoring.\n",
UDF_MAX_LVID_NESTING);
brelse(sbi->s_lvid_bh);
sbi->s_lvid_bh = NULL;
}
/*
* Step for reallocation of table of partition descriptor sequence numbers.
* Must be power of 2.
*/
#define PART_DESC_ALLOC_STEP 32
struct part_desc_seq_scan_data {
struct udf_vds_record rec;
u32 partnum;
};
struct desc_seq_scan_data {
struct udf_vds_record vds[VDS_POS_LENGTH];
unsigned int size_part_descs;
unsigned int num_part_descs;
struct part_desc_seq_scan_data *part_descs_loc;
};
static struct udf_vds_record *handle_partition_descriptor(
struct buffer_head *bh,
struct desc_seq_scan_data *data)
{
struct partitionDesc *desc = (struct partitionDesc *)bh->b_data;
int partnum;
int i;
partnum = le16_to_cpu(desc->partitionNumber);
for (i = 0; i < data->num_part_descs; i++)
if (partnum == data->part_descs_loc[i].partnum)
return &(data->part_descs_loc[i].rec);
if (data->num_part_descs >= data->size_part_descs) {
struct part_desc_seq_scan_data *new_loc;
unsigned int new_size;
new_size = data->num_part_descs + PART_DESC_ALLOC_STEP;
new_loc = kzalloc_objs(*new_loc, new_size);
if (!new_loc)
return ERR_PTR(-ENOMEM);
memcpy(new_loc, data->part_descs_loc,
data->size_part_descs * sizeof(*new_loc));
kfree(data->part_descs_loc);
data->part_descs_loc = new_loc;
data->size_part_descs = new_size;
}
data->part_descs_loc[data->num_part_descs].partnum = partnum;
return &(data->part_descs_loc[data->num_part_descs++].rec);
}
static struct udf_vds_record *get_volume_descriptor_record(uint16_t ident,
struct buffer_head *bh, struct desc_seq_scan_data *data)
{
switch (ident) {
case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
return &(data->vds[VDS_POS_PRIMARY_VOL_DESC]);
case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
return &(data->vds[VDS_POS_IMP_USE_VOL_DESC]);
case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
return &(data->vds[VDS_POS_LOGICAL_VOL_DESC]);
case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
return &(data->vds[VDS_POS_UNALLOC_SPACE_DESC]);
case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
return handle_partition_descriptor(bh, data);
}
return NULL;
}
/*
* Process a main/reserve volume descriptor sequence.
* @block First block of first extent of the sequence.
* @lastblock Lastblock of first extent of the sequence.
* @fileset There we store extent containing root fileset
*
* Returns <0 on error, 0 on success. -EAGAIN is special - try next descriptor
* sequence
*/
static noinline int udf_process_sequence(
struct super_block *sb,
sector_t block, sector_t lastblock,
struct kernel_lb_addr *fileset)
{
struct buffer_head *bh = NULL;
struct udf_vds_record *curr;
struct generic_desc *gd;
struct volDescPtr *vdp;
bool done = false;
uint32_t vdsn;
uint16_t ident;
int ret;
unsigned int indirections = 0;
struct desc_seq_scan_data data;
unsigned int i;
memset(data.vds, 0, sizeof(struct udf_vds_record) * VDS_POS_LENGTH);
data.size_part_descs = PART_DESC_ALLOC_STEP;
data.num_part_descs = 0;
data.part_descs_loc = kzalloc_objs(*data.part_descs_loc,
data.size_part_descs);
if (!data.part_descs_loc)
return -ENOMEM;
/*
* Read the main descriptor sequence and find which descriptors
* are in it.
*/
for (; (!done && block <= lastblock); block++) {
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
break;
/* Process each descriptor (ISO 13346 3/8.3-8.4) */
gd = (struct generic_desc *)bh->b_data;
vdsn = le32_to_cpu(gd->volDescSeqNum);
switch (ident) {
case TAG_IDENT_VDP: /* ISO 13346 3/10.3 */
if (++indirections > UDF_MAX_TD_NESTING) {
udf_err(sb, "too many Volume Descriptor "
"Pointers (max %u supported)\n",
UDF_MAX_TD_NESTING);
brelse(bh);
ret = -EIO;
goto out;
}
vdp = (struct volDescPtr *)bh->b_data;
block = le32_to_cpu(vdp->nextVolDescSeqExt.extLocation);
lastblock = le32_to_cpu(
vdp->nextVolDescSeqExt.extLength) >>
sb->s_blocksize_bits;
lastblock += block - 1;
/* For loop is going to increment 'block' again */
block--;
break;
case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
curr = get_volume_descriptor_record(ident, bh, &data);
if (IS_ERR(curr)) {
brelse(bh);
ret = PTR_ERR(curr);
goto out;
}
/* Descriptor we don't care about? */
if (!curr)
break;
if (vdsn >= curr->volDescSeqNum) {
curr->volDescSeqNum = vdsn;
curr->block = block;
}
break;
case TAG_IDENT_TD: /* ISO 13346 3/10.9 */
done = true;
break;
}
brelse(bh);
}
/*
* Now read interesting descriptors again and process them
* in a suitable order
*/
if (!data.vds[VDS_POS_PRIMARY_VOL_DESC].block) {
udf_err(sb, "Primary Volume Descriptor not found!\n");
ret = -EAGAIN;
goto out;
}
ret = udf_load_pvoldesc(sb, data.vds[VDS_POS_PRIMARY_VOL_DESC].block);
if (ret < 0)
goto out;
if (data.vds[VDS_POS_LOGICAL_VOL_DESC].block) {
ret = udf_load_logicalvol(sb,
data.vds[VDS_POS_LOGICAL_VOL_DESC].block,
fileset);
if (ret < 0)
goto out;
}
/* Now handle prevailing Partition Descriptors */
for (i = 0; i < data.num_part_descs; i++) {
ret = udf_load_partdesc(sb, data.part_descs_loc[i].rec.block);
if (ret < 0)
goto out;
}
ret = 0;
out:
kfree(data.part_descs_loc);
return ret;
}
/*
* Load Volume Descriptor Sequence described by anchor in bh
*
* Returns <0 on error, 0 on success
*/
static int udf_load_sequence(struct super_block *sb, struct buffer_head *bh,
struct kernel_lb_addr *fileset)
{
struct anchorVolDescPtr *anchor;
sector_t main_s, main_e, reserve_s, reserve_e;
int ret;
anchor = (struct anchorVolDescPtr *)bh->b_data;
/* Locate the main sequence */
main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation);
main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength);
main_e = main_e >> sb->s_blocksize_bits;
main_e += main_s - 1;
/* Locate the reserve sequence */
reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation);
reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength);
reserve_e = reserve_e >> sb->s_blocksize_bits;
reserve_e += reserve_s - 1;
/* Process the main & reserve sequences */
/* responsible for finding the PartitionDesc(s) */
ret = udf_process_sequence(sb, main_s, main_e, fileset);
if (ret != -EAGAIN)
return ret;
udf_sb_free_partitions(sb);
ret = udf_process_sequence(sb, reserve_s, reserve_e, fileset);
if (ret < 0) {
udf_sb_free_partitions(sb);
/* No sequence was OK, return -EIO */
if (ret == -EAGAIN)
ret = -EIO;
}
return ret;
}
/*
* Check whether there is an anchor block in the given block and
* load Volume Descriptor Sequence if so.
*
* Returns <0 on error, 0 on success, -EAGAIN is special - try next anchor
* block
*/
static int udf_check_anchor_block(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct buffer_head *bh;
uint16_t ident;
int ret;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return -EAGAIN;
if (ident != TAG_IDENT_AVDP) {
brelse(bh);
return -EAGAIN;
}
ret = udf_load_sequence(sb, bh, fileset);
brelse(bh);
return ret;
}
/*
* Search for an anchor volume descriptor pointer.
*
* Returns < 0 on error, 0 on success. -EAGAIN is special - try next set
* of anchors.
*/
static int udf_scan_anchors(struct super_block *sb, udf_pblk_t *lastblock,
struct kernel_lb_addr *fileset)
{
udf_pblk_t last[6];
int i;
struct udf_sb_info *sbi = UDF_SB(sb);
int last_count = 0;
int ret;
/* First try user provided anchor */
if (sbi->s_anchor) {
ret = udf_check_anchor_block(sb, sbi->s_anchor, fileset);
if (ret != -EAGAIN)
return ret;
}
/*
* according to spec, anchor is in either:
* block 256
* lastblock-256
* lastblock
* however, if the disc isn't closed, it could be 512.
*/
ret = udf_check_anchor_block(sb, sbi->s_session + 256, fileset);
if (ret != -EAGAIN)
return ret;
/*
* The trouble is which block is the last one. Drives often misreport
* this so we try various possibilities.
*/
last[last_count++] = *lastblock;
if (*lastblock >= 1)
last[last_count++] = *lastblock - 1;
last[last_count++] = *lastblock + 1;
if (*lastblock >= 2)
last[last_count++] = *lastblock - 2;
if (*lastblock >= 150)
last[last_count++] = *lastblock - 150;
if (*lastblock >= 152)
last[last_count++] = *lastblock - 152;
for (i = 0; i < last_count; i++) {
if (last[i] >= sb_bdev_nr_blocks(sb))
continue;
ret = udf_check_anchor_block(sb, last[i], fileset);
if (ret != -EAGAIN) {
if (!ret)
*lastblock = last[i];
return ret;
}
if (last[i] < 256)
continue;
ret = udf_check_anchor_block(sb, last[i] - 256, fileset);
if (ret != -EAGAIN) {
if (!ret)
*lastblock = last[i];
return ret;
}
}
/* Finally try block 512 in case media is open */
return udf_check_anchor_block(sb, sbi->s_session + 512, fileset);
}
/*
* Check Volume Structure Descriptor, find Anchor block and load Volume
* Descriptor Sequence.
*
* Returns < 0 on error, 0 on success. -EAGAIN is special meaning anchor
* block was not found.
*/
static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt,
int silent, struct kernel_lb_addr *fileset)
{
struct udf_sb_info *sbi = UDF_SB(sb);
int nsr = 0;
int ret;
if (!sb_set_blocksize(sb, uopt->blocksize)) {
if (!silent)
udf_warn(sb, "Bad block size\n");
return -EINVAL;
}
sbi->s_last_block = uopt->lastblock;
if (!UDF_QUERY_FLAG(sb, UDF_FLAG_NOVRS)) {
/* Check that it is NSR02 compliant */
nsr = udf_check_vsd(sb);
if (!nsr) {
if (!silent)
udf_warn(sb, "No VRS found\n");
return -EINVAL;
}
if (nsr == -1)
udf_debug("Failed to read sector at offset %d. "
"Assuming open disc. Skipping validity "
"check\n", VSD_FIRST_SECTOR_OFFSET);
if (!sbi->s_last_block)
sbi->s_last_block = udf_get_last_block(sb);
} else {
udf_debug("Validity check skipped because of novrs option\n");
}
/* Look for anchor block and load Volume Descriptor Sequence */
sbi->s_anchor = uopt->anchor;
ret = udf_scan_anchors(sb, &sbi->s_last_block, fileset);
if (ret < 0) {
if (!silent && ret == -EAGAIN)
udf_warn(sb, "No anchor found\n");
return ret;
}
return 0;
}
static void udf_finalize_lvid(struct logicalVolIntegrityDesc *lvid)
{
struct timespec64 ts;
ktime_get_real_ts64(&ts);
udf_time_to_disk_stamp(&lvid->recordingDateAndTime, ts);
lvid->descTag.descCRC = cpu_to_le16(
crc_itu_t(0, (char *)lvid + sizeof(struct tag),
le16_to_cpu(lvid->descTag.descCRCLength)));
lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
}
static void udf_open_lvid(struct super_block *sb)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct buffer_head *bh = sbi->s_lvid_bh;
struct logicalVolIntegrityDesc *lvid;
struct logicalVolIntegrityDescImpUse *lvidiu;
if (!bh)
return;
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
lvidiu = udf_sb_lvidiu(sb);
if (!lvidiu)
return;
mutex_lock(&sbi->s_alloc_mutex);
lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
if (le32_to_cpu(lvid->integrityType) == LVID_INTEGRITY_TYPE_CLOSE)
lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN);
else
UDF_SET_FLAG(sb, UDF_FLAG_INCONSISTENT);
udf_finalize_lvid(lvid);
mark_buffer_dirty(bh);
sbi->s_lvid_dirty = 0;
mutex_unlock(&sbi->s_alloc_mutex);
/* Make opening of filesystem visible on the media immediately */
sync_dirty_buffer(bh);
}
static void udf_close_lvid(struct super_block *sb)
{
struct udf_sb_info *sbi = UDF_SB(sb);
struct buffer_head *bh = sbi->s_lvid_bh;
struct logicalVolIntegrityDesc *lvid;
struct logicalVolIntegrityDescImpUse *lvidiu;
if (!bh)
return;
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
lvidiu = udf_sb_lvidiu(sb);
if (!lvidiu)
return;
mutex_lock(&sbi->s_alloc_mutex);
lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev))
lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION);
if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev))
lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev);
if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev))
lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev);
if (!UDF_QUERY_FLAG(sb, UDF_FLAG_INCONSISTENT))
lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE);
/*
* We set buffer uptodate unconditionally here to avoid spurious
* warnings from mark_buffer_dirty() when previous EIO has marked
* the buffer as !uptodate
*/
set_buffer_uptodate(bh);
udf_finalize_lvid(lvid);
mark_buffer_dirty(bh);
sbi->s_lvid_dirty = 0;
mutex_unlock(&sbi->s_alloc_mutex);
/* Make closing of filesystem visible on the media immediately */
sync_dirty_buffer(bh);
}
u64 lvid_get_unique_id(struct super_block *sb)
{
struct buffer_head *bh;
struct udf_sb_info *sbi = UDF_SB(sb);
struct logicalVolIntegrityDesc *lvid;
struct logicalVolHeaderDesc *lvhd;
u64 uniqueID;
u64 ret;
bh = sbi->s_lvid_bh;
if (!bh)
return 0;
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse;
mutex_lock(&sbi->s_alloc_mutex);
ret = uniqueID = le64_to_cpu(lvhd->uniqueID);
if (!(++uniqueID & 0xFFFFFFFF))
uniqueID += 16;
lvhd->uniqueID = cpu_to_le64(uniqueID);
udf_updated_lvid(sb);
mutex_unlock(&sbi->s_alloc_mutex);
return ret;
}
static int udf_fill_super(struct super_block *sb, struct fs_context *fc)
{
int ret = -EINVAL;
struct inode *inode = NULL;
struct udf_options *uopt = fc->fs_private;
struct kernel_lb_addr rootdir, fileset;
struct udf_sb_info *sbi;
bool lvid_open = false;
int silent = fc->sb_flags & SB_SILENT;
sbi = kzalloc_obj(*sbi);
if (!sbi)
return -ENOMEM;
sb->s_fs_info = sbi;
mutex_init(&sbi->s_alloc_mutex);
fileset.logicalBlockNum = 0xFFFFFFFF;
fileset.partitionReferenceNum = 0xFFFF;
sbi->s_flags = uopt->flags;
sbi->s_uid = uopt->uid;
sbi->s_gid = uopt->gid;
sbi->s_umask = uopt->umask;
sbi->s_fmode = uopt->fmode;
sbi->s_dmode = uopt->dmode;
sbi->s_nls_map = uopt->nls_map;
uopt->nls_map = NULL;
rwlock_init(&sbi->s_cred_lock);
if (uopt->session == 0xFFFFFFFF)
sbi->s_session = udf_get_last_session(sb);
else
sbi->s_session = uopt->session;
udf_debug("Multi-session=%d\n", sbi->s_session);
/* Fill in the rest of the superblock */
sb->s_op = &udf_sb_ops;
sb->s_export_op = &udf_export_ops;
sb->s_magic = UDF_SUPER_MAGIC;
sb->s_time_gran = 1000;
if (uopt->flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) {
ret = udf_load_vrs(sb, uopt, silent, &fileset);
} else {
uopt->blocksize = bdev_logical_block_size(sb->s_bdev);
while (uopt->blocksize <= 4096) {
ret = udf_load_vrs(sb, uopt, silent, &fileset);
if (ret < 0) {
if (!silent && ret != -EACCES) {
pr_notice("Scanning with blocksize %u failed\n",
uopt->blocksize);
}
brelse(sbi->s_lvid_bh);
sbi->s_lvid_bh = NULL;
/*
* EACCES is special - we want to propagate to
* upper layers that we cannot handle RW mount.
*/
if (ret == -EACCES)
break;
} else
break;
uopt->blocksize <<= 1;
}
}
if (ret < 0) {
if (ret == -EAGAIN) {
udf_warn(sb, "No partition found (1)\n");
ret = -EINVAL;
}
goto error_out;
}
udf_debug("Lastblock=%u\n", sbi->s_last_block);
if (sbi->s_lvid_bh) {
struct logicalVolIntegrityDescImpUse *lvidiu =
udf_sb_lvidiu(sb);
uint16_t minUDFReadRev;
uint16_t minUDFWriteRev;
if (!lvidiu) {
ret = -EINVAL;
goto error_out;
}
minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev);
minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev);
if (minUDFReadRev > UDF_MAX_READ_VERSION) {
udf_err(sb, "minUDFReadRev=%x (max is %x)\n",
minUDFReadRev,
UDF_MAX_READ_VERSION);
ret = -EINVAL;
goto error_out;
} else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION) {
if (!sb_rdonly(sb)) {
ret = -EACCES;
goto error_out;
}
UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
}
sbi->s_udfrev = minUDFWriteRev;
if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE)
UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE);
if (minUDFReadRev >= UDF_VERS_USE_STREAMS)
UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS);
}
if (!sbi->s_partitions) {
udf_warn(sb, "No partition found (2)\n");
ret = -EINVAL;
goto error_out;
}
if (sbi->s_partmaps[sbi->s_partition].s_partition_flags &
UDF_PART_FLAG_READ_ONLY) {
if (!sb_rdonly(sb)) {
ret = -EACCES;
goto error_out;
}
UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
}
ret = udf_find_fileset(sb, &fileset, &rootdir);
if (ret < 0) {
udf_warn(sb, "No fileset found\n");
goto error_out;
}
if (!silent) {
struct timestamp ts;
udf_time_to_disk_stamp(&ts, sbi->s_record_time);
udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n",
sbi->s_volume_ident,
le16_to_cpu(ts.year), ts.month, ts.day,
ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone));
}
if (!sb_rdonly(sb)) {
udf_open_lvid(sb);
lvid_open = true;
}
/* Assign the root inode */
/* assign inodes by physical block number */
/* perhaps it's not extensible enough, but for now ... */
inode = udf_iget(sb, &rootdir);
if (IS_ERR(inode)) {
udf_err(sb, "Error in udf_iget, block=%u, partition=%u\n",
rootdir.logicalBlockNum, rootdir.partitionReferenceNum);
ret = PTR_ERR(inode);
goto error_out;
}
/* Allocate a dentry for the root inode */
sb->s_root = d_make_root(inode);
if (!sb->s_root) {
udf_err(sb, "Couldn't allocate root dentry\n");
ret = -ENOMEM;
goto error_out;
}
sb->s_maxbytes = UDF_MAX_FILESIZE;
sb->s_max_links = UDF_MAX_LINKS;
return 0;
error_out:
iput(sbi->s_vat_inode);
unload_nls(uopt->nls_map);
if (lvid_open)
udf_close_lvid(sb);
brelse(sbi->s_lvid_bh);
udf_sb_free_partitions(sb);
kfree(sbi);
sb->s_fs_info = NULL;
return ret;
}
void _udf_err(struct super_block *sb, const char *function,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf);
va_end(args);
}
void _udf_warn(struct super_block *sb, const char *function,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf);
va_end(args);
}
static void udf_put_super(struct super_block *sb)
{
struct udf_sb_info *sbi;
sbi = UDF_SB(sb);
iput(sbi->s_vat_inode);
unload_nls(sbi->s_nls_map);
if (!sb_rdonly(sb))
udf_close_lvid(sb);
brelse(sbi->s_lvid_bh);
udf_sb_free_partitions(sb);
mutex_destroy(&sbi->s_alloc_mutex);
kfree(sb->s_fs_info);
sb->s_fs_info = NULL;
}
static int udf_sync_fs(struct super_block *sb, int wait)
{
struct udf_sb_info *sbi = UDF_SB(sb);
mutex_lock(&sbi->s_alloc_mutex);
if (sbi->s_lvid_dirty) {
struct buffer_head *bh = sbi->s_lvid_bh;
struct logicalVolIntegrityDesc *lvid;
lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
udf_finalize_lvid(lvid);
/*
* Blockdevice will be synced later so we don't have to submit
* the buffer for IO
*/
mark_buffer_dirty(bh);
sbi->s_lvid_dirty = 0;
}
mutex_unlock(&sbi->s_alloc_mutex);
return 0;
}
static int udf_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct udf_sb_info *sbi = UDF_SB(sb);
struct logicalVolIntegrityDescImpUse *lvidiu;
u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
lvidiu = udf_sb_lvidiu(sb);
buf->f_type = UDF_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len;
buf->f_bfree = udf_count_free(sb);
buf->f_bavail = buf->f_bfree;
/*
* Let's pretend each free block is also a free 'inode' since UDF does
* not have separate preallocated table of inodes.
*/
buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) +
le32_to_cpu(lvidiu->numDirs)) : 0)
+ buf->f_bfree;
buf->f_ffree = buf->f_bfree;
buf->f_namelen = UDF_NAME_LEN;
buf->f_fsid = u64_to_fsid(id);
return 0;
}
static unsigned int udf_count_free_bitmap(struct super_block *sb,
struct udf_bitmap *bitmap)
{
struct buffer_head *bh = NULL;
unsigned int accum = 0;
int index;
udf_pblk_t block = 0, newblock;
struct kernel_lb_addr loc;
uint32_t bytes;
uint8_t *ptr;
uint16_t ident;
struct spaceBitmapDesc *bm;
loc.logicalBlockNum = bitmap->s_extPosition;
loc.partitionReferenceNum = UDF_SB(sb)->s_partition;
bh = udf_read_ptagged(sb, &loc, 0, &ident);
if (!bh) {
udf_err(sb, "udf_count_free failed\n");
goto out;
} else if (ident != TAG_IDENT_SBD) {
brelse(bh);
udf_err(sb, "udf_count_free failed\n");
goto out;
}
bm = (struct spaceBitmapDesc *)bh->b_data;
bytes = le32_to_cpu(bm->numOfBytes);
index = sizeof(struct spaceBitmapDesc); /* offset in first block only */
ptr = (uint8_t *)bh->b_data;
while (bytes > 0) {
u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index);
accum += bitmap_weight((const unsigned long *)(ptr + index),
cur_bytes * 8);
bytes -= cur_bytes;
if (bytes) {
brelse(bh);
newblock = udf_get_lb_pblock(sb, &loc, ++block);
bh = sb_bread(sb, newblock);
if (!bh) {
udf_debug("read failed\n");
goto out;
}
index = 0;
ptr = (uint8_t *)bh->b_data;
}
}
brelse(bh);
out:
return accum;
}
static unsigned int udf_count_free_table(struct super_block *sb,
struct inode *table)
{
unsigned int accum = 0;
uint32_t elen;
struct kernel_lb_addr eloc;
struct extent_position epos;
int8_t etype;
mutex_lock(&UDF_SB(sb)->s_alloc_mutex);
epos.block = UDF_I(table)->i_location;
epos.offset = sizeof(struct unallocSpaceEntry);
epos.bh = NULL;
while (udf_next_aext(table, &epos, &eloc, &elen, &etype, 1) > 0)
accum += (elen >> table->i_sb->s_blocksize_bits);
brelse(epos.bh);
mutex_unlock(&UDF_SB(sb)->s_alloc_mutex);
return accum;
}
static unsigned int udf_count_free(struct super_block *sb)
{
unsigned int accum = 0;
struct udf_sb_info *sbi = UDF_SB(sb);
struct udf_part_map *map;
unsigned int part = sbi->s_partition;
int ptype = sbi->s_partmaps[part].s_partition_type;
if (ptype == UDF_METADATA_MAP25) {
part = sbi->s_partmaps[part].s_type_specific.s_metadata.
s_phys_partition_ref;
} else if (ptype == UDF_VIRTUAL_MAP15 || ptype == UDF_VIRTUAL_MAP20) {
/*
* Filesystems with VAT are append-only and we cannot write to
* them. Let's just report 0 here.
*/
return 0;
}
if (sbi->s_lvid_bh) {
struct logicalVolIntegrityDesc *lvid =
(struct logicalVolIntegrityDesc *)
sbi->s_lvid_bh->b_data;
if (le32_to_cpu(lvid->numOfPartitions) > part) {
accum = le32_to_cpu(
lvid->freeSpaceTable[part]);
if (accum == 0xFFFFFFFF)
accum = 0;
}
}
if (accum)
return accum;
map = &sbi->s_partmaps[part];
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
accum += udf_count_free_bitmap(sb,
map->s_uspace.s_bitmap);
}
if (accum)
return accum;
if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
accum += udf_count_free_table(sb,
map->s_uspace.s_table);
}
return accum;
}
MODULE_AUTHOR("Ben Fennema");
MODULE_DESCRIPTION("Universal Disk Format Filesystem");
MODULE_LICENSE("GPL");
module_init(init_udf_fs)
module_exit(exit_udf_fs)
]
|
| 12/2 |
2026/05/10 02:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 65839
output: 23
thoughts: 921
Thoughts: **Analyzing the UDF Filesystem Crash**
Okay, so I'm looking at this kernel crash log, and it points to a problem within the UDF filesystem code. Specifically, the crash originates in `fs/buffer.c` at `__getblk_slow` and `bdev_getblk`. This suggests a fundamental issue with block device access, likely involving the buffer cache. The backtrace leads me through a chain of UDF-specific functions, starting with `udf_fill_super`, which is the filesystem's superblock initialization function.
My initial thought is that the issue is likely within the `udf_fill_super` function. The code snippet shows that it attempts to determine the block size. If the block size isn't specified, it iterates through possible sizes to find a working one and then calls `udf_load_vrs`. Within `udf_load_vrs` is a call to `sb_set_blocksize`, and from there `udf_scan_anchors`. I have to admit I am not sure about why the code does not perform a blocksize check early on, like it does in `udf_load_vrs`.
My next thought is that the call to `udf_scan_anchors` is where the core issue might be, and then `udf_check_anchor_block` which reads the "anchor" block of the UDF volume, the code attempts a user provided anchor first. The crash appears to stem from `udf_read_tagged`, called by `udf_check_anchor_block`, which is responsible for reading a tagged block from the disk. This is a very interesting point as `udf_read_tagged` is the point where buffer_head issues are likely occurring. My guess is that it is reading a corrupt or malformed block, or that the block device access is somehow failing and is not handling the error. I'd suspect an issue with the block device or its access.
I will need to examine `udf_read_tagged` more closely, specifically how it interacts with the block device and the buffer cache. I'll be looking for potential race conditions, incorrect buffer handling, or errors related to block size assumptions. It's a classic case where a low-level error in block access propagates up to the UDF layer.
|
| 13/2 |
2026/05/10 02:57 |
tool |
read-file |
0m
Args:
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0-only
/*
* misc.c
*
* PURPOSE
* Miscellaneous routines for the OSTA-UDF(tm) filesystem.
*
* COPYRIGHT
* (C) 1998 Dave Boynton
* (C) 1998-2004 Ben Fennema
* (C) 1999-2000 Stelias Computing Inc
*
* HISTORY
*
* 04/19/99 blf partial support for reading/writing specific EA's
*/
#include "udfdecl.h"
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/crc-itu-t.h>
#include "udf_i.h"
#include "udf_sb.h"
struct genericFormat *udf_add_extendedattr(struct inode *inode, uint32_t size,
uint32_t type, uint8_t loc)
{
uint8_t *ea = NULL, *ad = NULL;
int offset;
uint16_t crclen;
struct udf_inode_info *iinfo = UDF_I(inode);
ea = iinfo->i_data;
if (iinfo->i_lenEAttr) {
ad = iinfo->i_data + iinfo->i_lenEAttr;
} else {
ad = ea;
size += sizeof(struct extendedAttrHeaderDesc);
}
offset = inode->i_sb->s_blocksize - udf_file_entry_alloc_offset(inode) -
iinfo->i_lenAlloc;
/* TODO - Check for FreeEASpace */
if (loc & 0x01 && offset >= size) {
struct extendedAttrHeaderDesc *eahd;
eahd = (struct extendedAttrHeaderDesc *)ea;
if (iinfo->i_lenAlloc)
memmove(&ad[size], ad, iinfo->i_lenAlloc);
if (iinfo->i_lenEAttr) {
/* check checksum/crc */
if (eahd->descTag.tagIdent !=
cpu_to_le16(TAG_IDENT_EAHD) ||
le32_to_cpu(eahd->descTag.tagLocation) !=
iinfo->i_location.logicalBlockNum)
return NULL;
} else {
struct udf_sb_info *sbi = UDF_SB(inode->i_sb);
size -= sizeof(struct extendedAttrHeaderDesc);
iinfo->i_lenEAttr +=
sizeof(struct extendedAttrHeaderDesc);
eahd->descTag.tagIdent = cpu_to_le16(TAG_IDENT_EAHD);
if (sbi->s_udfrev >= 0x0200)
eahd->descTag.descVersion = cpu_to_le16(3);
else
eahd->descTag.descVersion = cpu_to_le16(2);
eahd->descTag.tagSerialNum =
cpu_to_le16(sbi->s_serial_number);
eahd->descTag.tagLocation = cpu_to_le32(
iinfo->i_location.logicalBlockNum);
eahd->impAttrLocation = cpu_to_le32(0xFFFFFFFF);
eahd->appAttrLocation = cpu_to_le32(0xFFFFFFFF);
}
offset = iinfo->i_lenEAttr;
if (type < 2048) {
if (le32_to_cpu(eahd->appAttrLocation) <
iinfo->i_lenEAttr) {
uint32_t aal =
le32_to_cpu(eahd->appAttrLocation);
memmove(&ea[offset - aal + size],
&ea[aal], offset - aal);
offset -= aal;
eahd->appAttrLocation =
cpu_to_le32(aal + size);
}
if (le32_to_cpu(eahd->impAttrLocation) <
iinfo->i_lenEAttr) {
uint32_t ial =
le32_to_cpu(eahd->impAttrLocation);
memmove(&ea[offset - ial + size],
&ea[ial], offset - ial);
offset -= ial;
eahd->impAttrLocation =
cpu_to_le32(ial + size);
}
} else if (type < 65536) {
if (le32_to_cpu(eahd->appAttrLocation) <
iinfo->i_lenEAttr) {
uint32_t aal =
le32_to_cpu(eahd->appAttrLocation);
memmove(&ea[offset - aal + size],
&ea[aal], offset - aal);
offset -= aal;
eahd->appAttrLocation =
cpu_to_le32(aal + size);
}
}
/* rewrite CRC + checksum of eahd */
crclen = sizeof(struct extendedAttrHeaderDesc) - sizeof(struct tag);
eahd->descTag.descCRCLength = cpu_to_le16(crclen);
eahd->descTag.descCRC = cpu_to_le16(crc_itu_t(0, (char *)eahd +
sizeof(struct tag), crclen));
eahd->descTag.tagChecksum = udf_tag_checksum(&eahd->descTag);
iinfo->i_lenEAttr += size;
return (struct genericFormat *)&ea[offset];
}
return NULL;
}
struct genericFormat *udf_get_extendedattr(struct inode *inode, uint32_t type,
uint8_t subtype)
{
struct genericFormat *gaf;
uint8_t *ea = NULL;
uint32_t offset;
struct udf_inode_info *iinfo = UDF_I(inode);
ea = iinfo->i_data;
if (iinfo->i_lenEAttr) {
struct extendedAttrHeaderDesc *eahd;
eahd = (struct extendedAttrHeaderDesc *)ea;
/* check checksum/crc */
if (eahd->descTag.tagIdent !=
cpu_to_le16(TAG_IDENT_EAHD) ||
le32_to_cpu(eahd->descTag.tagLocation) !=
iinfo->i_location.logicalBlockNum)
return NULL;
if (type < 2048)
offset = sizeof(struct extendedAttrHeaderDesc);
else if (type < 65536)
offset = le32_to_cpu(eahd->impAttrLocation);
else
offset = le32_to_cpu(eahd->appAttrLocation);
while (offset + sizeof(*gaf) < iinfo->i_lenEAttr) {
uint32_t attrLength;
gaf = (struct genericFormat *)&ea[offset];
attrLength = le32_to_cpu(gaf->attrLength);
/* Detect undersized elements and buffer overflows */
if ((attrLength < sizeof(*gaf)) ||
(attrLength > (iinfo->i_lenEAttr - offset)))
break;
if (le32_to_cpu(gaf->attrType) == type &&
gaf->attrSubtype == subtype)
return gaf;
else
offset += attrLength;
}
}
return NULL;
}
/*
* udf_read_tagged
*
* PURPOSE
* Read the first block of a tagged descriptor.
*
* HISTORY
* July 1, 1997 - Andrew E. Mileski
* Written, tested, and released.
*/
struct buffer_head *udf_read_tagged(struct super_block *sb, uint32_t block,
uint32_t location, uint16_t *ident)
{
struct tag *tag_p;
struct buffer_head *bh = NULL;
u8 checksum;
/* Read the block */
if (block == 0xFFFFFFFF)
return NULL;
bh = sb_bread(sb, block);
if (!bh) {
udf_err(sb, "read failed, block=%u, location=%u\n",
block, location);
return NULL;
}
tag_p = (struct tag *)(bh->b_data);
*ident = le16_to_cpu(tag_p->tagIdent);
if (location != le32_to_cpu(tag_p->tagLocation)) {
udf_debug("location mismatch block %u, tag %u != %u\n",
block, le32_to_cpu(tag_p->tagLocation), location);
goto error_out;
}
/* Verify the tag checksum */
checksum = udf_tag_checksum(tag_p);
if (checksum != tag_p->tagChecksum) {
udf_err(sb, "tag checksum failed, block %u: 0x%02x != 0x%02x\n",
block, checksum, tag_p->tagChecksum);
goto error_out;
}
/* Verify the tag version */
if (tag_p->descVersion != cpu_to_le16(0x0002U) &&
tag_p->descVersion != cpu_to_le16(0x0003U)) {
udf_err(sb, "tag version 0x%04x != 0x0002 || 0x0003, block %u\n",
le16_to_cpu(tag_p->descVersion), block);
goto error_out;
}
/* Verify the descriptor CRC */
if (le16_to_cpu(tag_p->descCRCLength) + sizeof(struct tag) > sb->s_blocksize) {
udf_err(sb, "block %u: CRC length %u exceeds block size\n",
block, le16_to_cpu(tag_p->descCRCLength));
goto error_out;
}
if (le16_to_cpu(tag_p->descCRC) == crc_itu_t(0,
bh->b_data + sizeof(struct tag),
le16_to_cpu(tag_p->descCRCLength)))
return bh;
udf_debug("Crc failure block %u: crc = %u, crclen = %u\n", block,
le16_to_cpu(tag_p->descCRC),
le16_to_cpu(tag_p->descCRCLength));
error_out:
brelse(bh);
return NULL;
}
struct buffer_head *udf_read_ptagged(struct super_block *sb,
struct kernel_lb_addr *loc,
uint32_t offset, uint16_t *ident)
{
return udf_read_tagged(sb, udf_get_lb_pblock(sb, loc, offset),
loc->logicalBlockNum + offset, ident);
}
void udf_update_tag(char *data, int length)
{
struct tag *tptr = (struct tag *)data;
length -= sizeof(struct tag);
tptr->descCRCLength = cpu_to_le16(length);
tptr->descCRC = cpu_to_le16(crc_itu_t(0, data + sizeof(struct tag), length));
tptr->tagChecksum = udf_tag_checksum(tptr);
}
void udf_new_tag(char *data, uint16_t ident, uint16_t version, uint16_t snum,
uint32_t loc, int length)
{
struct tag *tptr = (struct tag *)data;
tptr->tagIdent = cpu_to_le16(ident);
tptr->descVersion = cpu_to_le16(version);
tptr->tagSerialNum = cpu_to_le16(snum);
tptr->tagLocation = cpu_to_le32(loc);
udf_update_tag(data, length);
}
u8 udf_tag_checksum(const struct tag *t)
{
u8 *data = (u8 *)t;
u8 checksum = 0;
int i;
for (i = 0; i < sizeof(struct tag); ++i)
if (i != 4) /* position of checksum */
checksum += data[i];
return checksum;
}
]
|
| 14/2 |
2026/05/10 02:57 |
llm |
debugger |
1m
Model:
Tokens:
input: 70401
output: 40
thoughts: 380
Thoughts: **Analyzing UDF Filesystem Block Size Handling**
Okay, so I'm looking at this `udf_read_tagged` function and the call stack it triggers. Specifically, I'm interested in how it reads blocks from the UDF filesystem. The critical path involves `sb_bread`, which then uses `__bread_gfp`, which relies on `bdev_getblk`, and finally, `__getblk_slow`. It seems this `__getblk_slow` has a check which is throwing a warning.
The warning itself catches my eye. It checks if the size of the block (`size`) is aligned to the logical block size of the underlying block device. The `size` in question is `sb->s_blocksize` – the superblock's idea of the block size. I need to keep in mind, I'm already aware that the super block size has the potential to be wrong. This potentially means there is an issue to diagnose.
Then I jump to `udf_load_vrs` and there's a call to `sb_set_blocksize`. Ah, that's where the superblock block size gets initialized. If this fails, then there is an issue which is potentially a problem. The code checks the return value, and if it's zero, then it errors out. My first thought is, does `sb_set_blocksize` return zero on error, or is this the kernel code checking for an issue?
So, I need to understand what happens if `sb_set_blocksize` fails. Is it just an unsupported block size, or does it indicate something more fundamental about how the filesystem is structured or the device it is using? I need to go look at the implementation of `sb_set_blocksize`, likely in `fs/block_dev.c` or perhaps `fs/super.c`, to figure out the exact failure conditions and the implications. I must understand how this block size initialization interacts with the alignment check in `__getblk_slow`.
|
| 15/2 |
2026/05/10 02:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/super.c IncludeLines:true Name:sb_set_blocksize]
Results: map[SourceCode: 236: int sb_set_blocksize(struct super_block *sb, int size)
237: {
238: if (size > PAGE_SIZE && sb_validate_large_blocksize(sb, size))
239: return 0;
240: if (set_blocksize(sb->s_bdev_file, size))
241: return 0;
242: /* If we get here, we know size is validated */
243: sb->s_blocksize = size;
244: sb->s_blocksize_bits = blksize_bits(size);
245: return sb->s_blocksize;
246: }
SourceFile:block/bdev.c]
|
| 16/2 |
2026/05/10 02:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 71469
output: 39
thoughts: 16
Thoughts: Here's my thought process, summarized as you requested:
**Internal Code Review: Set Blocksize Method**
Okay, let me think this through. I was just reviewing the `set_blocksize` method, and I just realized something. It checks if the `size` parameter is actually valid. Excellent, that's what I expect to see. Validation right at the start like that is crucial for robust code. No need to look any further into the validity checks - seems like the author had good foresight.
|
| 17/2 |
2026/05/10 02:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:set_blocksize]
Results: map[SourceCode: 178: int set_blocksize(struct file *file, int size)
179: {
180: struct inode *inode = file->f_mapping->host;
181: struct block_device *bdev = I_BDEV(inode);
182: int ret;
183:
184: ret = bdev_validate_blocksize(bdev, size);
185: if (ret)
186: return ret;
187:
188: if (!file->private_data)
189: return -EINVAL;
190:
191: /* Don't change the size if it is same as current */
192: if (inode->i_blkbits != blksize_bits(size)) {
193: /*
194: * Flush and truncate the pagecache before we reconfigure the
195: * mapping geometry because folio sizes are variable now. If a
196: * reader has already allocated a folio whose size is smaller
197: * than the new min_order but invokes readahead after the new
198: * min_order becomes visible, readahead will think there are
199: * "zero" blocks per folio and crash. Take the inode and
200: * invalidation locks to avoid racing with
201: * read/write/fallocate.
202: */
203: inode_lock(inode);
204: filemap_invalidate_lock(inode->i_mapping);
205:
206: sync_blockdev(bdev);
207: kill_bdev(bdev);
208:
209: inode->i_blkbits = blksize_bits(size);
210: mapping_set_folio_min_order(inode->i_mapping, get_order(size));
211: filemap_invalidate_unlock(inode->i_mapping);
212: inode_unlock(inode);
213: }
214: return 0;
215: }
SourceFile:block/bdev.c]
|
| 18/2 |
2026/05/10 02:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 72234
output: 42
thoughts: 19
Thoughts: Here's my thought process, summarized as you requested:
**Assessing Block Size Validation**
Okay, so I'm looking at this code... and I need to quickly grasp what's going on with this `bdev_validate_blocksize` function. Right, it checks `size`... that's the crucial variable. My understanding is, it's making sure that the provided `size` is a valid block size. That's good. It's the first step in ensuring data integrity and preventing errors down the line, right? Must validate the block size, that's what that function is tasked with.
|
| 19/2 |
2026/05/10 02:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:bdev_validate_blocksize]
Results: map[SourceCode: 155: /**
156: * bdev_validate_blocksize - check that this block size is acceptable
157: * @bdev: blockdevice to check
158: * @block_size: block size to check
159: *
160: * For block device users that do not use buffer heads or the block device
161: * page cache, make sure that this block size can be used with the device.
162: *
163: * Return: On success zero is returned, negative error code on failure.
164: */
165: int bdev_validate_blocksize(struct block_device *bdev, int block_size)
166: {
167: if (blk_validate_block_size(block_size))
168: return -EINVAL;
169:
170: /* Size cannot be smaller than the size supported by the device */
171: if (block_size < bdev_logical_block_size(bdev))
172: return -EINVAL;
173:
174: return 0;
175: }
SourceFile:block/bdev.c]
|
| 20/2 |
2026/05/10 02:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 72775
output: 42
thoughts: 72
Thoughts: **Checking Block Size Validation**
Okay, so `bdev_validate_blocksize` is designed to guarantee that the requested `block_size` is at least as large as the device's logical block size, as reported by `bdev_logical_block_size(bdev)`. That much is clear. But I'm now wondering if it goes further. Does it *also* enforce that the `block_size` is a multiple of that logical block size? That's the real question. I need to be sure about this detail. Let me double-check the logic within `blk_validate_block_size` to confirm. It's time to dig into the next function and see what it's really doing.
|
| 21/2 |
2026/05/10 02:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:blk_validate_block_size]
Results: map[SourceCode: 292: /* blk_validate_limits() validates bsize, so drivers don't usually need to */
293: static inline int blk_validate_block_size(unsigned long bsize)
294: {
295: if (bsize < 512 || bsize > BLK_MAX_BLOCK_SIZE || !is_power_of_2(bsize))
296: return -EINVAL;
297:
298: return 0;
299: }
SourceFile:include/linux/blkdev.h]
|
| 22/2 |
2026/05/10 02:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 73215
output: 42
thoughts: 2279
Thoughts: **Debugging a UDF Filesystem Block Size Mismatch**
Okay, so I'm looking at this warning that's popping up: `WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))`. The warning is triggered when the size parameter isn't aligned to the device's logical block size, which is a problem. Intuitively, this shouldn't happen. Since both `block_size` and `bdev_logical_block_size(bdev)` are powers of two, if the former is greater than or equal to the latter, then the alignment should *always* be correct.
The crash log points to this happening within the UDF filesystem code during the `__getblk_slow` operation. The `size` causing this warning is `sb->s_blocksize` which is the block size of the superblock. It seems the blocksize is set during mount.
My initial thought is to look at how block sizes are handled in `udf_fill_super`. I see there's logic that *either* uses a user-provided blocksize via the mount option `bs=...` *or* defaults to the device's logical block size. The mount option can specify block sizes of 512, 1024, 2048, or 4096. Then `udf_load_vrs` is called to validate the selected blocksize and set it as the superblock's blocksize. The `sb_set_blocksize` function is key. If this fails, it returns 0.
So, if a mount option like `bs=512` is passed, but the underlying block device reports, say, 1024 as its logical block size, `sb_set_blocksize` *should* fail, returning 0 and the `udf_load_vrs` returns `-EINVAL`. This suggests the filesystem *shouldn't* proceed. I'm trying to figure out why the warning is firing.
I examine `udf_check_vsd`, which calls `sb_bread` using `sb->s_blocksize`. If `sb_set_blocksize` succeeds, it updates `sb->s_blocksize`. But it *could* mean the blocksize selected isn't aligned to the logical blocksize of the device, if the `udf_load_vrs` is succesfull.
I then check `udf_read_tagged`, where `sb_bread` is called using `sb->s_blocksize` as the size parameter. It seems that `sb->s_blocksize` *is* used as the size parameter.
I'm now back to the alignment issue. If the warning is triggered, it means `sb->s_blocksize` is not aligned to `bdev_logical_block_size(bdev)`. However, since `sb_set_blocksize` ensures the block size is greater or equal to the logical block size of the underlying device, and both are powers of 2, the alignment *should* be guaranteed.
So, I have to go back to the base conditions: 1. `sb_set_blocksize` sets blocksize; and 2. both `sb->s_blocksize` and `bdev_logical_block_size` are powers of 2. The only way there can be an alignment issue is if the blocksize set is less than the device's logical blocksize, which is checked by `sb_set_blocksize` and returns -EINVAL.
I need to confirm that `bdev_logical_block_size` *is* always a power of 2. It appears that `blk_validate_block_size` confirms that the block size returned by the device is indeed a power of two.
The situation is puzzling. It's time to check how `sb_set_blocksize` is used, and what's going on with how the block device's logical block size is being determined.
I will need to investigate the block device itself to determine its block size and confirm that `bdev_logical_block_size` is correct. The warning clearly indicates a fundamental assumption about alignment is being violated, and I need to figure out *why*.
|
| 23/2 |
2026/05/10 02:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/super.c IncludeLines:true Name:get_tree_bdev_flags]
Results: map[SourceCode:1656: /**
1657: * get_tree_bdev_flags - Get a superblock based on a single block device
1658: * @fc: The filesystem context holding the parameters
1659: * @fill_super: Helper to initialise a new superblock
1660: * @flags: GET_TREE_BDEV_* flags
1661: */
1662: int get_tree_bdev_flags(struct fs_context *fc,
1663: int (*fill_super)(struct super_block *sb,
1664: struct fs_context *fc), unsigned int flags)
1665: {
1666: struct super_block *s;
1667: int error = 0;
1668: dev_t dev;
1669:
1670: if (!fc->source)
1671: return invalf(fc, "No source specified");
1672:
1673: error = lookup_bdev(fc->source, &dev);
1674: if (error) {
1675: if (!(flags & GET_TREE_BDEV_QUIET_LOOKUP))
1676: errorf(fc, "%s: Can't lookup blockdev", fc->source);
1677: return error;
1678: }
1679: fc->sb_flags |= SB_NOSEC;
1680: s = sget_dev(fc, dev);
1681: if (IS_ERR(s))
1682: return PTR_ERR(s);
1683:
1684: if (s->s_root) {
1685: /* Don't summarily change the RO/RW state. */
1686: if ((fc->sb_flags ^ s->s_flags) & SB_RDONLY) {
1687: warnf(fc, "%pg: Can't mount, would change RO state", s->s_bdev);
1688: deactivate_locked_super(s);
1689: return -EBUSY;
1690: }
1691: } else {
1692: error = setup_bdev_super(s, fc->sb_flags, fc);
1693: if (!error)
1694: error = fill_super(s, fc);
1695: if (error) {
1696: deactivate_locked_super(s);
1697: return error;
1698: }
1699: s->s_flags |= SB_ACTIVE;
1700: }
1701:
1702: BUG_ON(fc->root);
1703: fc->root = dget(s->s_root);
1704: return 0;
1705: }
SourceFile:fs/super.c]
|
| 24/2 |
2026/05/10 02:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 77257
output: 40
thoughts: 34
Thoughts: Okay, here's my interpretation of that thought process, from an expert's perspective:
**Diving into the Block Device Setup**
Alright, let me just double-check something. I'm looking at `setup_bdev_super`... and hold on a second. Isn't that function supposed to set the superblock's block size (`sb->s_blocksize`) based on the underlying block device (`bdev`)? Yeah, that's what I thought. It's using `bdev_logical_block_size(bdev)` to figure out the fundamental block size. That's good, that's expected behavior. We need to be sure that `sb->s_blocksize` is properly configured, that can cause problems later on. I just want to make sure I am following how this block size is set.
|
| 25/2 |
2026/05/10 02:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/super.c IncludeLines:true Name:setup_bdev_super]
Results: map[SourceCode:1605: int setup_bdev_super(struct super_block *sb, int sb_flags,
1606: struct fs_context *fc)
1607: {
1608: blk_mode_t mode = sb_open_mode(sb_flags);
1609: struct file *bdev_file;
1610: struct block_device *bdev;
1611:
1612: bdev_file = bdev_file_open_by_dev(sb->s_dev, mode, sb, &fs_holder_ops);
1613: if (IS_ERR(bdev_file)) {
1614: if (fc)
1615: errorf(fc, "%s: Can't open blockdev", fc->source);
1616: return PTR_ERR(bdev_file);
1617: }
1618: bdev = file_bdev(bdev_file);
1619:
1620: /*
1621: * This really should be in blkdev_get_by_dev, but right now can't due
1622: * to legacy issues that require us to allow opening a block device node
1623: * writable from userspace even for a read-only block device.
1624: */
1625: if ((mode & BLK_OPEN_WRITE) && bdev_read_only(bdev)) {
1626: bdev_fput(bdev_file);
1627: return -EACCES;
1628: }
1629:
1630: /*
1631: * It is enough to check bdev was not frozen before we set
1632: * s_bdev as freezing will wait until SB_BORN is set.
1633: */
1634: if (atomic_read(&bdev->bd_fsfreeze_count) > 0) {
1635: if (fc)
1636: warnf(fc, "%pg: Can't mount, blockdev is frozen", bdev);
1637: bdev_fput(bdev_file);
1638: return -EBUSY;
1639: }
1640: spin_lock(&sb_lock);
1641: sb->s_bdev_file = bdev_file;
1642: sb->s_bdev = bdev;
1643: sb->s_bdi = bdi_get(bdev->bd_disk->bdi);
1644: if (bdev_stable_writes(bdev))
1645: sb->s_iflags |= SB_I_STABLE_WRITES;
1646: spin_unlock(&sb_lock);
1647:
1648: snprintf(sb->s_id, sizeof(sb->s_id), "%pg", bdev);
1649: shrinker_debugfs_rename(sb->s_shrink, "sb-%s:%s", sb->s_type->name,
1650: sb->s_id);
1651: sb_set_blocksize(sb, block_size(bdev));
1652: return 0;
1653: }
SourceFile:fs/super.c]
|
| 26/2 |
2026/05/10 02:58 |
llm |
debugger |
1m
Model:
Tokens:
input: 78396
output: 45
thoughts: 1215
Thoughts: **Analyzing Potential Block Size Issues in UDF Filesystem Mounting**
Okay, so I'm looking at how the UDF filesystem handles block sizes during mounting, specifically considering potential issues with NBD devices. The code starts by calling `sb_set_blocksize(sb, block_size(bdev))`. `block_size(bdev)` retrieves the current block size of the block device. My initial thought is, what if there's a mismatch or a race condition with block size setting?
I know that `udf_fill_super` might set the block size with `sb_set_blocksize(sb, uopt->blocksize)`, and this could fail if `uopt->blocksize` is smaller than the device's logical block size, as returned by `bdev_logical_block_size(bdev)`. The important question is, what happens if `sb_set_blocksize` *isn't* called directly?
Diving into the code, if `uopt->flags & (1 << UDF_FLAG_BLOCKSIZE_SET)` is true, then `udf_load_vrs` is called directly. Otherwise, it sets `uopt->blocksize` to `bdev_logical_block_size(sb->s_bdev)` and attempts to load various versions of the filesystem, incrementing the block size until it is valid.
Within `udf_load_vrs`, `sb_set_blocksize` is called, and if it fails (returns 0), the function returns `-EINVAL`. This failure means `uopt->blocksize` can't be set to the superblock. The crucial point here is how `sb_set_blocksize` actually behaves. It checks for large block sizes, then calls `set_blocksize` on the block device. Importantly, it sets `sb->s_blocksize` to the size passed and returns the block size on success, or 0 on failure.
So, if `sb_set_blocksize` returns non-zero (success), it sets `sb->s_blocksize` to `uopt->blocksize`, which means that `uopt->blocksize >= bdev_logical_block_size(bdev)`. This seems correct, given that the filesystem has already validated it by this point.
Because `uopt->blocksize` must be a power of 2, it should be a multiple of `bdev_logical_block_size(bdev)`. Therefore, `IS_ALIGNED(uopt->blocksize, bdev_logical_block_size(bdev))` *should* be true.
Now, here's where it gets interesting: the reproducer uses an NBD device. *Can* the block size of this device change concurrently? I'm familiar with NBD's functionality, but let me consider: the code snippets show `ioctl$NBD_SET_SOCK`, `ioctl$NBD_DO_IT`, and the `mount` call. The `NBD_DO_IT` ioctl probably starts the NBD thread, but there is no server connection! `ioctl(fd_nbd, NBD_SET_SOCK, sock)` sets the socket to the NBD device. `ioctl(fd_nbd, NBD_DO_IT)` starts the NBD thread.
Therefore, the `NBD_DO_IT` might fail, but it's more important to consider that if the block size of the NBD device changes *concurrently* after we've read it with `bdev_logical_block_size(bdev)`, but before the block size is set, a race condition could exist. The critical issue is the concurrent modification of `bdev_logical_block_size(bdev)` after the mount has begun. This is where I need to focus my debugging.
|
| 27/2 |
2026/05/10 03:00 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/blkdev.h IncludeLines:true Name:bdev_logical_block_size]
Results: map[SourceCode:1397: static inline unsigned int bdev_logical_block_size(struct block_device *bdev)
1398: {
1399: return queue_logical_block_size(bdev_get_queue(bdev));
1400: }
SourceFile:include/linux/blkdev.h]
|
| 28/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 80585
output: 44
thoughts: 10
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Analyzing `queue_logical_block_size` in the Context of Optimization**
Right, let's break this down. When I see `queue_logical_block_size`, I immediately start thinking about its implications for I/O performance. It's not just a setting; it's a critical factor that dictates how efficiently data is handled at the block level, and ultimately, how that impacts the entire I/O stack.
I'm considering this in the context of optimizing a storage system, application, or perhaps even just analyzing a performance bottleneck. That `queue_logical_block_size` value *has* to align with the underlying hardware's physical characteristics, and ideally with the typical I/O pattern of the application. I'm wondering:
* **Is it set appropriately for the storage medium?** Flash, spinning disk, NVMe – they each have their sweet spots, and a mismatch here is just asking for trouble. A tiny block size on a high-end SSD? Likely suboptimal. A large block size on a random access workload? Probably not great either.
* **What about the host's perspective?** How does the OS interact with this value? Are there alignment issues? Overheads that might be creeping in? I know to double-check `sector_size` and see how it is aligned, that's crucial.
* **Could this be the source of fragmentation?** If the logical block size doesn't play nicely with the file system or the application's data structures, I'm thinking about potential fragmentation at the file system level and down to the physical storage.
* **Are there any performance implications with RAID?** Could misconfigured block sizes affect RAID parity calculations? Are there alignment issues that could impact write penalties?
Ultimately, this isn't just about setting a parameter. It's about understanding the entire I/O path, from the application's perspective all the way down to the physical storage, and making sure that all the pieces are working harmoniously to achieve optimal throughput, latency, and overall resource utilization.
|
| 29/2 |
2026/05/10 03:00 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/blkdev.h IncludeLines:true Name:queue_logical_block_size]
Results: map[SourceCode:1392: static inline unsigned queue_logical_block_size(const struct request_queue *q)
1393: {
1394: return q->limits.logical_block_size;
1395: }
SourceFile:include/linux/blkdev.h]
|
| 30/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 81194
output: 43
thoughts: 326
Thoughts: **Analyzing Potential Block Size Mismatches**
Okay, so I'm digging into this concurrent block size issue. My initial thought is, can the value of `q->limits.logical_block_size` actually change while the system is running? The answer is yes, because the block device driver can update the queue limits. Specifically, I'm thinking about NBD; I recall that `nbd_size_set` is responsible for changing the block size there.
But here's where it gets interesting, and concerning. If `bdev_logical_block_size` *does* change, it could end up being larger than `sb->s_blocksize`! Or, even worse, `sb->s_blocksize` might *not* be properly aligned to the new `bdev_logical_block_size`. I need to ensure this is handled safely.
Now, I need to confirm: is `bdev_logical_block_size` *always* a power of 2? Ah, yes, `blk_validate_limits` makes sure that the `logical_block_size` is indeed a power of two. That's a key requirement.
Let's illustrate with an example. If `bdev_logical_block_size` changes from 512 to 4096, and let's say `sb->s_blocksize` is 1024, then `IS_ALIGNED(1024, 4096)` becomes false! I can confirm this using the modulo operator: 1024 % 4096 is 1024, which is not zero!
I see, the `IS_ALIGNED(size, a)` macro is actually implemented as `!(size & (a - 1))`. So if `size` is 1024 and `a` is 4096, we have `1024 & (4096 - 1)`, which is `1024 & 4095`. That's 1024, which is not equal to zero. Thus, `IS_ALIGNED` indeed returns false. I should check `nbd_size_set` (or a similar routine in `drivers/block/nbd.c`) to understand how these size changes are managed. I need to understand how the power-of-2 requirement is enforced.
|
| 31/2 |
2026/05/10 03:00 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_size_set]
Results: map[SourceCode: SourceFile:]
|
| 32/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 82103
output: 22
thoughts: 34
Thoughts: Okay, let's dive into this. Here's how I'd approach that kernel code search, thinking like a seasoned kernel developer:
**Hunting Down Logical Block Size in the NBD Driver**
Alright, time to get to the heart of the matter. I need to figure out how the NBD driver handles logical block sizes. My first stop will definitely be `drivers/block/nbd.c`. That's where I'd expect to find the core implementation for the network block device. I need to find where the driver *stores* or *manages* the logical block size. I'm going to start by looking for two specific variables or definitions: `logical_block_size` and `blk_queue_logical_block_size`. Either of these should point me in the right direction. It's a quick and dirty way to get a focused search started. Let's see what we can find. I’m betting one of those will lead me to the relevant structure or function.
|
| 33/2 |
2026/05/10 03:00 |
tool |
grepper |
0m
Error:
Args: map[Expression:logical_block_size.*nbd]
Results:
|
| 34/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 82385
output: 32
thoughts: 27
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating Block Device Logical Block Size in the NBD Driver**
Alright, time to get to the heart of this. My initial instinct is to go digging in the Network Block Device driver code, specifically the `nbd.c` file within the `drivers/block` directory. I'm after something related to logical block size, so the search term `blk_queue_logical_block_size` seems like a solid starting point. That function usually deals directly with the block layer's configuration of a queue. Let's see how the NBD driver interacts with the block layer to define and handle its logical block size. I'm expecting to find where it sets the size, possibly during device initialization or configuration. I’m thinking there might be something related to the reported size from the NBD server. Depending on what I find, the next stop might be how the driver handles I/O requests that are not aligned to that logical block size, or how it propagates the size information upwards to user space. It should be pretty straightforward, but you never know. Ready, let's go get it!
|
| 35/2 |
2026/05/10 03:00 |
tool |
grepper |
0m
Error:
Args: map[Expression:blk_queue_logical_block_size.*drivers/block/nbd.c]
Results:
|
| 36/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 82710
output: 26
thoughts: 26
Thoughts: Here's my take on the thought process, as if it were my own:
**Investigating the Block Size in `nbd.c`**
Alright, let's get down to brass tacks. I need to understand how the block size is handled within the NBD driver. Rather than thrashing around and blindly guessing, the most direct approach here is to go straight to the source. Let's pull up the `drivers/block/nbd.c` file. That's the core of the network block device driver, so it's the logical place to start digging. Alternatively, a quick search within the file for instances of "block_size" should quickly illuminate where this parameter is defined, used, and manipulated within the code. This will be the most efficient path to clarity.
|
| 37/2 |
2026/05/10 03:00 |
tool |
grepper |
0m
Error:
Args: map[Expression:block_size.*drivers/block/nbd.c]
Results:
|
| 38/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 82944
output: 17
thoughts: 21
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Debugging the NBD Driver**
Right, something's not quite right. My `grep` expression clearly isn't hitting the target. I need to be more precise. Let me just double check, the file I'm after is definitely located in `drivers/block/nbd.c`. I've made a mistake with my search, and I need to refine that before I get bogged down.
|
| 39/2 |
2026/05/10 03:00 |
tool |
grepper |
0m
Args: map[Expression:block_size]
Results: map[Output:
Full output is too long, showing 500 out of 16140 lines.
Use more precise expression if possible.
[Documentation/ABI/stable/sysfs-block=471=Description:
--
Documentation/ABI/stable/sysfs-block-475-
Documentation/ABI/stable/sysfs-block:476:What: /sys/block/<disk>/queue/logical_block_size
Documentation/ABI/stable/sysfs-block-477-Date: May 2009
--
Documentation/ABI/stable/sysfs-block=669=Description:
--
Documentation/ABI/stable/sysfs-block-678-
Documentation/ABI/stable/sysfs-block:679:What: /sys/block/<disk>/queue/physical_block_size
Documentation/ABI/stable/sysfs-block-680-Date: May 2009
--
Documentation/ABI/stable/sysfs-block=682=Description:
--
Documentation/ABI/stable/sysfs-block-687- operating system. For stacked block devices the
Documentation/ABI/stable/sysfs-block:688: physical_block_size variable contains the maximum
Documentation/ABI/stable/sysfs-block:689: physical_block_size of the component devices.
Documentation/ABI/stable/sysfs-block-690-
--
Documentation/ABI/stable/sysfs-class-ubi=61=Description:
--
Documentation/ABI/stable/sysfs-class-ubi-64-
Documentation/ABI/stable/sysfs-class-ubi:65:What: /sys/class/ubi/ubiX/eraseblock_size
Documentation/ABI/stable/sysfs-class-ubi-66-Date: July 2006
--
Documentation/ABI/testing/sysfs-c2port=35=Description:
--
Documentation/ABI/testing/sysfs-c2port-39-
Documentation/ABI/testing/sysfs-c2port:40:What: /sys/class/c2port/c2portX/flash_block_size
Documentation/ABI/testing/sysfs-c2port-41-Date: October 2008
--
Documentation/ABI/testing/sysfs-c2port=43=Description:
Documentation/ABI/testing/sysfs-c2port:44: The /sys/class/c2port/c2portX/flash_block_size file show
Documentation/ABI/testing/sysfs-c2port-45- the on-board flash block size of the connected micro.
--
Documentation/ABI/testing/sysfs-driver-ufs=352=Description: This file shows the allocation unit size. This is one of
--
Documentation/ABI/testing/sysfs-driver-ufs-357-
Documentation/ABI/testing/sysfs-driver-ufs:358:What: /sys/bus/platform/drivers/ufshcd/*/geometry_descriptor/min_addressable_block_size
Documentation/ABI/testing/sysfs-driver-ufs:359:What: /sys/bus/platform/devices/*.ufs/geometry_descriptor/min_addressable_block_size
Documentation/ABI/testing/sysfs-driver-ufs-360-Date: February 2018
--
Documentation/ABI/testing/sysfs-driver-ufs=362=Description: This file shows the minimum addressable block size. This
--
Documentation/ABI/testing/sysfs-driver-ufs-368-
Documentation/ABI/testing/sysfs-driver-ufs:369:What: /sys/bus/platform/drivers/ufshcd/*/geometry_descriptor/optimal_read_block_size
Documentation/ABI/testing/sysfs-driver-ufs:370:What: /sys/bus/platform/devices/*.ufs/geometry_descriptor/optimal_read_block_size
Documentation/ABI/testing/sysfs-driver-ufs-371-Date: February 2018
--
Documentation/ABI/testing/sysfs-driver-ufs=373=Description: This file shows the optimal read block size. This is one
--
Documentation/ABI/testing/sysfs-driver-ufs-379-
Documentation/ABI/testing/sysfs-driver-ufs:380:What: /sys/bus/platform/drivers/ufshcd/*/geometry_descriptor/optimal_write_block_size
Documentation/ABI/testing/sysfs-driver-ufs:381:What: /sys/bus/platform/devices/*.ufs/geometry_descriptor/optimal_write_block_size
Documentation/ABI/testing/sysfs-driver-ufs-382-Date: February 2018
--
Documentation/ABI/testing/sysfs-driver-ufs=669=Description: This file defines the device behavior when a power failure
--
Documentation/ABI/testing/sysfs-driver-ufs-675-
Documentation/ABI/testing/sysfs-driver-ufs:676:What: /sys/class/scsi_device/*/device/unit_descriptor/logical_block_size
Documentation/ABI/testing/sysfs-driver-ufs-677-Date: February 2018
--
Documentation/ABI/testing/sysfs-driver-ufs=689=Description: This file shows total number of addressable logical blocks.
--
Documentation/ABI/testing/sysfs-driver-ufs-695-
Documentation/ABI/testing/sysfs-driver-ufs:696:What: /sys/class/scsi_device/*/device/unit_descriptor/erase_block_size
Documentation/ABI/testing/sysfs-driver-ufs-697-Date: February 2018
--
Documentation/admin-guide/bcache.rst=217=After you boot back with bcache enabled, you recreate the cache and attach it::
--
Documentation/admin-guide/bcache.rst-223- nbuckets: 106874
Documentation/admin-guide/bcache.rst:224: block_size: 1
Documentation/admin-guide/bcache.rst-225- bucket_size: 1024
--
Documentation/admin-guide/bcache.rst=518=bdev<0..n>
--
Documentation/admin-guide/bcache.rst-520-
Documentation/admin-guide/bcache.rst:521:block_size
Documentation/admin-guide/bcache.rst-522- Block size of the cache devices.
--
Documentation/admin-guide/bcache.rst=606=Available at /sys/block/<cdev>/bcache
Documentation/admin-guide/bcache.rst-607-
Documentation/admin-guide/bcache.rst:608:block_size
Documentation/admin-guide/bcache.rst-609- Minimum granularity of writes - should match hardware sector size.
--
Documentation/admin-guide/device-mapper/dm-ima.rst=421=section above) has the following data format for 'integrity' target.
--
Documentation/admin-guide/device-mapper/dm-ima.rst-425- target_attributes := <target_name> "," <target_version> "," <dev_name> "," <start>
Documentation/admin-guide/device-mapper/dm-ima.rst:426: <tag_size> "," <mode> "," [<meta_device> ","] [<block_size> ","] <recalculate> ","
Documentation/admin-guide/device-mapper/dm-ima.rst-427- <allow_discards> "," <fix_padding> "," <fix_hmac> "," <legacy_recalculate> ","
--
Documentation/admin-guide/device-mapper/dm-ima.rst-437- meta_device := "meta_device=" <meta_device_str>
Documentation/admin-guide/device-mapper/dm-ima.rst:438: block_size := "block_size=" <N>
Documentation/admin-guide/device-mapper/dm-ima.rst-439- recalculate := "recalculate=" <yes_no>
--
Documentation/admin-guide/device-mapper/dm-integrity.rst=165=journal_mac:algorithm(:key) (the key is optional)
--
Documentation/admin-guide/device-mapper/dm-integrity.rst-175-
Documentation/admin-guide/device-mapper/dm-integrity.rst:176:block_size:number (default 512)
Documentation/admin-guide/device-mapper/dm-integrity.rst-177- The size of a data block in bytes. The larger the block size the
--
Documentation/admin-guide/device-mapper/dm-integrity.rst=221=For example, on a device using the default interleave_sectors of 32768, a
Documentation/admin-guide/device-mapper/dm-integrity.rst:222:block_size of 512, and an internal_hash of crc32c with a tag size of 4
Documentation/admin-guide/device-mapper/dm-integrity.rst-223-bytes, it will take 128 KiB of tags to track a full data area, requiring
--
Documentation/admin-guide/device-mapper/thin-provisioning.rst=81=As a guide, we suggest you calculate the number of bytes to use in the
Documentation/admin-guide/device-mapper/thin-provisioning.rst:82:metadata device as 48 * $data_dev_size / $data_block_size but round it up
Documentation/admin-guide/device-mapper/thin-provisioning.rst-83-to 2MiB if the answer is smaller. If you're creating large numbers of
--
Documentation/admin-guide/device-mapper/thin-provisioning.rst=99=Using an existing pool device
--
Documentation/admin-guide/device-mapper/thin-provisioning.rst-105- --table "0 20971520 thin-pool $metadata_dev $data_dev \
Documentation/admin-guide/device-mapper/thin-provisioning.rst:106: $data_block_size $low_water_mark"
Documentation/admin-guide/device-mapper/thin-provisioning.rst-107-
Documentation/admin-guide/device-mapper/thin-provisioning.rst:108:$data_block_size gives the smallest unit of disk space that can be
Documentation/admin-guide/device-mapper/thin-provisioning.rst-109-allocated at a time expressed in units of 512-byte sectors.
Documentation/admin-guide/device-mapper/thin-provisioning.rst:110:$data_block_size must be between 128 (64KiB) and 2097152 (1GiB) and a
Documentation/admin-guide/device-mapper/thin-provisioning.rst:111:multiple of 128 (64KiB). $data_block_size cannot be changed after the
Documentation/admin-guide/device-mapper/thin-provisioning.rst-112-thin-pool is created. People primarily interested in thin provisioning
--
Documentation/admin-guide/device-mapper/thin-provisioning.rst=114=snapshotting may want a smaller value such as 128 (64KiB). If you are
Documentation/admin-guide/device-mapper/thin-provisioning.rst:115:not zeroing newly-allocated data, a larger $data_block_size in the
Documentation/admin-guide/device-mapper/thin-provisioning.rst-116-region of 262144 (128MiB) is suggested.
Documentation/admin-guide/device-mapper/thin-provisioning.rst-117-
Documentation/admin-guide/device-mapper/thin-provisioning.rst:118:$low_water_mark is expressed in blocks of size $data_block_size. If
Documentation/admin-guide/device-mapper/thin-provisioning.rst-119-free space on the data device drops below this level then a dm event
--
Documentation/admin-guide/device-mapper/verity.rst=9=Construction Parameters
--
Documentation/admin-guide/device-mapper/verity.rst-14- <version> <dev> <hash_dev>
Documentation/admin-guide/device-mapper/verity.rst:15: <data_block_size> <hash_block_size>
Documentation/admin-guide/device-mapper/verity.rst-16- <num_data_blocks> <hash_start_block>
--
Documentation/admin-guide/device-mapper/verity.rst-41-
Documentation/admin-guide/device-mapper/verity.rst:42:<data_block_size>
Documentation/admin-guide/device-mapper/verity.rst-43- The block size on a data device in bytes.
--
Documentation/admin-guide/device-mapper/verity.rst-45-
Documentation/admin-guide/device-mapper/verity.rst:46:<hash_block_size>
Documentation/admin-guide/device-mapper/verity.rst-47- The size of a hash block in bytes.
--
Documentation/admin-guide/device-mapper/verity.rst-54-<hash_start_block>
Documentation/admin-guide/device-mapper/verity.rst:55: This is the offset, in <hash_block_size>-blocks, from the start of hash_dev
Documentation/admin-guide/device-mapper/verity.rst-56- to the root block of the hash tree.
--
Documentation/admin-guide/device-mapper/verity.rst=104=use_fec_from_device <fec_dev>
--
Documentation/admin-guide/device-mapper/verity.rst-108- If this option is given, then <fec_roots> and <fec_blocks> must also be
Documentation/admin-guide/device-mapper/verity.rst:109: given. <hash_block_size> must also be equal to <data_block_size>.
Documentation/admin-guide/device-mapper/verity.rst-110-
--
Documentation/admin-guide/device-mapper/verity.rst=129=fec_blocks <num>
Documentation/admin-guide/device-mapper/verity.rst:130: The total number of <data_block_size> blocks that are error-checked using
Documentation/admin-guide/device-mapper/verity.rst-131- FEC. This must be at least the sum of <num_data_blocks> and the number of
--
Documentation/admin-guide/device-mapper/verity.rst-135- Note that this is *not* the number of parity blocks. The number of parity
Documentation/admin-guide/device-mapper/verity.rst:136: blocks is inferred from <fec_blocks>, <fec_roots>, and <data_block_size>.
Documentation/admin-guide/device-mapper/verity.rst-137-
Documentation/admin-guide/device-mapper/verity.rst=138=fec_start <offset>
Documentation/admin-guide/device-mapper/verity.rst:139: This is the offset, in <data_block_size> blocks, from the start of <fec_dev>
Documentation/admin-guide/device-mapper/verity.rst-140- to the beginning of the parity data.
--
Documentation/admin-guide/device-mapper/verity.rst=203=Each entry in the tree is a collection of neighboring nodes that fit in one
Documentation/admin-guide/device-mapper/verity.rst:204:block. The number is determined based on block_size and the size of the
Documentation/admin-guide/device-mapper/verity.rst-205-selected cryptographic digest algorithm. The hashes are linearly-ordered in
--
Documentation/admin-guide/device-mapper/verity.rst=209=The tree looks something like:
Documentation/admin-guide/device-mapper/verity.rst-210-
Documentation/admin-guide/device-mapper/verity.rst:211: alg = sha256, num_blocks = 32768, block_size = 4096
Documentation/admin-guide/device-mapper/verity.rst-212-
--
Documentation/admin-guide/device-mapper/verity.rst=270=Step 3a interleaves the RS codewords across the entire device using an
Documentation/admin-guide/device-mapper/verity.rst:271:interleaving degree of data_block_size * ceil(fec_blocks / k). This is the
Documentation/admin-guide/device-mapper/verity.rst-272-maximal interleaving, such that the message data consists of a region containing
--
Documentation/admin-guide/device-mapper/verity.rst=274=codewords, and so on up to the region for byte 'k - 1'. Note that the number of
Documentation/admin-guide/device-mapper/verity.rst:275:codewords is set to a multiple of data_block_size; thus, the regions are
Documentation/admin-guide/device-mapper/verity.rst-276-block-aligned, and there is an implicit zero padding of up to 'k - 1' blocks.
--
Documentation/admin-guide/md.rst=191=All md devices contain:
--
Documentation/admin-guide/md.rst-240-
Documentation/admin-guide/md.rst:241: logical_block_size
Documentation/admin-guide/md.rst-242- Configure the array's logical block size in bytes. This attribute
--
Documentation/admin-guide/media/visl.rst=105=The SPS data will be dumped to the trace buffer, i.e.:
--
Documentation/admin-guide/media/visl.rst-119- sps_max_latency_increase_plus1 0
Documentation/admin-guide/media/visl.rst:120: log2_min_luma_coding_block_size_minus3 0
Documentation/admin-guide/media/visl.rst:121: log2_diff_max_min_luma_coding_block_size 3
Documentation/admin-guide/media/visl.rst:122: log2_min_luma_transform_block_size_minus2 0
Documentation/admin-guide/media/visl.rst:123: log2_diff_max_min_luma_transform_block_size 3
Documentation/admin-guide/media/visl.rst-124- max_transform_hierarchy_depth_inter 2
--
Documentation/admin-guide/media/visl.rst-127- pcm_sample_bit_depth_chroma_minus1 0
Documentation/admin-guide/media/visl.rst:128: log2_min_pcm_luma_coding_block_size_minus3 0
Documentation/admin-guide/media/visl.rst:129: log2_diff_max_min_pcm_luma_coding_block_size 0
Documentation/admin-guide/media/visl.rst-130- num_short_term_ref_pic_sets 0
--
Documentation/admin-guide/mm/memory-hotplug.rst=123=by providing the physical start address of the memory block::
--
Documentation/admin-guide/mm/memory-hotplug.rst-126-
Documentation/admin-guide/mm/memory-hotplug.rst:127:Which results in a memory block for the range [addr, addr + memory_block_size)
Documentation/admin-guide/mm/memory-hotplug.rst-128-being created.
--
Documentation/admin-guide/mm/memory-hotplug.rst=276=The following files are currently defined:
--
Documentation/admin-guide/mm/memory-hotplug.rst-286- See the ``state`` property of memory blocks for details.
Documentation/admin-guide/mm/memory-hotplug.rst:287:``block_size_bytes`` read-only: the size in bytes of a memory block.
Documentation/admin-guide/mm/memory-hotplug.rst-288-``probe`` write-only: add (probe) selected memory blocks manually
--
Documentation/admin-guide/ufs.rst=11=ufstype=type_of_ufs
--
Documentation/admin-guide/ufs.rst-49- nextstep-cd
Documentation/admin-guide/ufs.rst:50: used for NextStep CDROMs (block_size == 2048)
Documentation/admin-guide/ufs.rst-51- supported as read-only
--
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml=16=properties:
--
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml-86-
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml:87: block_size:
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml-88- $ref: /schemas/types.yaml#/definitions/uint32
--
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml=164=examples:
--
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml-178- chan_priority = <1>;
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml:179: block_size = <0xfff>;
Documentation/devicetree/bindings/dma/snps,dma-spear1340.yaml-180- data-width = <8 8>;
--
Documentation/filesystems/erofs.rst=165=may not. All metadata can be now observed in two different spaces (views):
--
Documentation/filesystems/erofs.rst-172- Each inode can be directly found with the following formula:
Documentation/filesystems/erofs.rst:173: inode offset = meta_blkaddr * block_size + 32 * nid
Documentation/filesystems/erofs.rst-174-
--
Documentation/filesystems/erofs.rst-237- Each share xattr can also be directly found by the following formula:
Documentation/filesystems/erofs.rst:238: xattr offset = xattr_blkaddr * block_size + 4 * xattr_id
Documentation/filesystems/erofs.rst-239-
--
Documentation/filesystems/ext4/about.rst=28=pages on x86 and the block layer's default block size), though the
Documentation/filesystems/ext4/about.rst:29:actual size is calculated as 2 ^ (10 + ``sb.s_log_block_size``) bytes.
Documentation/filesystems/ext4/about.rst-30-Throughout this document, disk locations are given in terms of these
--
Documentation/filesystems/ext4/about.rst=32=convenience, the logical block size will be referred to as
Documentation/filesystems/ext4/about.rst:33:``$block_size`` throughout the rest of the document.
Documentation/filesystems/ext4/about.rst-34-
--
Documentation/filesystems/ext4/blockmap.rst-7-+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Documentation/filesystems/ext4/blockmap.rst:8:| 12 | Indirect block: (file blocks 12 to (``$block_size`` / 4) + 11, or 12 to 1035 if 4KiB blocks) |
Documentation/filesystems/ext4/blockmap.rst-9-| | |
--
Documentation/filesystems/ext4/blockmap.rst-12-| | +==============================+====================================================================+ |
Documentation/filesystems/ext4/blockmap.rst:13:| | | 0 to (``$block_size`` / 4) | Direct map to (``$block_size`` / 4) blocks (1024 if 4KiB blocks) | |
Documentation/filesystems/ext4/blockmap.rst-14-| | +------------------------------+--------------------------------------------------------------------+ |
Documentation/filesystems/ext4/blockmap.rst-15-+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Documentation/filesystems/ext4/blockmap.rst:16:| 13 | Double-indirect block: (file blocks ``$block_size``/4 + 12 to (``$block_size`` / 4) ^ 2 + (``$block_size`` / 4) + 11, or 1036 to 1049611 if 4KiB blocks) |
Documentation/filesystems/ext4/blockmap.rst-17-| | |
--
Documentation/filesystems/ext4/blockmap.rst-20-| | +================================+=========================================================================================================+ |
Documentation/filesystems/ext4/blockmap.rst:21:| | | 0 to (``$block_size`` / 4) | Map to (``$block_size`` / 4) indirect blocks (1024 if 4KiB blocks) | |
Documentation/filesystems/ext4/blockmap.rst-22-| | | | | |
--
Documentation/filesystems/ext4/blockmap.rst-25-| | | | +==============================+====================================================================+ | |
Documentation/filesystems/ext4/blockmap.rst:26:| | | | | 0 to (``$block_size`` / 4) | Direct map to (``$block_size`` / 4) blocks (1024 if 4KiB blocks) | | |
Documentation/filesystems/ext4/blockmap.rst-27-| | | | +------------------------------+--------------------------------------------------------------------+ | |
--
Documentation/filesystems/ext4/blockmap.rst-29-+---------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
Documentation/filesystems/ext4/blockmap.rst:30:| 14 | Triple-indirect block: (file blocks (``$block_size`` / 4) ^ 2 + (``$block_size`` / 4) + 12 to (``$block_size`` / 4) ^ 3 + (``$block_size`` / 4) ^ 2 + (``$block_size`` / 4) + 12, or 1049612 to 1074791436 if 4KiB blocks) |
Documentation/filesystems/ext4/blockmap.rst-31-| | |
--
Documentation/filesystems/ext4/blockmap.rst-34-| | +================================+================================================================================================================================================+ |
Documentation/filesystems/ext4/blockmap.rst:35:| | | 0 to (``$block_size`` / 4) | Map to (``$block_size`` / 4) double indirect blocks (1024 if 4KiB blocks) | |
Documentation/filesystems/ext4/blockmap.rst-36-| | | | | |
--
Documentation/filesystems/ext4/blockmap.rst-39-| | | | +================================+=========================================================================================================+ | |
Documentation/filesystems/ext4/blockmap.rst:40:| | | | | 0 to (``$block_size`` / 4) | Map to (``$block_size`` / 4) indirect blocks (1024 if 4KiB blocks) | | |
Documentation/filesystems/ext4/blockmap.rst-41-| | | | | | | | |
--
Documentation/filesystems/ext4/blockmap.rst-44-| | | | | | +==============================+====================================================================+ | | |
Documentation/filesystems/ext4/blockmap.rst:45:| | | | | | | 0 to (``$block_size`` / 4) | Direct map to (``$block_size`` / 4) blocks (1024 if 4KiB blocks) | | | |
Documentation/filesystems/ext4/blockmap.rst-46-| | | | | | +------------------------------+--------------------------------------------------------------------+ | | |
--
Documentation/filesystems/ext4/directory.rst=237=of a data block:
--
Documentation/filesystems/ext4/directory.rst-273- - dotdot.rec_len
Documentation/filesystems/ext4/directory.rst:274: - block_size - 12. The record length is long enough to cover all htree
Documentation/filesystems/ext4/directory.rst-275- data.
--
Documentation/filesystems/ext4/overview.rst=9=reducing seek times. The size of a block group is specified in
Documentation/filesystems/ext4/overview.rst-10-``sb.s_blocks_per_group`` blocks, though it can also calculated as 8 *
Documentation/filesystems/ext4/overview.rst:11:``block_size_in_bytes``. With the default block size of 4KiB, each group
Documentation/filesystems/ext4/overview.rst-12-will contain 32,768 blocks, for a length of 128MiB. The number of block
--
Documentation/filesystems/ext4/super.rst=18=The ext4 superblock is laid out as follows in
--
Documentation/filesystems/ext4/super.rst-55- - __le32
Documentation/filesystems/ext4/super.rst:56: - s_log_block_size
Documentation/filesystems/ext4/super.rst:57: - Block size is 2 ^ (10 + s_log_block_size).
Documentation/filesystems/ext4/super.rst-58- * - 0x1C
--
Documentation/filesystems/ext4/super.rst-61- - Cluster size is 2 ^ (10 + s_log_cluster_size) blocks if bigalloc is
Documentation/filesystems/ext4/super.rst:62: enabled. Otherwise s_log_cluster_size must equal s_log_block_size.
Documentation/filesystems/ext4/super.rst-63- * - 0x20
--
Documentation/filesystems/fsverity.rst=110=follows::
--
Documentation/filesystems/fsverity.rst-114- __u32 hash_algorithm;
Documentation/filesystems/fsverity.rst:115: __u32 block_size;
Documentation/filesystems/fsverity.rst-116- __u32 salt_size;
--
Documentation/filesystems/fsverity.rst=125=the file. It must be initialized as follows:
--
Documentation/filesystems/fsverity.rst-130- ``include/uapi/linux/fsverity.h`` for the list of possible values.
Documentation/filesystems/fsverity.rst:131:- ``block_size`` is the Merkle tree block size, in bytes. In Linux
Documentation/filesystems/fsverity.rst-132- v6.3 and later, this can be any power of 2 between (inclusively)
--
Documentation/filesystems/nfs/nfsd-io-modes.rst=110=NFSD's debugfs interfaces, ideally the IO will be aligned relative to
Documentation/filesystems/nfs/nfsd-io-modes.rst:111:the underlying block device's logical_block_size. Also the memory buffer
Documentation/filesystems/nfs/nfsd-io-modes.rst-112-used to store the READ or WRITE payload must be aligned relative to the
--
Documentation/filesystems/nfs/nfsd-io-modes.rst=118=Misaligned READ:
--
Documentation/filesystems/nfs/nfsd-io-modes.rst-120- DIO-aligned block (on either end of the READ). The expanded READ is
Documentation/filesystems/nfs/nfsd-io-modes.rst:121: verified to have proper offset/len (logical_block_size) and
Documentation/filesystems/nfs/nfsd-io-modes.rst-122- dma_alignment checking.
--
Documentation/filesystems/xfs/xfs-online-fsck-design.rst=2312=Roughly speaking, the maximum number of records is::
Documentation/filesystems/xfs/xfs-online-fsck-design.rst-2313-
Documentation/filesystems/xfs/xfs-online-fsck-design.rst:2314: maxrecs = (block_size - header_size) / record_size
Documentation/filesystems/xfs/xfs-online-fsck-design.rst-2315-
--
Documentation/filesystems/xfs/xfs-online-fsck-design.rst=2338=btree key and pointer as the record size::
Documentation/filesystems/xfs/xfs-online-fsck-design.rst-2339-
Documentation/filesystems/xfs/xfs-online-fsck-design.rst:2340: maxrecs = (block_size - header_size) / (key_size + ptr_size)
Documentation/filesystems/xfs/xfs-online-fsck-design.rst-2341- minrecs = maxrecs / 2
--
Documentation/misc-devices/c2port.rst=54=info or read/write in-system flash::
--
Documentation/misc-devices/c2port.rst-56- # ls /sys/class/c2port/c2port0/
Documentation/misc-devices/c2port.rst:57: access flash_block_size flash_erase rev_id
Documentation/misc-devices/c2port.rst-58- dev_id flash_blocks_num flash_size subsystem/
--
Documentation/networking/packet_mmap.rst=201=this parameter must to have the following structure::
--
Documentation/networking/packet_mmap.rst-204- {
Documentation/networking/packet_mmap.rst:205: unsigned int tp_block_size; /* Minimal size of contiguous block */
Documentation/networking/packet_mmap.rst-206- unsigned int tp_block_nr; /* Number of blocks */
--
Documentation/networking/packet_mmap.rst=216=Frames are grouped in blocks. Each block is a physically contiguous
Documentation/networking/packet_mmap.rst:217:region of memory and holds tp_block_size/tp_frame_size frames. The total number
Documentation/networking/packet_mmap.rst-218-of blocks is tp_block_nr. Note that tp_frame_nr is a redundant parameter because::
Documentation/networking/packet_mmap.rst-219-
Documentation/networking/packet_mmap.rst:220: frames_per_block = tp_block_size/tp_frame_size
Documentation/networking/packet_mmap.rst-221-
--
Documentation/networking/packet_mmap.rst=226=Lets see an example, with the following values::
Documentation/networking/packet_mmap.rst-227-
Documentation/networking/packet_mmap.rst:228: tp_block_size= 4096
Documentation/networking/packet_mmap.rst-229- tp_frame_size= 2048
--
Documentation/networking/packet_mmap.rst=393=The following are conditions that are checked in packet_set_ring
Documentation/networking/packet_mmap.rst-394-
Documentation/networking/packet_mmap.rst:395: - tp_block_size must be a multiple of PAGE_SIZE (1)
Documentation/networking/packet_mmap.rst-396- - tp_frame_size must be greater than TPACKET_HDRLEN (obvious)
--
Documentation/networking/packet_mmap.rst-399-
Documentation/networking/packet_mmap.rst:400:Note that tp_block_size should be chosen to be a power of two or there will
Documentation/networking/packet_mmap.rst-401-be a waste of memory.
--
Documentation/networking/packet_mmap.rst=409=just one call to mmap is needed::
--
Documentation/networking/packet_mmap.rst-412-
Documentation/networking/packet_mmap.rst:413:If tp_frame_size is a divisor of tp_block_size frames will be
Documentation/networking/packet_mmap.rst-414-contiguously spaced by tp_frame_size bytes. If not, each
Documentation/networking/packet_mmap.rst:415:tp_block_size/tp_frame_size frames there will be a gap between
Documentation/networking/packet_mmap.rst-416-the frames. This is because a frame cannot be spawn across two
--
Documentation/networking/packet_mmap.rst=773=it with gcc -Wall -O2 blob.c, and try things like "./a.out eth0", etc.)::
--
Documentation/networking/packet_mmap.rst-845- memset(&ring->req, 0, sizeof(ring->req));
Documentation/networking/packet_mmap.rst:846: ring->req.tp_block_size = blocksiz;
Documentation/networking/packet_mmap.rst-847- ring->req.tp_frame_size = framesiz;
--
Documentation/networking/packet_mmap.rst-859-
Documentation/networking/packet_mmap.rst:860: ring->map = mmap(NULL, ring->req.tp_block_size * ring->req.tp_block_nr,
Documentation/networking/packet_mmap.rst-861- PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, fd, 0);
--
Documentation/networking/packet_mmap.rst-869- for (i = 0; i < ring->req.tp_block_nr; ++i) {
Documentation/networking/packet_mmap.rst:870: ring->rd[i].iov_base = ring->map + (i * ring->req.tp_block_size);
Documentation/networking/packet_mmap.rst:871: ring->rd[i].iov_len = ring->req.tp_block_size;
Documentation/networking/packet_mmap.rst-872- }
--
Documentation/networking/packet_mmap.rst-944- {
Documentation/networking/packet_mmap.rst:945: munmap(ring->map, ring->req.tp_block_size * ring->req.tp_block_nr);
Documentation/networking/packet_mmap.rst-946- free(ring->rd);
--
Documentation/target/tcmu-design.rst=225=found at::
--
Documentation/target/tcmu-design.rst-228-
Documentation/target/tcmu-design.rst:229:This location contains attributes such as "hw_block_size", that
Documentation/target/tcmu-design.rst-230-userspace needs to know for correct operation.
--
Documentation/trace/events-kmem.rst=117=means of reducing the occurrence of this event is to increase the size of
Documentation/trace/events-kmem.rst:118:min_free_kbytes in increments of 3*pageblock_size*nr_online_nodes where
Documentation/trace/events-kmem.rst:119:pageblock_size is usually the size of the default hugepage size.
--
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst=1998=This structure contains all loop filter related parameters. See sections
--
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2114- * - __u8
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst:2115: - ``log2_min_luma_coding_block_size_minus3``
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2116- - This value plus 3 specifies the minimum luma coding block size.
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2117- * - __u8
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst:2118: - ``log2_diff_max_min_luma_coding_block_size``
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2119- - Specifies the difference between the maximum and minimum luma coding block size.
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2120- * - __u8
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst:2121: - ``log2_min_luma_transform_block_size_minus2``
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2122- - This value plus 2 specifies the minimum luma transform block size.
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2123- * - __u8
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst:2124: - ``log2_diff_max_min_luma_transform_block_size``
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2125- - Specifies the difference between the maximum and minimum luma transform block size.
--
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2142- * - __u8
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst:2143: - ``log2_min_pcm_luma_coding_block_size_minus3``
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2144- - Plus 3 specifies the minimum size of coding blocks.
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2145- * - __u8
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst:2146: - ``log2_diff_max_min_pcm_luma_coding_block_size``
Documentation/userspace-api/media/v4l/ext-ctrls-codec-stateless.rst-2147- - Specifies the difference between the maximum and minimum size of coding blocks.
--
arch/arc/boot/dts/abilis_tb10x.dtsi=105= dma@fe000000 {
--
arch/arc/boot/dts/abilis_tb10x.dtsi-115- chan_priority = <1>;
arch/arc/boot/dts/abilis_tb10x.dtsi:116: block_size = <0x7ff>;
arch/arc/boot/dts/abilis_tb10x.dtsi-117- data-width = <4>;
--
arch/arm/boot/dts/renesas/r9a06g032.dtsi=394= dma0: dma-controller@40104000 {
--
arch/arm/boot/dts/renesas/r9a06g032.dtsi-403- #dma-cells = <3>;
arch/arm/boot/dts/renesas/r9a06g032.dtsi:404: block_size = <0xfff>;
arch/arm/boot/dts/renesas/r9a06g032.dtsi-405- data-width = <8>;
--
arch/arm/boot/dts/renesas/r9a06g032.dtsi=408= dma1: dma-controller@40105000 {
--
arch/arm/boot/dts/renesas/r9a06g032.dtsi-417- #dma-cells = <3>;
arch/arm/boot/dts/renesas/r9a06g032.dtsi:418: block_size = <0xfff>;
arch/arm/boot/dts/renesas/r9a06g032.dtsi-419- data-width = <8>;
--
arch/arm/boot/dts/st/spear13xx.dtsi=101= dwdma0: dma@ea800000 {
--
arch/arm/boot/dts/st/spear13xx.dtsi-111- chan_priority = <1>;
arch/arm/boot/dts/st/spear13xx.dtsi:112: block_size = <0xfff>;
arch/arm/boot/dts/st/spear13xx.dtsi-113- dma-masters = <2>;
--
arch/arm/boot/dts/st/spear13xx.dtsi=118= dma@eb000000 {
--
arch/arm/boot/dts/st/spear13xx.dtsi-129- chan_priority = <1>;
arch/arm/boot/dts/st/spear13xx.dtsi:130: block_size = <0xfff>;
arch/arm/boot/dts/st/spear13xx.dtsi-131- data-width = <8 8>;
--
arch/arm/mach-omap2/control.c=48=struct omap3_scratchpad_prcm_block {
--
arch/arm/mach-omap2/control.c-50- u32 cm_contents[11];
arch/arm/mach-omap2/control.c:51: u32 prcm_block_size;
arch/arm/mach-omap2/control.c-52-};
--
arch/arm/mach-omap2/control.c=54=struct omap3_scratchpad_sdrc_block {
--
arch/arm/mach-omap2/control.c-82- u32 flags;
arch/arm/mach-omap2/control.c:83: u32 block_size;
arch/arm/mach-omap2/control.c-84-};
--
arch/arm/mach-omap2/control.c=231=void omap3_save_scratchpad_contents(void)
--
arch/arm/mach-omap2/control.c-272-
arch/arm/mach-omap2/control.c:273: prcm_block_contents.prcm_block_size = 0x0;
arch/arm/mach-omap2/control.c-274-
--
arch/arm/mach-omap2/control.c-327- sdrc_block_contents.flags = 0x0;
arch/arm/mach-omap2/control.c:328: sdrc_block_contents.block_size = 0x0;
arch/arm/mach-omap2/control.c-329-
--
arch/arm/mm/cache-l2x0.c=943=static int __init l2x0_cache_size_of_parse(const struct device_node *np,
--
arch/arm/mm/cache-l2x0.c-951- u32 way_size = 0;
arch/arm/mm/cache-l2x0.c:952: u32 block_size = 0;
arch/arm/mm/cache-l2x0.c-953- u32 line_size = 0;
--
arch/arm/mm/cache-l2x0.c-956- of_property_read_u32(np, "cache-sets", &sets);
arch/arm/mm/cache-l2x0.c:957: of_property_read_u32(np, "cache-block-size", &block_size);
arch/arm/mm/cache-l2x0.c-958- of_property_read_u32(np, "cache-line-size", &line_size);
--
arch/arm/mm/cache-l2x0.c-964- if (!line_size) {
arch/arm/mm/cache-l2x0.c:965: if (block_size) {
arch/arm/mm/cache-l2x0.c-966- /* If linesize is not given, it is equal to blocksize */
arch/arm/mm/cache-l2x0.c:967: line_size = block_size;
arch/arm/mm/cache-l2x0.c-968- } else {
--
arch/arm/mm/init.c=122=int pfn_valid(unsigned long pfn)
--
arch/arm/mm/init.c-124- phys_addr_t addr = __pfn_to_phys(pfn);
arch/arm/mm/init.c:125: unsigned long pageblock_size = PAGE_SIZE * pageblock_nr_pages;
]
]
|
| 40/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 95664
output: 22
thoughts: 56
Thoughts: **Investigating the NBD Driver's Block Size Configuration**
Okay, so I need to figure out how the network block device (NBD) driver is handling block size configuration. My initial instinct was to search directly for `nbd_size_set` within `drivers/block/nbd.c`, assuming that's where the primary mechanism would reside. However, that didn't yield the results I expected, it failed. This indicates the relevant logic is likely either elsewhere or handled indirectly.
Therefore, let's pivot and examine `drivers/block/nbd.c` for any mention of `logical_block_size`. That variable name feels like a more general term for defining the block size, and I suspect it may be used to configure it within the driver. Let's see if that provides any clues.
|
| 41/2 |
2026/05/10 03:00 |
tool |
grepper |
0m
Error:
Args: map[Expression:logical_block_size.*nbd]
Results:
|
| 42/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 95930
output: 26
thoughts: 27
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating Block Device Logical Block Size in the NBD Driver**
Alright, so the task at hand is to understand how the logical block size is handled within the Network Block Device (NBD) driver. My initial thought is to go straight to the source. Let's see... the most likely place to find this is within the `drivers/block/nbd.c` file. A quick search within that file using `blk_queue_logical_block_size` should hopefully pinpoint where and how the block size is set, retrieved, and potentially modified. This will reveal the mechanics of how the driver interacts with the underlying block layer regarding block size. Knowing this will give me a fundamental grasp on the NBD driver's ability to efficiently handle block size, and thus, performance.
|
| 43/2 |
2026/05/10 03:00 |
tool |
grepper |
0m
Error:
Args: map[Expression:blk_queue_logical_block_size.*nbd]
Results:
|
| 44/2 |
2026/05/10 03:00 |
llm |
debugger |
0m
Model:
Tokens:
input: 96182
output: 28
thoughts: 23
Thoughts: Okay, here's my summary, framed as my internal thought process:
**Diving into the NBD Driver's Block Size**
Alright, time to get to the heart of the matter. I need to understand how the Network Block Device (NBD) driver in Linux handles its logical block size. The objective here is to figure out the behavior of `logical_block_size`.
My instinct is to start digging into the source code, specifically, the `nbd.c` file which houses the NBD driver logic. So, let's fire up a search, and zero in on the exact variable or definition within that file, `drivers/block/nbd.c`. I have a feeling `logical_block_size` will be a critical parameter and might be used in different configurations, so I have to understand the source to trace it. Let's see what we can uncover!
|
| 45/2 |
2026/05/10 03:01 |
tool |
grepper |
0m
Error:
Args: map[Expression:logical_block_size.*drivers/block/nbd.c]
Results:
|
| 46/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 96436
output: 23
thoughts: 21
Thoughts: Here's my thought process, summarized as you requested:
**Navigating the Block Layer: Searching for `blk_queue_logical_block_size`**
Okay, time to dig into the block layer again. I need to find where the `blk_queue_logical_block_size` variable is used, and more importantly, how it's handled. This is likely related to how the kernel interfaces with different storage devices, and I want to understand the specifics of logical block size management within the `blk_queue` structure. Let's start with a full-tree search for the exact string, `blk_queue_logical_block_size`. That should give me a comprehensive picture of its uses. This should be a good starting point to understand the interactions in different contexts. From there I can refine my search based on where it's used the most.
|
| 47/2 |
2026/05/10 03:01 |
tool |
grepper |
0m
Error:
Args: map[Expression:blk_queue_logical_block_size]
Results:
|
| 48/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 96676
output: 19
thoughts: 45
Thoughts: Okay, here's the summary, tailored for an expert audience, in the first person:
**Investigating Potential Block Size Changes in NBD**
Hmm, a flicker of doubt. I've got this nagging feeling that the `blk_queue_logical_block_size` function, or perhaps something semantically equivalent, might have been deprecated, renamed, or flat-out removed. That could definitely impact the NBD driver's behavior, and I need to verify its current block size configuration.
My first thought is to dive into the code directly. Specifically, I'll zero in on `drivers/block/nbd.c`. I'm going to quickly search for occurrences of both "blocksize" and "blksize" within that file. That should give me a quick indication of how the code is currently handling (or failing to handle) block size information. If it's not being handled in the way I anticipate, I'll need to trace the code to see what's changed and how to adapt to it. This initial investigation should either confirm my suspicion or quickly reassure me, allowing me to move forward with greater confidence.
|
| 49/2 |
2026/05/10 03:01 |
tool |
grepper |
0m
Args: map[Expression:blksize.*nbd]
Results: map[Output:drivers/block/nbd.c=92=struct nbd_config {
--
drivers/block/nbd.c-110-
drivers/block/nbd.c:111:static inline unsigned int nbd_blksize(struct nbd_config *config)
drivers/block/nbd.c-112-{
--
include/uapi/linux/nbd.h-9- * 2003/06/24 Louis D. Langholtz <ldl@aros.net>
include/uapi/linux/nbd.h:10: * Removed unneeded blksize_bits field from nbd_device struct.
include/uapi/linux/nbd.h-11- * Cleanup PARANOIA usage & code.
]
|
| 50/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 97174
output: 42
thoughts: 22
Thoughts: Here's a first-person summary, tailored for an expert audience, as if I were processing those thoughts:
**Analyzing `nbd_blksize` in `drivers/block/nbd.c`**
Alright, let's dive into `drivers/block/nbd.c` and specifically focus on how `nbd_blksize` is handled. I need to refresh my memory on the NBD (Network Block Device) driver and how it negotiates block sizes with the server. I'm assuming we're looking for how the driver determines the optimal transfer size and what considerations are made for compatibility and performance. I expect there to be a few key areas of interest: initialization, where the block size is likely agreed upon; any error handling related to block size mismatches or limitations; and, of course, the actual read/write path where this block size is used during data transfer. We probably want to see how this block size interacts with the underlying block device interface of the host system. Is there any flexibility allowed? Are there any sanity checks in place to prevent requests that are too large or too small? Knowing this allows for understanding the performance profiles and the limits of the system in any given situation. Let's see if we can find any comments that reveal the rationale behind the chosen implementation, particularly if there are performance trade-offs involved. This is where the magic (or the problems) likely live.
|
| 51/2 |
2026/05/10 03:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_blksize]
Results: map[SourceCode: 111: static inline unsigned int nbd_blksize(struct nbd_config *config)
112: {
113: return 1u << config->blksize_bits;
114: }
SourceFile:drivers/block/nbd.c]
|
| 52/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 97624
output: 27
thoughts: 24
Thoughts: Here's my thought process, summarized as you requested:
**Navigating the NBD Driver Configuration**
Okay, so I need to understand how the block size is handled within the Network Block Device (NBD) driver. The obvious first step is to dig into the code itself. Specifically, I'm going to look for the `config` structure and, within it, the `blksize_bits` member. The file to start in is likely `drivers/block/nbd.c`. That's where the core NBD functionality resides. I expect that `config->blksize_bits` will hold the configuration setting related to the block size, probably as a bit shift value. Hopefully, this variable is well-commented, as is the habit within the linux kernel. Now, let's get to it. Time to open that file and start searching!
|
| 53/2 |
2026/05/10 03:01 |
tool |
grepper |
0m
Error:
Args: map[Expression:blksize_bits.*drivers/block/nbd.c]
Results:
|
| 54/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 97871
output: 18
thoughts: 24
Thoughts: Okay, here's my thought process on that:
**Quick Search Strategy**
Alright, I need to figure out how the block size is handled, likely within the NBD driver code. Instead of getting bogged down in a general code review, I'm going to take a targeted approach. Let me just search within the `drivers/block/nbd.c` file for the specific term `blksize_bits`. That's likely the variable or macro I'm looking for. It's concise and probably the best place to start.
|
| 55/2 |
2026/05/10 03:01 |
tool |
grepper |
0m
Args: map[Expression:blksize_bits]
Results: map[Output:block/bdev.c=140=static void set_init_blocksize(struct block_device *bdev)
--
block/bdev.c-149- }
block/bdev.c:150: BD_INODE(bdev)->i_blkbits = blksize_bits(bsize);
block/bdev.c-151- mapping_set_folio_min_order(BD_INODE(bdev)->i_mapping,
--
block/bdev.c=178=int set_blocksize(struct file *file, int size)
--
block/bdev.c-191- /* Don't change the size if it is same as current */
block/bdev.c:192: if (inode->i_blkbits != blksize_bits(size)) {
block/bdev.c-193- /*
--
block/bdev.c-208-
block/bdev.c:209: inode->i_blkbits = blksize_bits(size);
block/bdev.c-210- mapping_set_folio_min_order(inode->i_mapping, get_order(size));
--
block/bdev.c=236=int sb_set_blocksize(struct super_block *sb, int size)
--
block/bdev.c-243- sb->s_blocksize = size;
block/bdev.c:244: sb->s_blocksize_bits = blksize_bits(size);
block/bdev.c-245- return sb->s_blocksize;
--
drivers/block/nbd.c=92=struct nbd_config {
--
drivers/block/nbd.c-103- wait_queue_head_t recv_wq;
drivers/block/nbd.c:104: unsigned int blksize_bits;
drivers/block/nbd.c-105- loff_t bytesize;
--
drivers/block/nbd.c=111=static inline unsigned int nbd_blksize(struct nbd_config *config)
drivers/block/nbd.c-112-{
drivers/block/nbd.c:113: return 1u << config->blksize_bits;
drivers/block/nbd.c-114-}
--
drivers/block/nbd.c=334=static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
--
drivers/block/nbd.c-348- nbd->config->bytesize = bytesize;
drivers/block/nbd.c:349: nbd->config->blksize_bits = __ffs(blksize);
drivers/block/nbd.c-350-
--
drivers/block/nbd.c=1593=static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
--
drivers/block/nbd.c-1611- case NBD_SET_SIZE_BLOCKS:
drivers/block/nbd.c:1612: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
drivers/block/nbd.c-1613- return -EINVAL;
--
drivers/block/nbd.c=1670=static int nbd_alloc_and_init_config(struct nbd_device *nbd)
--
drivers/block/nbd.c-1688- init_waitqueue_head(&config->conn_wait);
drivers/block/nbd.c:1689: config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
drivers/block/nbd.c-1690- atomic_set(&config->live_connections, 0);
--
drivers/block/nbd.c=1820=static int nbd_dev_dbg_init(struct nbd_device *nbd)
--
drivers/block/nbd.c-1838- debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
drivers/block/nbd.c:1839: debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
drivers/block/nbd.c-1840- debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
--
drivers/nvme/target/io-cmd-bdev.c=93=int nvmet_bdev_ns_enable(struct nvmet_ns *ns)
--
drivers/nvme/target/io-cmd-bdev.c-117- ns->size = bdev_nr_bytes(ns->bdev);
drivers/nvme/target/io-cmd-bdev.c:118: ns->blksize_shift = blksize_bits(bdev_logical_block_size(ns->bdev));
drivers/nvme/target/io-cmd-bdev.c-119-
--
drivers/nvme/target/zns.c=35=bool nvmet_bdev_zns_enable(struct nvmet_ns *ns)
--
drivers/nvme/target/zns.c-63-
drivers/nvme/target/zns.c:64: ns->blksize_shift = blksize_bits(bdev_logical_block_size(ns->bdev));
drivers/nvme/target/zns.c-65-
--
drivers/s390/block/dasd_ioctl.c=192=dasd_format(struct dasd_block *block, struct format_data_t *fdata)
--
drivers/s390/block/dasd_ioctl.c-218- block->gdp->part0->bd_mapping->host->i_blkbits =
drivers/s390/block/dasd_ioctl.c:219: blksize_bits(fdata->blksize);
drivers/s390/block/dasd_ioctl.c-220- }
--
drivers/usb/gadget/function/storage_common.c=179=int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
--
drivers/usb/gadget/function/storage_common.c-236- blksize = bdev_logical_block_size(I_BDEV(inode));
drivers/usb/gadget/function/storage_common.c:237: blkbits = blksize_bits(blksize);
drivers/usb/gadget/function/storage_common.c-238- } else {
--
fs/btrfs/disk-io.c=2896=static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
--
fs/btrfs/disk-io.c-2902- sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
fs/btrfs/disk-io.c:2903: sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
fs/btrfs/disk-io.c-2904-
--
fs/btrfs/disk-io.c=3279=int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices)
--
fs/btrfs/disk-io.c-3452- sb->s_blocksize = sectorsize;
fs/btrfs/disk-io.c:3453: sb->s_blocksize_bits = blksize_bits(sectorsize);
fs/btrfs/disk-io.c-3454- memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
--
fs/buffer.c=893=static sector_t blkdev_max_block(struct block_device *bdev, unsigned int size)
--
fs/buffer.c-898- if (sz) {
fs/buffer.c:899: unsigned int sizebits = blksize_bits(size);
fs/buffer.c-900- retval = (sz >> sizebits);
--
fs/direct-io.c=1105=ssize_t __blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
--
fs/direct-io.c-1152- if (bdev)
fs/direct-io.c:1153: blkbits = blksize_bits(bdev_logical_block_size(bdev));
fs/direct-io.c-1154- blocksize_mask = (1 << blkbits) - 1;
--
fs/exfat/nls.c=738=int exfat_create_upcase_table(struct super_block *sb)
--
fs/exfat/nls.c-743- unsigned long long tbl_size, num_sectors;
fs/exfat/nls.c:744: unsigned char blksize_bits = sb->s_blocksize_bits;
fs/exfat/nls.c-745- struct exfat_chain clu;
--
fs/exfat/nls.c-773- sector = exfat_cluster_to_sector(sbi, tbl_clu);
fs/exfat/nls.c:774: num_sectors = ((tbl_size - 1) >> blksize_bits) + 1;
fs/exfat/nls.c-775- ret = exfat_load_upcase_table(sb, sector, num_sectors,
--
fs/ext4/extents.c=2221=static int ext4_fill_es_cache_info(struct inode *inode,
--
fs/ext4/extents.c-2226- struct extent_status es;
fs/ext4/extents.c:2227: unsigned char blksize_bits = inode->i_sb->s_blocksize_bits;
fs/ext4/extents.c-2228- unsigned int flags;
--
fs/ext4/extents.c-2250- err = fiemap_fill_next_extent(fieinfo,
fs/ext4/extents.c:2251: (__u64)es.es_lblk << blksize_bits,
fs/ext4/extents.c:2252: (__u64)es.es_pblk << blksize_bits,
fs/ext4/extents.c:2253: (__u64)es.es_len << blksize_bits,
fs/ext4/extents.c-2254- flags);
--
fs/ntfs3/fslog.c=1333=static void log_create(struct ntfs_log *log, const u64 last_lsn,
--
fs/ntfs3/fslog.c-1336- /* All file offsets must be quadword aligned. */
fs/ntfs3/fslog.c:1337: log->file_data_bits = blksize_bits(log->l_size) - 3;
fs/ntfs3/fslog.c-1338- log->seq_num_mask = (8 << log->file_data_bits) - 1;
--
fs/ntfs3/fslog.c=3748=int log_replay(struct ntfs_inode *ni, bool *initialized)
--
fs/ntfs3/fslog.c-3815- log->page_mask = log->page_size - 1;
fs/ntfs3/fslog.c:3816: log->page_bits = blksize_bits(log->page_size);
fs/ntfs3/fslog.c-3817-
--
fs/ntfs3/fslog.c-3952- log->page_mask = log->page_size - 1;
fs/ntfs3/fslog.c:3953: log->page_bits = blksize_bits(log->page_size);
fs/ntfs3/fslog.c-3954-
--
fs/ntfs3/index.c=870=int indx_init(struct ntfs_index *indx, struct ntfs_sb_info *sbi,
--
fs/ntfs3/index.c-890- t32 = le32_to_cpu(root->index_block_size);
fs/ntfs3/index.c:891: indx->index_bits = blksize_bits(t32);
fs/ntfs3/index.c-892-
--
fs/ntfs3/run.c=317=bool run_add_entry(struct runs_tree *run, CLST vcn, CLST lcn, CLST len,
--
fs/ntfs3/run.c-382- bytes = (size_t)1
fs/ntfs3/run.c:383: << (2 + blksize_bits(used));
fs/ntfs3/run.c-384- } else {
--
fs/ntfs3/super.c=954=static int ntfs_init_from_boot(struct super_block *sb, u32 sector_size,
--
fs/ntfs3/super.c-1020- sbi->cluster_size = boot_sector_size * sct_per_clst;
fs/ntfs3/super.c:1021: sbi->cluster_bits = cluster_bits = blksize_bits(sbi->cluster_size);
fs/ntfs3/super.c-1022- sbi->cluster_mask = sbi->cluster_size - 1;
--
fs/ntfs3/super.c-1047- sbi->record_size = record_size;
fs/ntfs3/super.c:1048: sbi->record_bits = blksize_bits(record_size);
fs/ntfs3/super.c-1049- sbi->attr_size_tr = (5 * record_size >> 4); // ~320 bytes
--
fs/ntfs3/super.c-1221-
fs/ntfs3/super.c:1222: boot_block = lbo >> blksize_bits(block_size);
fs/ntfs3/super.c-1223- boot_off = lbo & (block_size - 1);
--
fs/ocfs2/super.c=1944=static int ocfs2_initialize_super(struct super_block *sb,
--
fs/ocfs2/super.c-1986- osb->sb = sb;
fs/ocfs2/super.c:1987: osb->s_sectsize_bits = blksize_bits(sector_size);
fs/ocfs2/super.c-1988- BUG_ON(!osb->s_sectsize_bits);
--
fs/romfs/super.c=450=static int romfs_fill_super(struct super_block *sb, struct fs_context *fc)
--
fs/romfs/super.c-466- sb->s_blocksize = ROMBSIZE;
fs/romfs/super.c:467: sb->s_blocksize_bits = blksize_bits(ROMBSIZE);
fs/romfs/super.c-468- }
--
include/linux/blkdev.h=1612=static inline bool blk_rq_aligned(struct request_queue *q, unsigned long addr,
--
include/linux/blkdev.h-1620-/* assumes size > 256 */
include/linux/blkdev.h:1621:static inline unsigned int blksize_bits(unsigned int size)
include/linux/blkdev.h-1622-{
--
include/uapi/linux/nbd.h-9- * 2003/06/24 Louis D. Langholtz <ldl@aros.net>
include/uapi/linux/nbd.h:10: * Removed unneeded blksize_bits field from nbd_device struct.
include/uapi/linux/nbd.h-11- * Cleanup PARANOIA usage & code.
]
|
| 56/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 102205
output: 43
thoughts: 2116
Thoughts: **Analyzing the NBD Block Size Issue**
Okay, so I've been tracing the block size logic in the NBD driver, trying to understand this reported warning in the UDF filesystem. It looks like the core of the problem lies in a race condition between mounting a filesystem on an NBD device and the initialization of the NBD device itself.
First, I see `nbd_set_size` is called to set the block size. This is called when `NBD_SET_SIZE_BLOCKS` or `NBD_SET_BLKSIZE` ioctls are used. However, the reproducer doesn't seem to use this; it uses `NBD_DO_IT`, which kicks off device startup. Looking into `nbd_start_device`, the logical block size is set via `blk_queue_logical_block_size(nbd->disk->queue, nbd_blksize(config))`, where `nbd_blksize(config)` is calculated from `config->blksize_bits`, which defaults to 10, resulting in 1024. This initialization of block size to 1024 is the key.
Meanwhile, a mount operation is happening in parallel. The `mount` syscall calls `get_tree_bdev_flags`, which calls `setup_bdev_super`, and that in turn sets the superblock's block size using `block_size(bdev)`. At this point, the block size is set to the default block size of a block device. Importantly, the `udf_fill_super` function then sets the UDF filesystem block size. This is done by looking at `bdev_logical_block_size(sb->s_bdev)`, which I *thought* was initialized to 512, but this assumption is incorrect.
So, here's how the race *should* occur if my initial assumption was true:
1. **Mount Process (Thread A):** The mount process starts, initializes its block size to some default, and then starts scanning the UDF disk. Critically, during UDF initialization, it reads blocks, setting the filesystem block size (e.g. 512) based on what's detected at this point.
2. **NBD Start (Thread B):** Concurrently, the NBD device is started via `NBD_DO_IT`, which sets the *logical* block size of the underlying block device to 1024, through the function `nbd_start_device`.
If this scenario played out, then when UDF read block, the check `IS_ALIGNED(512, 1024)` would fail. And that's exactly what's reported in the kernel message.
However, I've just remembered where the size is initialized, and this assumption about 512 is wrong!
The NBD disk is initialized with a default logical block size of 1024 in `nbd_alloc_disk`. This sets both logical and physical block size to 1024. So, there is no chance that `bdev_logical_block_size` can be 512.
So, how can we trigger the `WARN_ON_ONCE`?
1. **Mount Process (Thread A):** Mount operation calls `udf_fill_super` which calls `udf_load_vrs`. This calls `sb_set_blocksize`, which sets `sb->s_blocksize = bdev_logical_block_size`. Since logical block size is set to 1024 by `nbd_alloc_disk`, `sb->s_blocksize` is set to 1024. Then, the block size of the underlying block device *is* 1024.
2. **NBD Start (Thread B):** `ioctl(NBD_DO_IT)` is called, which calls `nbd_start_device`. But the block size is already set to 1024, so it is just set again to 1024.
3. **Thread A (continues):** Then, UDF tries to read a block in `udf_read_tagged`. But block size is already 1024.
4. **Conclusion:** But if UDF does this reading based on the default block size, while the device size is initialized with a different value (e.g., set to 512 using an ioctl and then changed in the middle with `nbd_start_device`), this will then trigger this warning.
So, the issue isn't about the *initial* block size but about a potential change of block size while the mount is already running. The race condition occurs when a
|
| 57/2 |
2026/05/10 03:01 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_alloc_disk]
Results: map[SourceCode: SourceFile:]
|
| 58/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 105410
output: 26
thoughts: 27
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating Block Device Logical Block Size in the NBD Driver**
Alright, so the task at hand is to understand how the logical block size is handled within the Network Block Device (NBD) driver. My initial thought is to go straight to the source. Let's see... the most likely place to find this is within the `drivers/block/nbd.c` file. A quick search within that file using `blk_queue_logical_block_size` should hopefully pinpoint where and how the block size is set, retrieved, and potentially modified. This will reveal the mechanics of how the driver interacts with the underlying block layer regarding block size. Knowing this will give me a fundamental grasp on the NBD driver's ability to efficiently handle block size, and thus, performance.
|
| 59/2 |
2026/05/10 03:01 |
tool |
grepper |
0m
Error:
Args: map[Expression:blk_queue_logical_block_size.*nbd]
Results:
|
| 60/2 |
2026/05/10 03:01 |
llm |
debugger |
0m
Model:
Tokens:
input: 105662
output: 43
thoughts: 63
Thoughts: **Investigating the Disappearance of `blk_queue_logical_block_size`**
Okay, hold on a second. Didn't I just look for `blk_queue_logical_block_size`? And the search turned up empty? That's...interesting. It strongly suggests that function might have been removed or deprecated. Right, let's explore that possibility. The kernel changes quickly.
Given that, I'll switch gears and try to chase down a related function or method. Let's see... a good candidate might be something that sets the logical block size for a block device driver. That makes me think of the NBD driver. Let's dig into `drivers/block/nbd.c` and specifically look at `nbd_set_size`. Maybe that's where the relevant functionality now resides, or at least hints at how block sizes are handled now.
|
| 61/2 |
2026/05/10 03:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_set_size]
Results: map[SourceCode: 334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
335: {
336: struct queue_limits lim;
337: int error;
338:
339: if (!blksize)
340: blksize = 1u << NBD_DEF_BLKSIZE_BITS;
341:
342: if (blk_validate_block_size(blksize))
343: return -EINVAL;
344:
345: if (bytesize < 0)
346: return -EINVAL;
347:
348: nbd->config->bytesize = bytesize;
349: nbd->config->blksize_bits = __ffs(blksize);
350:
351: if (!nbd->pid)
352: return 0;
353:
354: lim = queue_limits_start_update(nbd->disk->queue);
355: if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
356: lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
357: else
358: lim.max_hw_discard_sectors = 0;
359: if (!(nbd->config->flags & NBD_FLAG_SEND_FLUSH)) {
360: lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
361: } else if (nbd->config->flags & NBD_FLAG_SEND_FUA) {
362: lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
363: } else {
364: lim.features |= BLK_FEAT_WRITE_CACHE;
365: lim.features &= ~BLK_FEAT_FUA;
366: }
367: if (nbd->config->flags & NBD_FLAG_ROTATIONAL)
368: lim.features |= BLK_FEAT_ROTATIONAL;
369: if (nbd->config->flags & NBD_FLAG_SEND_WRITE_ZEROES)
370: lim.max_write_zeroes_sectors = UINT_MAX >> SECTOR_SHIFT;
371:
372: lim.logical_block_size = blksize;
373: lim.physical_block_size = blksize;
374: error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
375: if (error)
376: return error;
377:
378: if (max_part)
379: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
380: if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
381: kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
382: return 0;
383: }
SourceFile:drivers/block/nbd.c]
|
| 62/2 |
2026/05/10 03:02 |
llm |
debugger |
0m
Model:
Tokens:
input: 106861
output: 43
thoughts: 205
Thoughts: **Analyzing the `queue_limits_commit_update_frozen` Function and `NBD_SET_BLKSIZE` Behavior**
Okay, so I'm digging into this code and trying to understand how these queue limits are handled. Specifically, I see that the `queue_limits_commit_update_frozen` function is the one responsible for updating limits, including the all-important `logical_block_size`. That seems straightforward. But then, my attention is caught by this `nbd_set_size` function and how it interacts.
I see it's called when `nbd->pid` is *not* zero, meaning the device has been started. However, the critical point is that if `nbd->pid` *is* zero, then it just immediately returns a zero, meaning it does **not** update those queue limits! This is a key observation.
Now, if I think about the implications...if `ioctl(fd_nbd, NBD_SET_BLKSIZE, blksize)` is called *before* `NBD_DO_IT`, `nbd_set_size` only goes as far as updating `nbd->config->blksize_bits`. Importantly, it DOES NOT update the queue limits at this stage! That's a critical difference. This suggests that the block size setting happens in two steps - setting the internal value and setting the queue limits.
So, setting the block size *before* starting the device effectively delays the actual queue limit update. Then, when `NBD_DO_IT` is finally called, we get to `nbd_start_device`. That's where the magic happens and the queue limits are properly updated, and therefore, I should analyze the `nbd_start_device` function to see exactly how this update is happening.
|
| 63/2 |
2026/05/10 03:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device]
Results: map[SourceCode:1471: static int nbd_start_device(struct nbd_device *nbd)
1472: {
1473: struct nbd_config *config = nbd->config;
1474: int num_connections = config->num_connections;
1475: int error = 0, i;
1476:
1477: if (nbd->pid)
1478: return -EBUSY;
1479: if (!config->socks)
1480: return -EINVAL;
1481: if (num_connections > 1 &&
1482: !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1483: dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1484: return -EINVAL;
1485: }
1486:
1487: retry:
1488: mutex_unlock(&nbd->config_lock);
1489: blk_mq_update_nr_hw_queues(&nbd->tag_set, num_connections);
1490: mutex_lock(&nbd->config_lock);
1491:
1492: /* if another code path updated nr_hw_queues, retry until succeed */
1493: if (num_connections != config->num_connections) {
1494: num_connections = config->num_connections;
1495: goto retry;
1496: }
1497:
1498: nbd->pid = task_pid_nr(current);
1499:
1500: nbd_parse_flags(nbd);
1501:
1502: error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1503: if (error) {
1504: dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1505: return error;
1506: }
1507: set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1508:
1509: nbd_dev_dbg_init(nbd);
1510: for (i = 0; i < num_connections; i++) {
1511: struct recv_thread_args *args;
1512:
1513: args = kzalloc_obj(*args);
1514: if (!args) {
1515: sock_shutdown(nbd);
1516: /*
1517: * If num_connections is m (2 < m),
1518: * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1519: * But NO.(n + 1) failed. We still have n recv threads.
1520: * So, add flush_workqueue here to prevent recv threads
1521: * dropping the last config_refs and trying to destroy
1522: * the workqueue from inside the workqueue.
1523: */
1524: if (i)
1525: flush_workqueue(nbd->recv_workq);
1526: return -ENOMEM;
1527: }
1528: sk_set_memalloc(config->socks[i]->sock->sk);
1529: if (nbd->tag_set.timeout)
1530: config->socks[i]->sock->sk->sk_sndtimeo =
1531: nbd->tag_set.timeout;
1532: atomic_inc(&config->recv_threads);
1533: refcount_inc(&nbd->config_refs);
1534: INIT_WORK(&args->work, recv_work);
1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
SourceFile:drivers/block/nbd.c]
|
| 64/2 |
2026/05/10 03:02 |
llm |
debugger |
0m
Model:
Tokens:
input: 108678
output: 47
thoughts: 155
Thoughts: **Analyzing the Queue Limits Update**
Okay, so `nbd_start_device` triggers the `nbd_set_size` function, and I see that it's using the provided `bytesize` along with the calculated block size from `nbd_blksize(config)`. Ah, excellent, since the process ID (`nbd->pid`) has been assigned now, `nbd_set_size` will update the queue limits. That's good, that's what I expect.
Now, a quick sanity check... `nbd_blksize(config)` translates to `1u << config->blksize_bits`. Right, that's straightforward. If `NBD_SET_BLKSIZE` hasn't been used, then `config->blksize_bits` defaults to 10 (which represents 1024 bytes). But wait a second, what was the initial `logical_block_size` that the queue started with? I need to know the baseline before the update. Let me go back and trace the initialization process, I need to check `nbd_alloc_and_init_config`. I'll find my answers there.
|
| 65/2 |
2026/05/10 03:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_alloc_and_init_config]
Results: map[SourceCode:1670: static int nbd_alloc_and_init_config(struct nbd_device *nbd)
1671: {
1672: struct nbd_config *config;
1673:
1674: if (WARN_ON(nbd->config))
1675: return -EINVAL;
1676:
1677: if (!try_module_get(THIS_MODULE))
1678: return -ENODEV;
1679:
1680: config = kzalloc_obj(struct nbd_config, GFP_NOFS);
1681: if (!config) {
1682: module_put(THIS_MODULE);
1683: return -ENOMEM;
1684: }
1685:
1686: atomic_set(&config->recv_threads, 0);
1687: init_waitqueue_head(&config->recv_wq);
1688: init_waitqueue_head(&config->conn_wait);
1689: config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1690: atomic_set(&config->live_connections, 0);
1691:
1692: nbd->config = config;
1693: /*
1694: * Order refcount_set(&nbd->config_refs, 1) and nbd->config assignment,
1695: * its pair is the barrier in nbd_get_config_unlocked().
1696: * So nbd_get_config_unlocked() won't see nbd->config as null after
1697: * refcount_inc_not_zero() succeed.
1698: */
1699: smp_mb__before_atomic();
1700: refcount_set(&nbd->config_refs, 1);
1701:
1702: return 0;
1703: }
SourceFile:drivers/block/nbd.c]
|
| 66/2 |
2026/05/10 03:02 |
llm |
debugger |
0m
Model:
Tokens:
input: 109686
output: 43
thoughts: 42
Thoughts: Okay, let me think this through.
**Analyzing Queue Limit Initialization in the NBD Driver**
Hmm, hold on a second. I just realized something about `nbd_alloc_and_init_config`. It appears that this function *doesn't* actually touch the queue limits. That's a key detail I missed initially. So, if the configuration isn't setting the limits, then where *are* they being set? This requires a closer look.
My immediate next step is to trace back the execution flow. I need to pinpoint where this vital information is being initialized. Let's shift our focus to `nbd_dev_add`. I'm guessing that's where the limits are likely being established. Let's see if this function initializes the queue limits during the device addition process. I will now examine `nbd_dev_add` more closely.
|
| 67/2 |
2026/05/10 03:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_dev_add]
Results: map[SourceCode:1907: static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1908: {
1909: struct queue_limits lim = {
1910: .max_hw_sectors = 65536,
1911: .io_opt = 256 << SECTOR_SHIFT,
1912: .max_segments = USHRT_MAX,
1913: .max_segment_size = UINT_MAX,
1914: };
1915: struct nbd_device *nbd;
1916: struct gendisk *disk;
1917: int err = -ENOMEM;
1918:
1919: nbd = kzalloc_obj(struct nbd_device);
1920: if (!nbd)
1921: goto out;
1922:
1923: nbd->tag_set.ops = &nbd_mq_ops;
1924: nbd->tag_set.nr_hw_queues = 1;
1925: nbd->tag_set.queue_depth = 128;
1926: nbd->tag_set.numa_node = NUMA_NO_NODE;
1927: nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1928: nbd->tag_set.flags = BLK_MQ_F_BLOCKING;
1929: nbd->tag_set.driver_data = nbd;
1930: INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1931: nbd->backend = NULL;
1932:
1933: err = blk_mq_alloc_tag_set(&nbd->tag_set);
1934: if (err)
1935: goto out_free_nbd;
1936:
1937: mutex_lock(&nbd_index_mutex);
1938: if (index >= 0) {
1939: err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1940: GFP_KERNEL);
1941: if (err == -ENOSPC)
1942: err = -EEXIST;
1943: } else {
1944: err = idr_alloc(&nbd_index_idr, nbd, 0,
1945: (MINORMASK >> part_shift) + 1, GFP_KERNEL);
1946: if (err >= 0)
1947: index = err;
1948: }
1949: nbd->index = index;
1950: mutex_unlock(&nbd_index_mutex);
1951: if (err < 0)
1952: goto out_free_tags;
1953:
1954: disk = blk_mq_alloc_disk(&nbd->tag_set, &lim, NULL);
1955: if (IS_ERR(disk)) {
1956: err = PTR_ERR(disk);
1957: goto out_free_idr;
1958: }
1959: nbd->disk = disk;
1960:
1961: nbd->recv_workq = alloc_workqueue("nbd%d-recv",
1962: WQ_MEM_RECLAIM | WQ_HIGHPRI |
1963: WQ_UNBOUND, 0, nbd->index);
1964: if (!nbd->recv_workq) {
1965: dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1966: err = -ENOMEM;
1967: goto out_err_disk;
1968: }
1969:
1970: mutex_init(&nbd->config_lock);
1971: refcount_set(&nbd->config_refs, 0);
1972: /*
1973: * Start out with a zero references to keep other threads from using
1974: * this device until it is fully initialized.
1975: */
1976: refcount_set(&nbd->refs, 0);
1977: INIT_LIST_HEAD(&nbd->list);
1978: disk->major = NBD_MAJOR;
1979: disk->first_minor = index << part_shift;
1980: disk->minors = 1 << part_shift;
1981: disk->fops = &nbd_fops;
1982: disk->private_data = nbd;
1983: sprintf(disk->disk_name, "nbd%d", index);
1984: err = add_disk(disk);
1985: if (err)
1986: goto out_free_work;
1987:
1988: /*
1989: * Now publish the device.
1990: */
1991: refcount_set(&nbd->refs, refs);
1992: nbd_total_devices++;
1993: return nbd;
1994:
1995: out_free_work:
1996: destroy_workqueue(nbd->recv_workq);
1997: out_err_disk:
1998: put_disk(disk);
1999: out_free_idr:
2000: mutex_lock(&nbd_index_mutex);
2001: idr_remove(&nbd_index_idr, index);
2002: mutex_unlock(&nbd_index_mutex);
2003: out_free_tags:
2004: blk_mq_free_tag_set(&nbd->tag_set);
2005: out_free_nbd:
2006: kfree(nbd);
2007: out:
2008: return ERR_PTR(err);
2009: }
SourceFile:drivers/block/nbd.c]
|
| 68/2 |
2026/05/10 03:02 |
llm |
debugger |
0m
Model:
Tokens:
input: 111640
output: 42
thoughts: 941
Thoughts: **Analyzing a Block Size Mismatch Issue**
Okay, so I'm digging into this block size issue and here's what I've got so far. We initialize `queue_limits` with some standard values, including `max_hw_sectors`, `io_opt`, `max_segments`, and `max_segment_size`. No explicit `logical_block_size` is set initially, so it defaults to 512, which is what `bdev_logical_block_size` starts at. When the `mount` syscall happens, `setup_bdev_super` sets `sb->s_blocksize` also to 512. The `udf_fill_super` function calls `udf_load_vrs`, which dutifully calls `sb_set_blocksize(sb, 512)`. This succeeds, as 512 is obviously greater than or equal to 512. Then `udf_load_vrs` proceeds normally.
Concurrently, there's an `ioctl(fd_nbd, NBD_DO_IT, 0)` call going on. This calls `nbd_start_device`, which eventually calls `nbd_set_size`. `nbd_set_size` is responsible for updating the device's block size. It is called with `nbd_blksize(config)`, which is calculated as `1u << config->blksize_bits`. Since `config->blksize_bits` is initialized to `NBD_DEF_BLKSIZE_BITS` (which is 10), then `nbd_blksize(config)` is 1024. So `nbd_set_size` updates the block device's `logical_block_size` to 1024. Now, `bdev_logical_block_size` is 1024.
Then, when `udf_read_tagged` calls `sb_bread(sb, block)`, and `sb_bread` eventually calls `__bread_gfp(sb->s_bdev, block, 512, ...)`, `__getblk_slow` triggers a warning because `512` is *not* aligned to `1024`.
So, the fundamental issue is that the block device's logical block size can change *concurrently* while the filesystem is mounting or, potentially, is running. This leads to a situation where `sb->s_blocksize` is misaligned with the current `bdev_logical_block_size(bdev)`. The question now is: is this a bug in NBD, or is it something in the VFS/UDF layers? A block device *should* not change its logical block size while it's opened exclusively, like when it's mounted. But, does `mount` open the block device exclusively?
Yes, `bdev_file_open_by_dev` does use `fs_holder_ops` to exclusively open the device. If it's opened exclusively, shouldn't NBD be prevented from changing the block size? Let's look at `nbd_set_size`. It uses `queue_limits_commit_update_frozen`, which seems to freeze the queue and update the limits. But importantly, *it doesn't check* if the block device is exclusively opened! However, when `set_blocksize` (which `sb_set_blocksize` calls) is used, it does call `bdev_validate_blocksize`. But, if the block device driver just changes the `logical_block_size` directly via `queue_limits_commit_update_frozen`, it bypasses the VFS checks.
Now the real question: is it *allowed* for a block device to change its `logical_block_size` while it's mounted? No, that's almost certainly a recipe for disaster, and it's what's leading to this warning. `nbd_set_size` gets called from `nbd_start_device`, which is triggered by the `NBD_DO_IT` ioctl. So, the question now is, can `NBD_DO_IT` be called when the device is mounted? It looks like I need to dive into `__nbd_ioctl`.
|
| 69/2 |
2026/05/10 03:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:__nbd_ioctl]
Results: map[SourceCode:1592: /* Must be called with config_lock held */
1593: static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1594: unsigned int cmd, unsigned long arg)
1595: {
1596: struct nbd_config *config = nbd->config;
1597: loff_t bytesize;
1598:
1599: switch (cmd) {
1600: case NBD_DISCONNECT:
1601: return nbd_disconnect(nbd);
1602: case NBD_CLEAR_SOCK:
1603: nbd_clear_sock_ioctl(nbd);
1604: return 0;
1605: case NBD_SET_SOCK:
1606: return nbd_add_socket(nbd, arg, false);
1607: case NBD_SET_BLKSIZE:
1608: return nbd_set_size(nbd, config->bytesize, arg);
1609: case NBD_SET_SIZE:
1610: return nbd_set_size(nbd, arg, nbd_blksize(config));
1611: case NBD_SET_SIZE_BLOCKS:
1612: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1613: return -EINVAL;
1614: return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1615: case NBD_SET_TIMEOUT:
1616: nbd_set_cmd_timeout(nbd, arg);
1617: return 0;
1618:
1619: case NBD_SET_FLAGS:
1620: config->flags = arg;
1621: return 0;
1622: case NBD_DO_IT:
1623: return nbd_start_device_ioctl(nbd);
1624: case NBD_CLEAR_QUE:
1625: /*
1626: * This is for compatibility only. The queue is always cleared
1627: * by NBD_DO_IT or NBD_CLEAR_SOCK.
1628: */
1629: return 0;
1630: case NBD_PRINT_DEBUG:
1631: /*
1632: * For compatibility only, we no longer keep a list of
1633: * outstanding requests.
1634: */
1635: return 0;
1636: }
1637: return -ENOTTY;
1638: }
SourceFile:drivers/block/nbd.c]
|
| 70/2 |
2026/05/10 03:02 |
llm |
debugger |
0m
Model:
Tokens:
input: 114307
output: 45
thoughts: 1079
Thoughts: **Analyzing the NBD Device and UDF Filesystem Vulnerability**
Okay, let's break this down. First, I'm confirming that `nbd_ioctl` is indeed the ioctl handler for the NBD block device. And, the device can be accessed with ioctls even when mounted, as long as it isn't opened with `O_EXCL`.
The reproducer shows a specific sequence: it opens the device, calls `NBD_SET_SOCK`, then `NBD_DO_IT`, and *then* the `mount` syscall. The critical observation is that `NBD_DO_IT` comes *before* the mount. I need to verify that order in the reproducer as that's my main point of focus. Yes, I see that the order is `NBD_SET_SOCK` then `NBD_DO_IT` then `mount`.
So, `nbd_start_device` is called *before* the mount operation. Consequently, `nbd_start_device` sets `logical_block_size` to 1024 before the filesystem is mounted. The subsequent `mount` system call leads to `setup_bdev_super`, which calls `sb_set_blocksize` with `block_size(bdev)` set to 1024 (derived from the `logical_block_size`). This means `sb->s_blocksize` is also 1024.
Then, `udf_fill_super` is called, specifically `udf_load_vrs`. In `udf_fill_super`, it checks if the block size is set. If not, it sets `uopt->blocksize` to `bdev_logical_block_size(sb->s_bdev)`. In our case, this is also 1024. So `uopt->blocksize` begins at 1024 and `udf_load_vrs` calls `sb_set_blocksize(sb, 1024)`. This *succeeds* because the block size is 1024 for both the device and the superblock. Then it proceeds, which is expected. With `sb->s_blocksize` and `bdev_logical_block_size` both 1024, `IS_ALIGNED(1024, 1024)` is clearly true, yet there's a warning, that I need to clarify.
Why does the warning trigger? It shouldn't, based on the current logic.
Now I'm looking back at the crash log. The warning message, `fs/buffer.c:1029`, within `__getblk_slow`. It suggests an issue within the buffer cache.
A key point I'm missing is that `NBD_DO_IT` *blocks*. It calls `nbd_start_device_ioctl`, which calls `nbd_start_device`. `nbd_start_device` *waits* for the device to disconnect or an error! That must be an important factor. Let me check the code.
|
| 71/2 |
2026/05/10 03:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device_ioctl]
Results: map[SourceCode:1543: static int nbd_start_device_ioctl(struct nbd_device *nbd)
1544: {
1545: struct nbd_config *config = nbd->config;
1546: int ret;
1547:
1548: ret = nbd_start_device(nbd);
1549: if (ret)
1550: return ret;
1551:
1552: if (max_part)
1553: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1554: mutex_unlock(&nbd->config_lock);
1555: ret = wait_event_interruptible(config->recv_wq,
1556: atomic_read(&config->recv_threads) == 0);
1557: if (ret) {
1558: sock_shutdown(nbd);
1559: nbd_clear_que(nbd);
1560: }
1561:
1562: flush_workqueue(nbd->recv_workq);
1563: mutex_lock(&nbd->config_lock);
1564: nbd_bdev_reset(nbd);
1565: /* user requested, ignore socket errors */
1566: if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1567: ret = 0;
1568: if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1569: ret = -ETIMEDOUT;
1570: return ret;
1571: }
SourceFile:drivers/block/nbd.c]
|
| 72/2 |
2026/05/10 03:02 |
llm |
debugger |
0m
Model:
Tokens:
input: 116596
output: 44
thoughts: 1129
Thoughts: **Analyzing the NBD Device Reproducer**
Okay, so I'm looking at this reproducer, and my initial thought is that `NBD_DO_IT` blocks until the device disconnects, right? But the key here is that it's *multi-threaded*! I need to consider how this threading impacts the sequence of events. Let's break down this C code:
```c
syscall(__NR_ioctl, /*fd=*/r[0], /*cmd=*/0xab00, /*arg=*/r[1]);
syscall(__NR_ioctl, /*fd=*/r[2], /*cmd=*/0xab03, 0);
syscall(__NR_mount, /*src=*/0x200000000000ul, /*dst=*/0x200000004a00ul, /*type=*/0x200000000080ul, /*flags=MS_LAZYTIME|MS_SILENT|MS_RDONLY|MS_NOSUID|MS_NODEV|0x80*/0x2008087ul, /*data=*/0ul);
```
Right, the `syscall(__NR_ioctl, ...)` calls, if they block, would mean `mount` is *not* called until `NBD_DO_IT` returns. But wait... if `NBD_DO_IT` *blocks*, how does `mount` ever get called? The key is that `NBD_DO_IT` might return immediately if there's an error. For instance, if `nbd_start_device` fails, `NBD_DO_IT` will return right away. Or if `wait_event_interruptible` is interrupted by a signal, it'll return `-ERESTARTSYS`. Even if the socket is closed, `recv_threads` will become 0 and `NBD_DO_IT` will return.
Let's look at the file descriptors being used. `syz_open_dev` is used to open `/dev/nbd#`. `r[0]` is the `fd_nbd`, and `r[1]` is the socket. So `ioctl(r[0], NBD_SET_SOCK, r[1])` is setting the socket, and `ioctl(r[2], NBD_DO_IT, 0)` is the call that *starts* the device. And, crucial point, `r[2]` is *another* file descriptor for the *same* NBD device!
```c
res = syz_open_dev(/*dev=*/0x2000000000c0, /*id=*/0, /*flags=O_CLOEXEC*/0x80000);
if (res != -1)
r[0] = res;
res = syscall(__NR_socket, /*domain=AF_INET*/2ul, /*type=SOCK_STREAM*/1ul, /*proto=*/0);
if (res != -1)
r[1] = res;
res = syz_open_dev(/*dev=*/0x200000000000, /*id=*/0, /*flags=*/0);
if (res != -1)
r[2] = res;
```
Okay, so `r[0]` and `r[2]` are both `/dev/nbd0`.
I see, if `NBD_DO_IT` *blocks*, `mount` won't execute! But, given `syzkaller` and its multithreaded design, I need to consider that the tools are probably executing these system calls in separate threads to allow for blocking. But no, the generated C code *does* execute them sequentially. So if `NBD_DO_IT` blocks, `mount` is *not* reached.
But the key is, `NBD_DO_IT` might fail and return immediately. What would cause that? If `nbd_start_device` fails, it returns an error. The important point is, if it fails, it does *not* change the block size.
Here's the critical insight: what if `NBD_DO_IT` *succeeds* initially, but the socket is closed *immediately* because the other end of the socket isn't connected? The code creates an unconnected socket using `socket(AF_INET, SOCK_STREAM, 0)`. Then, in the `recv_work` function, it calls `sock_xmit`
|
| 73/2 |
2026/05/10 03:03 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_bdev_reset]
Results: map[SourceCode:1375: static void nbd_bdev_reset(struct nbd_device *nbd)
1376: {
1377: if (disk_openers(nbd->disk) > 1)
1378: return;
1379: set_capacity(nbd->disk, 0);
1380: }
SourceFile:drivers/block/nbd.c]
|
| 74/2 |
2026/05/10 03:03 |
llm |
debugger |
0m
Model:
Tokens:
input: 118918
output: 40
thoughts: 140
Thoughts: **Analyzing the Block Device Reset and Mounting Process**
Okay, hold on a second. I'm focusing on `nbd_bdev_reset` and just realized something critical. It *only* sets the capacity of the block device to zero. It *doesn't* touch the `logical_block_size`! So, even after the reset, `logical_block_size` is still 1024. That's a huge potential gotcha.
Then, the system calls `mount`. During the `mount` procedure, `setup_bdev_super` gets invoked, and within that, `sb_set_blocksize(sb, block_size(bdev))` is called. This is where things get interesting. I need to be sure the block size is correct because that can really affect performance.
Let me think…`block_size(bdev)` retrieves the block size of the block device, obviously. But I need to be absolutely certain of its behavior in this scenario, especially given the reset. The documentation isn't always reliable.
I'm going to have to check the definition of `block_size` directly. Let's look in `include/linux/blkdev.h`. I want to know exactly what that function returns, specifically in this context, after the reset. I need to be very precise here.
|
| 75/2 |
2026/05/10 03:03 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/blkdev.h IncludeLines:true Name:block_size]
Results: map[SourceCode:1361: unsigned int block_size(struct block_device *bdev)
1362: {
1363: return 1 << BD_INODE(bdev)->i_blkbits;
1364: }
SourceFile:block/bdev.c]
|
| 76/2 |
2026/05/10 03:03 |
llm |
debugger |
0m
Model:
Tokens:
input: 119475
output: 41
thoughts: 253
Thoughts: **Analyzing Block Size Determination**
Okay, so `block_size(bdev)` uses `1 << BD_INODE(bdev)->i_blkbits` to determine the block size. I need to figure out what `i_blkbits` represents. Ah, it's the block size of the block device's inode. That makes sense. Now, when is this value updated? Let's see... `set_blocksize(bdev_file, size)` is responsible for that.
Right, how is this handled with the NBD driver? `nbd_set_size` calls `blk_queue_logical_block_size(nbd->disk->queue, blksize)`. My instinct tells me this is the key to understanding how we determine size, but does that function actually update *our* inode's `i_blkbits`? I don't think so... Let me double-check.
No! It looks like `blk_queue_logical_block_size` only affects `q->limits.logical_block_size`. It doesn't modify `BD_INODE(bdev)->i_blkbits` at all. This means, if the block size isn't otherwise specified, `BD_INODE(bdev)->i_blkbits` must remain at its initial value of 9, meaning 512 bytes, since that's how it's initialized. Hmm, I should verify how we initialize these values. Let me look at `set_init_blocksize` in `block/bdev.c`.
|
| 77/2 |
2026/05/10 03:03 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:set_init_blocksize]
Results: map[SourceCode: 140: static void set_init_blocksize(struct block_device *bdev)
141: {
142: unsigned int bsize = bdev_logical_block_size(bdev);
143: loff_t size = i_size_read(BD_INODE(bdev));
144:
145: while (bsize < PAGE_SIZE) {
146: if (size & bsize)
147: break;
148: bsize <<= 1;
149: }
150: BD_INODE(bdev)->i_blkbits = blksize_bits(bsize);
151: mapping_set_folio_min_order(BD_INODE(bdev)->i_mapping,
152: get_order(bsize));
153: }
SourceFile:block/bdev.c]
|
| 78/2 |
2026/05/10 03:03 |
llm |
debugger |
0m
Model:
Tokens:
input: 120368
output: 39
thoughts: 69
Thoughts: Here's my thought process, as it flows through my mind:
**Tracing Block Device Initialization**
Okay, so `set_init_blocksize` is triggered when a block device gets opened. But I need to follow the actual call chain here. Let's see... `bdev_file_open_by_dev` is the function that handles opening the file using its device number, which calls `blkdev_get_by_dev`. That sounds right, and *that* then calls `bdev_open`. So, the question is, does `bdev_open` then itself call `set_init_blocksize`? I need to check the code in `bdev_open` to confirm.
|
| 79/2 |
2026/05/10 03:03 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:bdev_open]
Results: map[SourceCode: 917: /**
918: * bdev_open - open a block device
919: * @bdev: block device to open
920: * @mode: open mode (BLK_OPEN_*)
921: * @holder: exclusive holder identifier
922: * @hops: holder operations
923: * @bdev_file: file for the block device
924: *
925: * Open the block device. If @holder is not %NULL, the block device is opened
926: * with exclusive access. Exclusive opens may nest for the same @holder.
927: *
928: * CONTEXT:
929: * Might sleep.
930: *
931: * RETURNS:
932: * zero on success, -errno on failure.
933: */
934: int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
935: const struct blk_holder_ops *hops, struct file *bdev_file)
936: {
937: bool unblock_events = true;
938: struct gendisk *disk = bdev->bd_disk;
939: int ret;
940:
941: if (holder) {
942: mode |= BLK_OPEN_EXCL;
943: ret = bd_prepare_to_claim(bdev, holder, hops);
944: if (ret)
945: return ret;
946: } else {
947: if (WARN_ON_ONCE(mode & BLK_OPEN_EXCL))
948: return -EIO;
949: }
950:
951: disk_block_events(disk);
952:
953: mutex_lock(&disk->open_mutex);
954: ret = -ENXIO;
955: if (!disk_live(disk))
956: goto abort_claiming;
957: if (!try_module_get(disk->fops->owner))
958: goto abort_claiming;
959: ret = -EBUSY;
960: if (!bdev_may_open(bdev, mode))
961: goto put_module;
962: if (bdev_is_partition(bdev))
963: ret = blkdev_get_part(bdev, mode);
964: else
965: ret = blkdev_get_whole(bdev, mode);
966: if (ret)
967: goto put_module;
968: bdev_claim_write_access(bdev, mode);
969: if (holder) {
970: bd_finish_claiming(bdev, holder, hops);
971:
972: /*
973: * Block event polling for write claims if requested. Any write
974: * holder makes the write_holder state stick until all are
975: * released. This is good enough and tracking individual
976: * writeable reference is too fragile given the way @mode is
977: * used in blkdev_get/put().
978: */
979: if ((mode & BLK_OPEN_WRITE) &&
980: !bdev_test_flag(bdev, BD_WRITE_HOLDER) &&
981: (disk->event_flags & DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE)) {
982: bdev_set_flag(bdev, BD_WRITE_HOLDER);
983: unblock_events = false;
984: }
985: }
986: mutex_unlock(&disk->open_mutex);
987:
988: if (unblock_events)
989: disk_unblock_events(disk);
990:
991: bdev_file->f_flags |= O_LARGEFILE;
992: bdev_file->f_mode |= FMODE_CAN_ODIRECT;
993: if (bdev_nowait(bdev))
994: bdev_file->f_mode |= FMODE_NOWAIT;
995: if (mode & BLK_OPEN_RESTRICT_WRITES)
996: bdev_file->f_mode |= FMODE_WRITE_RESTRICTED;
997: bdev_file->f_mapping = bdev->bd_mapping;
998: bdev_file->f_wb_err = filemap_sample_wb_err(bdev_file->f_mapping);
999: bdev_file->private_data = holder;
1000:
1001: return 0;
1002: put_module:
1003: module_put(disk->fops->owner);
1004: abort_claiming:
1005: if (holder)
1006: bd_abort_claiming(bdev, holder);
1007: mutex_unlock(&disk->open_mutex);
1008: disk_unblock_events(disk);
1009: return ret;
1010: }
SourceFile:block/bdev.c]
|
| 80/2 |
2026/05/10 03:03 |
llm |
debugger |
0m
Model:
Tokens:
input: 122118
output: 39
thoughts: 20
Thoughts: Here's my thought process, as if I were the one thinking it:
**A Realization About Block Size Initialization**
Okay, wait a minute... I'm tracing through this code, trying to understand the initialization process for the block device. And *boom*! It just hit me. `set_init_blocksize` is actually called from within `bdev_alloc`! I didn't see that initially. That's a key point. This means the block size setting, the very fundamental unit of how we interact with storage, is being handled at the allocation stage itself. I need to re-evaluate my mental model of the bdev initialization sequence; this impacts its fundamental assumptions. Now, what does this implication mean?
|
| 81/2 |
2026/05/10 03:03 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:bdev_alloc]
Results: map[SourceCode: 464: struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
465: {
466: struct block_device *bdev;
467: struct inode *inode;
468:
469: inode = new_inode(blockdev_superblock);
470: if (!inode)
471: return NULL;
472: inode->i_mode = S_IFBLK;
473: inode->i_rdev = 0;
474: inode->i_data.a_ops = &def_blk_aops;
475: mapping_set_gfp_mask(&inode->i_data, GFP_USER);
476:
477: bdev = I_BDEV(inode);
478: mutex_init(&bdev->bd_fsfreeze_mutex);
479: spin_lock_init(&bdev->bd_size_lock);
480: mutex_init(&bdev->bd_holder_lock);
481: atomic_set(&bdev->__bd_flags, partno);
482: bdev->bd_mapping = &inode->i_data;
483: bdev->bd_queue = disk->queue;
484: if (partno && bdev_test_flag(disk->part0, BD_HAS_SUBMIT_BIO))
485: bdev_set_flag(bdev, BD_HAS_SUBMIT_BIO);
486: bdev->bd_stats = alloc_percpu(struct disk_stats);
487: if (!bdev->bd_stats) {
488: iput(inode);
489: return NULL;
490: }
491: bdev->bd_disk = disk;
492: return bdev;
493: }
SourceFile:block/bdev.c]
|
| 82/2 |
2026/05/10 03:03 |
llm |
debugger |
0m
Model:
Tokens:
input: 122868
output: 20
thoughts: 44
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Debugging a Bdev Block Size Initialization**
Hmm, hold on a second. I was under the impression that `set_init_blocksize` was invoked directly from within `bdev_alloc`. But that doesn't seem right. Let me just double-check my assumptions here. I need to be absolutely certain of the initialization flow.
Right, I'm going to quickly search for every instance of `set_init_blocksize` within `block/bdev.c`. I need to figure out exactly where this function *is* called from, and understand the calling context to pinpoint where and how the block size is being initially set. I suspect there may be some indirect calls or potential race conditions that I'm overlooking. Let's see what the code reveals.
|
| 83/2 |
2026/05/10 03:03 |
tool |
grepper |
0m
Args: map[Expression:set_init_blocksize]
Results: map[Output:block/bdev.c=111=int truncate_bdev_range(struct block_device *bdev, blk_mode_t mode,
--
block/bdev.c-139-
block/bdev.c:140:static void set_init_blocksize(struct block_device *bdev)
block/bdev.c-141-{
--
block/bdev.c=732=static int blkdev_get_whole(struct block_device *bdev, blk_mode_t mode)
--
block/bdev.c-748- if (!atomic_read(&bdev->bd_openers))
block/bdev.c:749: set_init_blocksize(bdev);
block/bdev.c-750- atomic_inc(&bdev->bd_openers);
--
block/bdev.c=765=static int blkdev_get_part(struct block_device *part, blk_mode_t mode)
--
block/bdev.c-779- disk->open_partitions++;
block/bdev.c:780: set_init_blocksize(part);
block/bdev.c-781- }
]
|
| 84/2 |
2026/05/10 03:03 |
llm |
debugger |
0m
Model:
Tokens:
input: 123429
output: 45
thoughts: 3036
Thoughts: **Root Cause Analysis of the Block Size Mismatch in NBD and UDF Filesystems**
Okay, so here's the deal. I've been tracing through this nbd and udf interaction, and I think I've got it. It boils down to a race condition and a block size mismatch. Here's the sequence: we've got `set_init_blocksize` being called from `blkdev_get_whole` and `blkdev_get_part` when the device is opened for the *first* time (remember `bd_openers` being zero initially). The `mount` command triggers `blkdev_get_whole`, which calls `set_init_blocksize(bdev)`. At this point, `i_blkbits` is determined by `bdev_logical_block_size()`. If that size is 512, which is what it starts at, `i_blkbits` gets set to 9. Then, `setup_bdev_super` calls `sb_set_blocksize(sb, block_size(bdev))`, and the superblock's size is set to 512. So far, so good. UDF then calls `udf_load_vrs` which again calls `sb_set_blocksize(sb, 512)`. That also succeeds.
Then, here is where it gets interesting: concurrently, `NBD_DO_IT` is executed. This initiates `nbd_start_device`, which eventually changes the `logical_block_size` to 1024 through the `queue_limits_commit_update_frozen` function. Now, `bdev_logical_block_size(bdev)` is 1024, but critically, `sb->s_blocksize` *remains* 512. Later, UDF's `udf_read_tagged` calls `sb_bread(sb, block)`. This, in turn, calls `__bread_gfp(sb->s_bdev, block, 512, ...)`. `__getblk_slow` then performs an alignment check using `WARN_ON_ONCE(!IS_ALIGNED(512, 1024))`. Boom! Since 512 is not a multiple of 1024, the warning triggers.
The core issue is `nbd_set_size` modifying the logical block size of the device *while* it's mounted. Normally, `NBD_DO_IT` should happen before `mount`. In that case, the block size would be 1024 *before* the mount. However, the reproducer's setup calls them concurrently, and that's the key. The C code from syzkaller isn't the problem, it's the fact that `NBD_DO_IT` doesn't block due to the socket being immediately disconnected, so the change in size *can* happen while mount has already set the filesystem block size to 512. Specifically: `NBD_DO_IT` uses the `wait_event_interruptible(config->recv_wq, atomic_read(&config->recv_threads) == 0)` call, but this wakes up almost immediately, due to the disconnected socket. This permits the race.
So, here's the exact race:
1. **Thread A**: `NBD_DO_IT` ioctl. `nbd_set_size` changes `logical_block_size` to 1024. `nbd_start_device` completes without blocking due to the disconnected socket.
2. **Thread B**: `mount`. It opens the device, *before* Thread A can block, sees the old size of 512, sets `sb->s_blocksize` to 512.
3. Thread B reads the super block and issues a read for 512 bytes, while the logical block size is now 1024. The misalignment error is triggered.
The crux is `nbd_start_device` *must* finish setting the new size *before* `mount` is called, but it doesn't, causing the mismatch. The solution requires adding checks within `NBD_DO_IT` to prevent size changes on mounted devices.
|
| 85/2 |
2026/05/10 03:04 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_clear_sock_ioctl]
Results: map[SourceCode:1573: static void nbd_clear_sock_ioctl(struct nbd_device *nbd)
1574: {
1575: nbd_clear_sock(nbd);
1576: disk_force_media_change(nbd->disk);
1577: nbd_bdev_reset(nbd);
1578: if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1579: &nbd->config->runtime_flags))
1580: nbd_config_put(nbd);
1581: }
SourceFile:drivers/block/nbd.c]
|
| 86/2 |
2026/05/10 03:04 |
llm |
debugger |
0m
Model:
Tokens:
input: 127640
output: 41
thoughts: 1424
Thoughts: **Analyzing the Block Size and Mount Issues**
Okay, let's break this down. First, `nbd_config_put` frees the config, got it. But `nbd_start_device_ioctl` doesn't free the config when it returns. That means `config->blksize_bits` is still 10. And when `NBD_DO_IT` returns, the device disconnects, right? The key is what happens with the block size during this process, especially *before* mount gets called.
So, the device is disconnected, then `mount` is called. `mount` opens the device. It sees `bdev_logical_block_size` as 1024, so `sb->s_blocksize` is set to 1024. Then, `udf_fill_super` calls `udf_load_vrs`, which in turn calls `sb_set_blocksize(sb, 1024)`. Everything works as expected. And if `sb->s_blocksize` is 1024, the `IS_ALIGNED(1024, 1024)` check in `__getblk_slow` succeeds, so the warning shouldn't trigger.
But wait, what if `udf_fill_super` *tries* to mount with a 512-byte block size? Looking at that code, if the flag `UDF_FLAG_BLOCKSIZE_SET` isn't set, then `uopt->blocksize` is initialized to `bdev_logical_block_size(sb->s_bdev)`. And since `bdev_logical_block_size` is 1024 at that point, it'll try 1024, 2048, and 4096. It will NEVER try 512. So, `sb->s_blocksize` *will* be 1024, 2048, or 4096. They are all aligned to 1024. Therefore, the warning *cannot* trigger if `bdev_logical_block_size` is 1024 before `mount`!
This means `bdev_logical_block_size` *must* be 512 at the beginning of `mount`, and then change to 1024 *after*! The critical question is, how does the block size change *after* `mount` starts? The only thing that could cause that change would be `NBD_DO_IT` being called *after* mount starts! But, the C code calls `NBD_DO_IT` *before* mount! The key is the call itself `syscall(__NR_ioctl, /*fd=*/r[2], /*cmd=*/0xab03, 0);`. That's `NBD_DO_IT`.
Does `NBD_DO_IT` run asynchronously? No, it blocks. Could `NBD_DO_IT` be interrupted by a signal? If it's interrupted, it returns `-ERESTARTSYS`. But there are no signals in the C code. So, that's not it.
What if `NBD_DO_IT` is called in a separate thread? The syzkaller generated C code might be simplified. Syzkaller executes syscalls in separate threads if they are known to block, or it just executes them sequentially. So, does `syzkaller` execute each syscall in a separate thread, or does it run them sequentially? The issue here is if `NBD_DO_IT` blocks in a sequential execution, then other syscalls don't run until it returns. So, we established that `NBD_DO_IT` returns almost immediately. This is the issue. If it returns immediately, `mount` is executed after `NBD_DO_IT` returns. If `mount` runs after `NBD_DO_IT` returns, the `logical_block_size` is already 1024! So, `mount` would see 1024 and no warning!
Okay, is `logical_block_size` reset to 512 when `NBD_DO_IT` returns? Let's check `nbd_bdev_reset`.
```c
static void nbd_bdev_reset(struct nbd_device *nbd)
{
if (disk_openers(nbd->disk) > 1)
return;
set_capacity(nbd->disk, 0);
}
```
This doesn't reset `logical_block_size`.
What happens if the device
|
| 87/2 |
2026/05/10 03:04 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_release]
Results: map[SourceCode:1748: static void nbd_release(struct gendisk *disk)
1749: {
1750: struct nbd_device *nbd = disk->private_data;
1751:
1752: if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1753: disk_openers(disk) == 0)
1754: nbd_disconnect_and_put(nbd);
1755:
1756: nbd_config_put(nbd);
1757: nbd_put(nbd);
1758: }
SourceFile:drivers/block/nbd.c]
|
| 88/2 |
2026/05/10 03:04 |
llm |
debugger |
0m
Model:
Tokens:
input: 130338
output: 43
thoughts: 145
Thoughts: **My Analysis of `nbd_config_put` and its Implications**
Okay, so `nbd_config_put` is all about managing the lifetime of a network block device's configuration. It looks like it's responsible for decrementing a reference count (`nbd->config_refs`) associated with the config. The key here is that if that reference count hits zero, it means no one is using the configuration anymore, and *bam!* it's freed. The function uses `refcount_dec_and_mutex_lock`, which tells me this is thread-safe, so multiple parts of the system can safely manage the config's lifetime.
The interesting part is *what* happens when the refcount hits zero. It calls `nbd_dev_dbg_close` and, more importantly, `nbd_size_clear(nbd)`. The `nbd_dev_dbg_close` is probably just some debug logging or cleanup function specific to the device. However, `nbd_size_clear`... that *really* jumps out at me. I need to take a look at what *that* function does. It is important to know the flow to know how the config is released, and how it effects the device size. I need to understand that call to know how this impacts the device size management and any possible side effects during the cleanup process. Let me check what that actually does...
|
| 89/2 |
2026/05/10 03:04 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_size_clear]
Results: map[SourceCode: SourceFile:]
|
| 90/2 |
2026/05/10 03:04 |
llm |
debugger |
0m
Model:
Tokens:
input: 130849
output: 20
thoughts: 24
Thoughts: Here's my thought process, summarized as you requested:
**Navigating the NBD Driver Codebase**
Okay, so I need to find where the `nbd_size_clear` function is defined and used within the Network Block Device (NBD) driver. My immediate thought is to start within the core NBD code, so I'll begin by looking directly in `drivers/block/nbd.c`. This is the logical place to start digging since it's the central file for the driver. I expect to find the function declaration and its implementations there, and, hopefully, a glimpse of the function call hierarchy. I'll be looking for cross-references and usage patterns once I locate it. This will give me a better understanding of how the size clearing is managed within the overall NBD framework.
|
| 91/2 |
2026/05/10 03:05 |
tool |
grepper |
0m
Error:
Args: map[Expression:nbd_size_clear]
Results:
|
| 92/2 |
2026/05/10 03:05 |
llm |
debugger |
0m
Model:
Tokens:
input: 131078
output: 43
thoughts: 23
Thoughts: Here's my thought process, summarized as if I were considering the code:
**Checking My Assumptions**
Okay, hold on a second. I think I jumped the gun there. My initial read of the code might have been off, or maybe I was just making an educated guess based on context. Let's not assume anything. The key function here is `nbd_config_put`. I need to go back and verify exactly what that function does, and how it's interacting with the rest of the system. I need a concrete understanding before I commit to any assumptions about the problem. Let's dig into the details and make sure I'm on the right track.
|
| 93/2 |
2026/05/10 03:05 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_config_put]
Results: map[SourceCode:1432: static void nbd_config_put(struct nbd_device *nbd)
1433: {
1434: if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1435: &nbd->config_lock)) {
1436: struct nbd_config *config = nbd->config;
1437: nbd_dev_dbg_close(nbd);
1438: invalidate_disk(nbd->disk);
1439: if (nbd->config->bytesize)
1440: kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
1441: if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1442: &config->runtime_flags))
1443: device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1444: nbd->pid = 0;
1445: if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1446: &config->runtime_flags)) {
1447: device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1448: kfree(nbd->backend);
1449: nbd->backend = NULL;
1450: }
1451: nbd_clear_sock(nbd);
1452: if (config->num_connections) {
1453: int i;
1454: for (i = 0; i < config->num_connections; i++) {
1455: sockfd_put(config->socks[i]->sock);
1456: kfree(config->socks[i]);
1457: }
1458: kfree(config->socks);
1459: }
1460: kfree(nbd->config);
1461: nbd->config = NULL;
1462:
1463: nbd->tag_set.timeout = 0;
1464:
1465: mutex_unlock(&nbd->config_lock);
1466: nbd_put(nbd);
1467: module_put(THIS_MODULE);
1468: }
1469: }
SourceFile:drivers/block/nbd.c]
|
| 94/2 |
2026/05/10 03:05 |
llm |
debugger |
1m
Model:
Tokens:
input: 131953
output: 43
thoughts: 12113
Thoughts: **Race Condition in NBD Block Size Update**
Okay, so I've been wrestling with this NBD issue, and here's what I've figured out. `nbd_config_put` calls `invalidate_disk`, but that doesn't seem to touch the `logical_block_size`. `nbd_set_size`, that's the key. It *does* set it. But where is it reset? I went through `nbd_clear_sock_ioctl`, but that just forces a media change which increments the event counter.
The default block size is 1024, not 512, because if `blksize = 0`, it defaults to `1u << NBD_DEF_BLKSIZE_BITS`. However, `blk_mq_alloc_disk` sets it to 512 during device init. So initially it is 512. After the device is set up by `nbd_set_size`, it should be 1024. If mount is called BEFORE `NBD_DO_IT` it sees 512, after it sees 1024. The crux is that `NBD_DO_IT` is not synchronous. It calls `nbd_start_device` which calls `nbd_set_size`.
If `nbd_start_device` returns an error (which it does not in the crashlog), `nbd_set_size` will not be called.
So I dug into `nbd_start_device`. It creates `recv_thread_args` and queues them. But in a successful run, it also calls `nbd_set_size`. So even with the threads, the `logical_block_size` gets set to 1024 before the `mount` is called. The crash happens only if we can find a way to make `mount` see 512 and then `__getblk_slow` see 1024, and the only way is if the `logical_block_size` changes. This should not be happening if the operations are sequential as shown in the C code, so there must be concurrent access.
I then check `nbd_bdev_reset`, but that only happens when the device has only 1 opener. With the two fds in the reproducers it won't be called.
Looking at the syzkaller reproducer, it appears single-threaded, which SHOULD mean the block size is set to 1024 before mount is called. So, the warning shouldn't trigger.
Then, I looked at the UDF filesystem code within mount, specifically at `udf_fill_super`. This is where block size is initialized and it loops, calling `udf_load_vrs`. It uses `bdev_logical_block_size` for that, so it checks for a minimum block size. So, the loop uses 512, 1024, 2048, and 4096. No matter which size, if all sizes are aligned to `bdev_logical_block_size`, then `IS_ALIGNED` should be true.
So, when `udf_load_vrs` finds a block size of 512 it works. However, the crux is that it can only succeed if `bdev_logical_block_size` is 512.
The `__getblk_slow` function triggers the warning and that calls `IS_ALIGNED(size, bdev_logical_block_size(bdev))`. The `size` in `__getblk_slow` is `sb->s_blocksize` which comes from `sb_bread`. But `bdev_logical_block_size(bdev)` comes from the block device. So, the warning occurs because `sb->s_blocksize` is not aligned to `bdev_logical_block_size(bdev)`. I think I'm on the right track here!
So how does `bdev_logical_block_size` change? `nbd_set_size` is the culprit. We know `NBD_DO_IT` calls `nbd_set_size`.
The syzkaller reproducer *does* use `/dev/nbd0` for both ioctl and mount. So it's the same device. If NBD_DO_IT returns immediately, `logical_block_size` should be 1024. `disk_openers` is 2. `nbd_bdev_reset` returns immediately. If `NBD_DO_IT` fails, it returns before the block size is updated. So if `
|
| 95/2 |
2026/05/10 03:06 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/loop.c IncludeLines:true Name:loop_set_block_size]
Results: map[SourceCode:1445: static int loop_set_block_size(struct loop_device *lo, blk_mode_t mode,
1446: struct block_device *bdev, unsigned long arg)
1447: {
1448: struct queue_limits lim;
1449: unsigned int memflags;
1450: int err = 0;
1451:
1452: /*
1453: * If we don't hold exclusive handle for the device, upgrade to it
1454: * here to avoid changing device under exclusive owner.
1455: */
1456: if (!(mode & BLK_OPEN_EXCL)) {
1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
1458: if (err)
1459: return err;
1460: }
1461:
1462: err = mutex_lock_killable(&lo->lo_mutex);
1463: if (err)
1464: goto abort_claim;
1465:
1466: if (lo->lo_state != Lo_bound) {
1467: err = -ENXIO;
1468: goto unlock;
1469: }
1470:
1471: if (lo->lo_queue->limits.logical_block_size == arg)
1472: goto unlock;
1473:
1474: sync_blockdev(lo->lo_device);
1475: invalidate_bdev(lo->lo_device);
1476:
1477: lim = queue_limits_start_update(lo->lo_queue);
1478: loop_update_limits(lo, &lim, arg);
1479:
1480: memflags = blk_mq_freeze_queue(lo->lo_queue);
1481: err = queue_limits_commit_update(lo->lo_queue, &lim);
1482: loop_update_dio(lo);
1483: blk_mq_unfreeze_queue(lo->lo_queue, memflags);
1484:
1485: unlock:
1486: mutex_unlock(&lo->lo_mutex);
1487: abort_claim:
1488: if (!(mode & BLK_OPEN_EXCL))
1489: bd_abort_claiming(bdev, loop_set_block_size);
1490: return err;
1491: }
SourceFile:drivers/block/loop.c]
|
| 96/2 |
2026/05/10 03:06 |
llm |
debugger |
0m
Model:
Tokens:
input: 145853
output: 43
thoughts: 1007
Thoughts: **Analyzing the NBD Block Size Change Vulnerability**
Okay, so I'm digging into this `loop_set_block_size` function, and it's pretty straightforward: it refuses to change the block size if the block device is already claimed, like when mounted. That's good, prevents obvious issues.
But then I see `nbd_set_size`, and it doesn't have this same check! This is concerning. `nbd_set_size` is called from `nbd_start_device` (through `NBD_DO_IT`) and via the `NBD_SET_BLKSIZE` ioctl. Looking at the `__nbd_ioctl` code for `NBD_SET_BLKSIZE`, it simply calls `nbd_set_size` directly. If the device is mounted, using `NBD_SET_BLKSIZE` would allow changing the block size while in use.
However, a closer look shows that `NBD_SET_BLKSIZE` *only* updates `config->blksize_bits` when `nbd->pid` is 0. If the device isn't started (`nbd->pid == 0`), it just sets the config, and returns. If it *is* started (`nbd->pid != 0`), it updates the queue limits.
So, if the device isn't started initially, `NBD_SET_BLKSIZE` doesn't touch the queue limits. Then, we call `mount` and it uses the *old* queue limits (512). Afterward, `NBD_DO_IT` is called. It starts the device, calls `nbd_set_size`, *and* updates the queue limits to the newly configured block size! Effectively, `NBD_DO_IT` is changing the queue limits after the device *might* be mounted, which is the problem.
I was thinking, should `NBD_DO_IT` be checking for exclusive access? Typically, you configure an NBD device (socket, block size, etc.) and *then* call `NBD_DO_IT`. The device is unusable once `NBD_DO_IT` returns (when it disconnects). `NBD_DO_IT` blocks until the device disconnects, meaning it's active and mountable during that blocking period. So, `mount` is usually called *after* `NBD_DO_IT` has finished, because you call it in another terminal or thread. If `mount` is called *after* `NBD_DO_IT` starts the device, `nbd_set_size` is already called and the queue limits are already updated, meaning `mount` sees the correct block size.
But, if `mount` is called *before* `NBD_DO_IT`? If the device *isn't* started, can you even mount it? Yes, `mount` opens the block device `/dev/nbd0`. `mount` then tries to read the superblock. Since it's not started, reads fail with an I/O error. However, `mount` still opens the device and sets `sb->s_blocksize` based on the current `logical_block_size` (which is still 512). After this, `NBD_DO_IT` is called. It starts the device, changing `logical_block_size` to 1024. Now, the potential vulnerability happens: `mount`, which might be retrying or reading other blocks, might call `sb_bread` with a size of 512, which triggers the warning.
So, what happens if `mount` tries to read before the device is started? The read fails, so `udf_read_tagged` returns NULL. This might make `udf_load_vrs` fail. But then, what if `mount` gets blocked in `sb_bread`? However, `sb_bread` does not block indefinitely if the device isn't started, it just returns an I/O error. I need to make sure this is what is actually happening. Time to check `nbd_queue_rq`!
|
| 97/2 |
2026/05/10 03:06 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_queue_rq]
Results: map[SourceCode:1184: static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1185: const struct blk_mq_queue_data *bd)
1186: {
1187: struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1188: blk_status_t ret;
1189:
1190: /*
1191: * Since we look at the bio's to send the request over the network we
1192: * need to make sure the completion work doesn't mark this request done
1193: * before we are done doing our send. This keeps us from dereferencing
1194: * freed data if we have particularly fast completions (ie we get the
1195: * completion before we exit sock_xmit on the last bvec) or in the case
1196: * that the server is misbehaving (or there was an error) before we're
1197: * done sending everything over the wire.
1198: */
1199: mutex_lock(&cmd->lock);
1200: clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1201:
1202: /* We can be called directly from the user space process, which means we
1203: * could possibly have signals pending so our sendmsg will fail. In
1204: * this case we need to return that we are busy, otherwise error out as
1205: * appropriate.
1206: */
1207: ret = nbd_handle_cmd(cmd, hctx->queue_num);
1208: mutex_unlock(&cmd->lock);
1209:
1210: return ret;
1211: }
SourceFile:drivers/block/nbd.c]
|
| 98/2 |
2026/05/10 03:06 |
llm |
debugger |
2m
Model:
Tokens:
input: 148316
output: 43
thoughts: 9
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, presented in the first person:
**Navigating the `nbd_handle_cmd` Execution Flow**
Alright, let's break down this `nbd_handle_cmd` function. I'm thinking about the nbd (Network Block Device) protocol, and specifically, how a command gets processed. I see this function as the central dispatch point, the conductor, if you will, for incoming requests. The challenge, as always with block devices, is the inherent asynchronous nature. We're dealing with network latency, potential I/O bottlenecks on the server, and the requirement to keep the connection responsive.
So, first, I need to look closely at how the command is parsed and validated. I'm assuming there's robust error checking in place. Are we verifying command lengths, flags, and data sizes against the negotiated capabilities and the block device's capacity? Is there proper sanity checking on the command code itself? I need to understand the implications of a malformed or malicious command; that could lead to serious problems like data corruption or even a denial-of-service.
Next, I'm zeroing in on the command handling itself. I'd imagine that based on the command type (READ, WRITE, TRIM, FLUSH, etc.), there's a switch or dispatch table. I'm interested in the degree of abstraction. Is this implemented using function pointers, a more modern object-oriented approach, or just a series of `if/else` statements? Regardless, the efficiency and clarity of this dispatch mechanism are crucial. It's the performance bottleneck that needs to be addressed early in the design.
Of course, concurrency is a major concern here. How are concurrent requests handled? Are we using mutexes, read-write locks, or something more sophisticated, like per-command contexts or a work queue? I'm wondering if each command has its own thread or if there's a thread pool. And even further, how is data coherency guaranteed across different client connections?
Now, the meat of the matter: I/O scheduling. The function likely translates the logical block access into physical operations on the underlying storage. Is there any attempt at I/O optimization here? Are we leveraging techniques like I/O merging, reordering, or even speculative reads/writes? Does the system use a block layer to provide caching or other optimization tricks?
Finally, the return path. I need to see how the completion status is signaled back to the client. Are we using a completion queue, a callback mechanism, or are we just sending acknowledgements over the network? And how is error handling managed? Is there a robust mechanism to handle timeouts, network errors, and storage errors, and how are these errors propagated back to the client in a meaningful way? I'm specifically looking for information on error propagation and recovery.
I also need to check the security implications. Are there any checks for client authorization, particularly for commands like TRIM or FLUSH? Is there any protection against replay attacks, or denial-of-service attempts by sending a high volume of spurious or intentionally malformed commands?
In short, `nbd_handle_cmd` is the heart of the system. I’m thinking about the robustness, the efficiency, the concurrency, the security, and the I/O optimization that goes into making it work.
|
| 99/2 |
2026/05/10 03:09 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_handle_cmd]
Results: map[SourceCode:1117: static blk_status_t nbd_handle_cmd(struct nbd_cmd *cmd, int index)
1118: {
1119: struct request *req = blk_mq_rq_from_pdu(cmd);
1120: struct nbd_device *nbd = cmd->nbd;
1121: struct nbd_config *config;
1122: struct nbd_sock *nsock;
1123: blk_status_t ret;
1124:
1125: lockdep_assert_held(&cmd->lock);
1126:
1127: config = nbd_get_config_unlocked(nbd);
1128: if (!config) {
1129: dev_err_ratelimited(disk_to_dev(nbd->disk),
1130: "Socks array is empty\n");
1131: return BLK_STS_IOERR;
1132: }
1133:
1134: if (index >= config->num_connections) {
1135: dev_err_ratelimited(disk_to_dev(nbd->disk),
1136: "Attempted send on invalid socket\n");
1137: nbd_config_put(nbd);
1138: return BLK_STS_IOERR;
1139: }
1140: cmd->status = BLK_STS_OK;
1141: again:
1142: nsock = config->socks[index];
1143: mutex_lock(&nsock->tx_lock);
1144: if (nsock->dead) {
1145: int old_index = index;
1146: index = find_fallback(nbd, index);
1147: mutex_unlock(&nsock->tx_lock);
1148: if (index < 0) {
1149: if (wait_for_reconnect(nbd)) {
1150: index = old_index;
1151: goto again;
1152: }
1153: /* All the sockets should already be down at this point,
1154: * we just want to make sure that DISCONNECTED is set so
1155: * any requests that come in that were queue'ed waiting
1156: * for the reconnect timer don't trigger the timer again
1157: * and instead just error out.
1158: */
1159: sock_shutdown(nbd);
1160: nbd_config_put(nbd);
1161: return BLK_STS_IOERR;
1162: }
1163: goto again;
1164: }
1165:
1166: /* Handle the case that we have a pending request that was partially
1167: * transmitted that _has_ to be serviced first. We need to call requeue
1168: * here so that it gets put _after_ the request that is already on the
1169: * dispatch list.
1170: */
1171: blk_mq_start_request(req);
1172: if (unlikely(nsock->pending && nsock->pending != req)) {
1173: nbd_requeue_cmd(cmd);
1174: ret = BLK_STS_OK;
1175: goto out;
1176: }
1177: ret = nbd_send_cmd(nbd, cmd, index);
1178: out:
1179: mutex_unlock(&nsock->tx_lock);
1180: nbd_config_put(nbd);
1181: return ret;
1182: }
SourceFile:drivers/block/nbd.c]
|
| 100/2 |
2026/05/10 03:09 |
llm |
debugger |
1m
Model:
Tokens:
input: 150121
output: 1219
thoughts: 7343
Thoughts: **Race Condition in NBD Device Configuration and Filesystem Mount**
Okay, so here's what's happening. I've got this UDF filesystem mount, and it's interacting badly with an NBD (Network Block Device) setup, resulting in a warning during a block read and potential data corruption. It hinges on a race condition between the `mount` process and the NBD configuration, specifically, altering the *logical block size* of the NBD device concurrently to when mount is using it.
Here's the sequence of events, and where it all goes wrong:
1. A filesystem is mounted on a network block device. During mount, `udf_fill_super` is called. It starts to set up the superblock with a block size, for example, 512, which is the default for an unconfigured NBD device. `uopt->blocksize` is set to this value (512). It proceeds to call `udf_load_vrs` with blocksize = 512, then calls `sb_set_blocksize(sb, 512)` making `sb->s_blocksize` also be 512.
2. Concurrent to this, another thread or process makes an `ioctl(NBD_DO_IT)` (or similar ioctl calls `NBD_SET_BLKSIZE`) call on the *same* NBD device. This calls `nbd_set_size`. This changes the *logical block size* of the NBD device to 1024 (or another value, based on configuration). The NBD driver calls `queue_limits_commit_update_frozen` and commits the new block size to the device queue, making the changes effectively immediately.
3. Back on the `mount` thread, the filesystem is now trying to read blocks from the device. Because of the mounting options/steps taken, `udf_load_vrs` is still active, reading block from disk. It calls `udf_scan_anchors` which makes the call to `udf_read_tagged` which calls `sb_bread(sb, block)`, with the blocksize of 512 that was set *before* the NBD configuration change, and stores it in `__bread_gfp`.
4. Here's the crux: `__getblk_slow` gets called during the read. Now it checks, using `WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))`, whether the block size used during the read is aligned with the current logical block size of the device. Since NBD *changed* the `logical_block_size` to 1024, but the block read is using 512, the check fails.
5. This triggers the warning `fs/buffer.c:1029`. The read might fail and return a NULL.
The core of the problem is `nbd_set_size`, which changes the `logical_block_size`, can be called when there is already someone else using the device (e.g., has it mounted). This leads to a Time-of-Check to Time-of-Use vulnerability. The VFS and the filesystem's assumption about the device's characteristics (in this case, block size), is being broken because another component can mutate it concurrently. The device size or capacity can be changed safely while mounted (although it could produce I/O errors if the size is decreased), but the logical block size MUST NOT be changed without the block being exclusive to that process/thread.
**A Fix**: NBD should guard against this by preventing modifications to the `logical_block_size` if the device is exclusively opened, or at least open, for usage by another entity. This could be achieved by using a mechanism like the one used by the loop driver in `loop_set_block_size`.
This basically ensures the device size (and the block size) can only be changed if no other process/thread has the device in use.
|
| 101/1 |
2026/05/10 03:10 |
action |
kernel-scratch-checkouter |
0m
Results: map[KernelScratchSrc:/app/workdir/cache/tmp/tmp3765357259]
|
| 102/1 |
2026/05/10 03:10 |
loop |
|
56m
|
| 103/2 |
2026/05/10 03:10 |
iteration |
0 |
56m
|
| 104/3 |
2026/05/10 03:10 |
agent |
patch-generator |
22m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with creating a fix for a kernel bug.
You will be given a crash report, and an initial explanation of the root cause done by another
kernel expert.
Use the codeeditor tool to do code edits.
Note: you will not see your changes when looking at the code using codesearch tools.
Your final reply should contain explanation of what you did in the patch and why
(details not present in the initial explanation of the bug).
Your fix must not just prevent the given crash, but also be the best fix for the underlying
root cause from the software engineering point of view. There can be several ways to fix the
same bug. Consider alternatives, and pick the best one. For example, additional checks may be
added at different locations/functions, it's usually better to place them earlier in the
execution to avoid multiple checks at various locations later.
Frequently the same coding mistake is done in several locations in the source code.
Check if your fix should be extended/applied to similar cases around to fix other similar bugs.
But don't go too wide, don't try to fix problems kernel-wide, fix similar issues
in the same file only.
If you are changing post-conditions of a function, consider all callers of the functions,
and if they need to be updated to handle new post-conditions. For example, if you make
a function that previously never returned a NULL, return NULL, consider if callers
need to be updated to handle NULL return value.
If you will end up removing the WARN_ON macro because the condition can legitimately happen,
add a pr_err call that logs that the unlikely condition has happened. The pr_err message
must not include "WARNING" string.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
------------[ cut here ]------------
WARNING: fs/buffer.c:1029 at __getblk_slow fs/buffer.c:1029 [inline], CPU#1: syz.5.22/6454
WARNING: fs/buffer.c:1029 at bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358, CPU#1: syz.5.22/6454
Modules linked in:
CPU: 1 UID: 0 PID: 6454 Comm: syz.5.22 Not tainted syzkaller #1 PREEMPT(full)
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
RIP: 0010:__getblk_slow fs/buffer.c:1029 [inline]
RIP: 0010:bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358
Code: eb cf e8 68 fa 6e ff 48 c7 c7 80 d4 9c 8b 48 c7 c6 f6 e3 c2 8d 4c 89 e2 48 8b 4c 24 10 e8 cd e9 d2 fe eb be e8 46 fa 6e ff 90 <0f> 0b 90 48 b8 00 00 00 00 00 fc ff df 41 80 3c 07 00 74 08 48 89
RSP: 0018:ffffc9000575f668 EFLAGS: 00010293
RAX: ffffffff8254b52a RBX: ffff8880424af318 RCX: ffff888023179d80
RDX: 0000000000000000 RSI: 0000000000000200 RDI: 0000000000000000
RBP: 0000000000000200 R08: ffffffff82217e1c R09: ffffffff8e67f1a0
R10: 0000000000000406 R11: 0000000000000000 R12: 0000000000000200
R13: 0000000000000400 R14: 0000000000000200 R15: 1ffff11008495e63
FS: 00007f7ef90ec6c0(0000) GS:ffff8880ebf32000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007fb010d456b8 CR3: 000000001feba000 CR4: 00000000000006f0
Call Trace:
<TASK>
__bread_gfp+0x89/0x3b0 fs/buffer.c:1412
sb_bread include/linux/buffer_head.h:346 [inline]
udf_read_tagged+0xab/0xe60 fs/udf/misc.c:199
udf_check_anchor_block+0x9f/0x560 fs/udf/super.c:1913
udf_scan_anchors fs/udf/super.c:1991 [inline]
udf_load_vrs+0xa91/0xfe0 fs/udf/super.c:2034
udf_fill_super+0x58b/0x1870 fs/udf/super.c:2202
get_tree_bdev_flags+0x431/0x4f0 fs/super.c:1694
vfs_get_tree+0x92/0x2a0 fs/super.c:1754
fc_mount fs/namespace.c:1193 [inline]
do_new_mount_fc fs/namespace.c:3758 [inline]
do_new_mount+0x341/0xd30 fs/namespace.c:3834
do_mount fs/namespace.c:4167 [inline]
__do_sys_mount fs/namespace.c:4383 [inline]
__se_sys_mount+0x31d/0x420 fs/namespace.c:4360
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f7ef819cdd9
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f7ef90ec028 EFLAGS: 00000246 ORIG_RAX: 00000000000000a5
RAX: ffffffffffffffda RBX: 00007f7ef8416090 RCX: 00007f7ef819cdd9
RDX: 0000200000000080 RSI: 0000200000004a00 RDI: 0000200000000000
RBP: 00007f7ef8232d69 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000002008087 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f7ef8416128 R14: 00007f7ef8416090 R15: 00007ffd283d4848
</TASK>
The explanation of the root cause of the bug is:
The root cause of this crash is a Time-Of-Check to Time-Of-Use (TOCTOU) race condition between the VFS/filesystem mount process and the NBD (Network Block Device) driver.
The NBD driver allows changing the block device's `logical_block_size` concurrently while the device is being mounted or is already in use. This violates the VFS assumption that a block device's logical block size remains constant while it is exclusively claimed (e.g., by a filesystem).
### Detailed Sequence of Events
Although the provided C reproducer executes the syscalls sequentially, syzkaller often executes them in parallel threads to trigger race conditions. The crash happens when `mount` and `ioctl(NBD_DO_IT)` are executed concurrently:
1. **[Thread A - `mount`]**: The `mount` syscall enters the UDF filesystem's `udf_fill_super()`. Since no block size was explicitly provided in the mount options, UDF reads the block device's current logical block size to use as a starting point:
```c
// fs/udf/super.c : udf_fill_super()
uopt->blocksize = bdev_logical_block_size(sb->s_bdev);
```
At this point, the NBD device has not been started, so its `logical_block_size` is the default `512`. Thus, `uopt->blocksize` is set to `512`.
2. **[Thread A - `mount`]**: UDF calls `udf_load_vrs()`, which successfully sets the superblock's block size to `512` because it matches the block device's current logical block size:
```c
// fs/udf/super.c : udf_load_vrs()
if (!sb_set_blocksize(sb, uopt->blocksize)) { ... }
```
Now, `sb->s_blocksize` is `512`.
3. **[Thread B - `ioctl`]**: Concurrently, another thread executes the `NBD_DO_IT` ioctl (or `NBD_SET_BLKSIZE`) on the same NBD device. This calls `nbd_start_device()`, which configures the device and updates its queue limits via `nbd_set_size()`:
```c
// drivers/block/nbd.c : nbd_set_size()
lim.logical_block_size = blksize; // blksize is 1024 (1u << NBD_DEF_BLKSIZE_BITS)
lim.physical_block_size = blksize;
error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
```
The block device's `logical_block_size` is now changed to `1024` under the hood.
4. **[Thread A - `mount`]**: UDF continues the mounting process and attempts to read the Volume Recognition Sequence (VRS) from the disk using `sb_bread()`:
```c
// fs/udf/misc.c : udf_read_tagged()
bh = sb_bread(sb, block);
```
`sb_bread()` requests a buffer of size `sb->s_blocksize` (which is still `512`).
5. **[Thread A - `mount`]**: The read request reaches `__getblk_slow()`, which validates the requested size against the block device's *current* logical block size:
```c
// fs/buffer.c : __getblk_slow()
if (WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))) {
printk(KERN_ERR "getblk(): block size %d not aligned to logical block size %d\n",
size, bdev_logical_block_size(bdev));
return NULL;
}
```
Since the requested size is `512` but the block device's `logical_block_size` was concurrently changed to `1024` by Thread B, `IS_ALIGNED(512, 1024)` evaluates to false, triggering the `WARN_ON_ONCE`.
### Suggested Fix
The NBD driver should not be allowed to change the `logical_block_size` of the block device if it is already exclusively claimed (e.g., actively mounted by a filesystem).
A similar issue was previously fixed in the loop device driver (`drivers/block/loop.c : loop_set_block_size()`), which uses `bd_prepare_to_claim()` to ensure it has exclusive access before modifying the block size:
```c
/*
* If we don't hold exclusive handle for the device, upgrade to it
* here to avoid changing device under exclusive owner.
*/
if (!(mode & BLK_OPEN_EXCL)) {
err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
if (err)
return err;
}
```
Applying a similar exclusive claim check in `nbd_set_size()` (or preventing geometry changes when `disk_openers(nbd->disk) > 1`) would prevent this race condition and safely reject concurrent modifications while the device is mounted.
Reply: The root cause of the crash is a Time-Of-Check to Time-Of-Use (TOCTOU) race condition where the NBD driver allows changing the block device's `logical_block_size` concurrently while the device is being mounted. This violates the VFS assumption that a block device's logical block size remains constant while it is exclusively claimed (e.g., by a filesystem).
While the loop driver uses `bd_prepare_to_claim()` to prevent this, using it in the NBD driver inside `nbd_set_size()` would introduce a severe ABBA deadlock. `nbd_set_size()` is called with the NBD-internal `nbd->config_lock` held. If it calls `bd_prepare_to_claim()`, it will attempt to acquire the global `bdev_lock`. Concurrently, a thread opening the block device (e.g., `mount`) will acquire `bdev_lock` first and then call `nbd_open()`, which attempts to acquire `nbd->config_lock`, resulting in a deadlock.
To safely prevent this race condition without introducing deadlocks, we can check the number of openers of the block device. If `disk_openers(nbd->disk) > 1`, it means that another entity (like a filesystem mounting the device) has the device open concurrently with the configuration process (which holds one open reference via the ioctl file descriptor).
By rejecting geometry changes in `nbd_set_size()` when `disk_openers(nbd->disk) > 1` and the device is already started (`nbd->pid` is set), we safely prevent concurrent modifications while the device is mounted or otherwise exclusively claimed.
I have implemented this fix by adding the `disk_openers` check directly in `nbd_set_size()`.
|
| 105/4 |
2026/05/10 03:10 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 7103
output: 27
thoughts: 110
Thoughts: **Analyzing a Block Device Crash**
Okay, so I've got a crash, and it's hitting me in `__getblk_slow`. The error message screams `WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))`. Right, that's a classic alignment issue. The explanation points the finger at NBD, suggesting it's changing the `logical_block_size` while the device is mounted. That's a classic concurrency problem, and a pretty nasty one at that.
The fix? Looks like they're proposing that NBD should behave more like the loop driver, preventing block size modifications if the device is exclusively claimed. That makes sense, keeps things consistent and avoids any surprise changes during the mount process.
Right, time to dive into the code. Let's see how they've handled this – I need to get into `drivers/block/nbd.c` and take a look.
|
| 106/4 |
2026/05/10 03:10 |
tool |
codesearch-file-index |
0m
Args: map[SourceFile:drivers/block/nbd.c]
Results: map[Entities:[map[Kind:function Name:__check_max_part] map[Kind:function Name:__check_nbds_max] map[Kind:function Name:__nbd_ioctl] map[Kind:function Name:__sock_xmit] map[Kind:function Name:backend_show] map[Kind:function Name:find_fallback] map[Kind:function Name:nbd_add_socket] map[Kind:function Name:nbd_alloc_and_init_config] map[Kind:function Name:nbd_bdev_reset] map[Kind:function Name:nbd_blksize] map[Kind:function Name:nbd_cleanup] map[Kind:function Name:nbd_clear_que] map[Kind:function Name:nbd_clear_req] map[Kind:function Name:nbd_clear_sock] map[Kind:function Name:nbd_clear_sock_ioctl] map[Kind:function Name:nbd_cmd_handle] map[Kind:function Name:nbd_complete_rq] map[Kind:function Name:nbd_config_put] map[Kind:function Name:nbd_connect_reply] map[Kind:function Name:nbd_dbg_close] map[Kind:function Name:nbd_dbg_flags_open] map[Kind:function Name:nbd_dbg_flags_show] map[Kind:function Name:nbd_dbg_init] map[Kind:function Name:nbd_dbg_tasks_open] map[Kind:function Name:nbd_dbg_tasks_show] map[Kind:function Name:nbd_dead_link_work] map[Kind:function Name:nbd_dev_add] map[Kind:function Name:nbd_dev_dbg_close] map[Kind:function Name:nbd_dev_dbg_init] map[Kind:function Name:nbd_dev_remove] map[Kind:function Name:nbd_dev_remove_work] map[Kind:function Name:nbd_disconnect] map[Kind:function Name:nbd_disconnect_and_put] map[Kind:function Name:nbd_disconnected] map[Kind:function Name:nbd_exit_cb] map[Kind:function Name:nbd_find_get_unused] map[Kind:function Name:nbd_free_disk] map[Kind:function Name:nbd_genl_connect] map[Kind:function Name:nbd_genl_disconnect] map[Kind:function Name:nbd_genl_reconfigure] map[Kind:function Name:nbd_genl_size_set] map[Kind:function Name:nbd_genl_status] map[Kind:function Name:nbd_get_config_unlocked] map[Kind:function Name:nbd_get_socket] map[Kind:function Name:nbd_handle_cmd] map[Kind:function Name:nbd_handle_reply] map[Kind:function Name:nbd_handle_to_cookie] map[Kind:function Name:nbd_handle_to_tag] map[Kind:function Name:nbd_init] map[Kind:function Name:nbd_init_request] map[Kind:function Name:nbd_ioctl] map[Kind:function Name:nbd_mark_nsock_dead] map[Kind:function Name:nbd_mcast_index] map[Kind:function Name:nbd_open] map[Kind:function Name:nbd_parse_flags] map[Kind:function Name:nbd_pending_cmd_work] map[Kind:function Name:nbd_put] map[Kind:function Name:nbd_queue_rq] map[Kind:function Name:nbd_read_reply] map[Kind:function Name:nbd_reconnect_socket] map[Kind:function Name:nbd_release] map[Kind:function Name:nbd_requeue_cmd] map[Kind:function Name:nbd_sched_pending_work] map[Kind:function Name:nbd_send_cmd] map[Kind:function Name:nbd_set_cmd_timeout] map[Kind:function Name:nbd_set_size] map[Kind:function Name:nbd_start_device] map[Kind:function Name:nbd_start_device_ioctl] map[Kind:function Name:nbd_to_dev] map[Kind:function Name:nbd_xmit_timeout] map[Kind:function Name:nbdcmd_to_ascii] map[Kind:function Name:pid_show] map[Kind:function Name:populate_nbd_status] map[Kind:function Name:recv_work] map[Kind:function Name:req_to_nbd_cmd_type] map[Kind:function Name:send_disconnects] map[Kind:function Name:sock_shutdown] map[Kind:function Name:sock_xmit] map[Kind:function Name:status_cb] map[Kind:function Name:wait_for_reconnect] map[Kind:function Name:was_interrupted] map[Kind:struct Name:link_dead_args] map[Kind:struct Name:nbd_cmd] map[Kind:struct Name:nbd_config] map[Kind:struct Name:nbd_device] map[Kind:struct Name:nbd_sock] map[Kind:struct Name:recv_thread_args] map[Kind:global_variable Name:__UNIQUE_ID_addressable_nbd_init_1559] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1556] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1560] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1561] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1562] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1563] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1564] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1565] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_1566] map[Kind:global_variable Name:__exitcall_nbd_cleanup] map[Kind:global_variable Name:__param_max_part] map[Kind:global_variable Name:__param_nbds_max] map[Kind:global_variable Name:__param_str_max_part] map[Kind:global_variable Name:__param_str_nbds_max] map[Kind:global_variable Name:backend_attr] map[Kind:global_variable Name:max_part] map[Kind:global_variable Name:nbd_attr_policy] map[Kind:global_variable Name:nbd_connect_genl_ops] map[Kind:global_variable Name:nbd_dbg_flags_fops] map[Kind:global_variable Name:nbd_dbg_tasks_fops] map[Kind:global_variable Name:nbd_device_policy] map[Kind:global_variable Name:nbd_fops] map[Kind:global_variable Name:nbd_genl_family] map[Kind:global_variable Name:nbd_index_idr] map[Kind:global_variable Name:nbd_index_mutex] map[Kind:global_variable Name:nbd_mcast_grps] map[Kind:global_variable Name:nbd_mq_ops] map[Kind:global_variable Name:nbd_sock_policy] map[Kind:global_variable Name:nbd_total_devices] map[Kind:global_variable Name:nbds_max] map[Kind:global_variable Name:pid_attr]]]
|
| 107/4 |
2026/05/10 03:10 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 9611
output: 43
thoughts: 60
Thoughts: Okay, here's my assessment of the situation, tailored for my fellow experts:
**Investigating a Potential Block Size Adjustment Conflict**
Right, so here's the crux of the problem as I see it. We've got a potential race condition or data integrity issue brewing because the `nbd_set_size` function, responsible for dynamically adjusting the block size of the network block device, can be invoked while the device is in an exclusive state – a scenario that often arises when the device is actively in use, like being mounted. This is a red flag.
My immediate instinct is to dive into the code and critically examine both `nbd_set_size` and, crucially, `nbd_start_device`. I need to understand *how* `nbd_set_size` handles (or doesn't handle) these concurrent access scenarios. I'm thinking about locking mechanisms, atomic operations, and how we ensure consistency if the block size changes while writes or reads are in progress. I also need to see the context within `nbd_start_device` to determine if we are starting the device with some initial size, which then gets updated, or it gets updated later.
|
| 108/4 |
2026/05/10 03:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_set_size]
Results: map[SourceCode: 334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
335: {
336: struct queue_limits lim;
337: int error;
338:
339: if (!blksize)
340: blksize = 1u << NBD_DEF_BLKSIZE_BITS;
341:
342: if (blk_validate_block_size(blksize))
343: return -EINVAL;
344:
345: if (bytesize < 0)
346: return -EINVAL;
347:
348: nbd->config->bytesize = bytesize;
349: nbd->config->blksize_bits = __ffs(blksize);
350:
351: if (!nbd->pid)
352: return 0;
353:
354: lim = queue_limits_start_update(nbd->disk->queue);
355: if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
356: lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
357: else
358: lim.max_hw_discard_sectors = 0;
359: if (!(nbd->config->flags & NBD_FLAG_SEND_FLUSH)) {
360: lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
361: } else if (nbd->config->flags & NBD_FLAG_SEND_FUA) {
362: lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
363: } else {
364: lim.features |= BLK_FEAT_WRITE_CACHE;
365: lim.features &= ~BLK_FEAT_FUA;
366: }
367: if (nbd->config->flags & NBD_FLAG_ROTATIONAL)
368: lim.features |= BLK_FEAT_ROTATIONAL;
369: if (nbd->config->flags & NBD_FLAG_SEND_WRITE_ZEROES)
370: lim.max_write_zeroes_sectors = UINT_MAX >> SECTOR_SHIFT;
371:
372: lim.logical_block_size = blksize;
373: lim.physical_block_size = blksize;
374: error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
375: if (error)
376: return error;
377:
378: if (max_part)
379: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
380: if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
381: kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
382: return 0;
383: }
SourceFile:drivers/block/nbd.c]
|
| 109/4 |
2026/05/10 03:10 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 10868
output: 51
thoughts: 143
Thoughts: **Analyzing the Block Device Claiming Logic**
Okay, so I'm looking at this proposed code snippet, and my initial thought is, "Hmm, this seems like it's trying to ensure exclusive access to a block device before potentially modifying it." The comment suggests the goal is to prevent a scenario where the device's characteristics are changed while another entity has exclusive control, which makes perfect sense. Safeguarding data integrity is paramount, especially in block device operations.
Now, I'm taking a closer look at the condition: `if (!(mode & BLK_OPEN_EXCL))`. This is testing if the device isn't *already* opened in exclusive mode. If it's *not*, then `bd_prepare_to_claim` is called. That's good, but my radar is going up, I'm thinking, "Where is the `bdev` and `mode` coming from?". And even bigger question is, what is `loop_set_block_size` doing here? How does it fit in?
Then I realize... wait a second! `nbd_set_size` - isn't that the function that eventually sets the size? I don't recall seeing those arguments in its signature! This is concerning. This proposed fix seems like it is trying to call something on the `bdev` before the size is set, but that may not be available. I need to trace back and find every call to `nbd_set_size` and see how this data is passed to the function, and what other variables or context there may be around it. Something seems amiss here. My job now is to determine how this code interacts with the device, and whether the proposed fix is actually applicable to the context.
|
| 110/4 |
2026/05/10 03:10 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeSnippetLines:0 Name:nbd_set_size SourceTreePrefix:]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1608] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1610] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1614] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_genl_size_set SourceFile:drivers/block/nbd.c SourceLine:2069] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_start_device SourceFile:drivers/block/nbd.c SourceLine:1540]] TruncatedOutput:false]
|
| 111/4 |
2026/05/10 03:10 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 11709
output: 42
thoughts: 31
Thoughts: Okay, here's my take on those thoughts, framed as a first-person expert summary:
**Initial Diagnostic Thoughts: Kernel NBD Modules**
Alright, let's dive in. When I'm looking at the NBD (Network Block Device) kernel modules and debugging or reviewing, the first things that jump out as potential areas to investigate are `__nbd_ioctl`, `nbd_genl_size_set`, and `nbd_start_device`. Each of these functions represents a crucial component of NBD's operational logic, and therefore presents different opportunities for system behavior analysis.
`__nbd_ioctl` is, of course, the general entry point for user-space interactions through the `ioctl` system call. It's essentially the gatekeeper for various control operations on the NBD device. If I'm troubleshooting a specific issue, I'd want to check this function to see how those specific operations are being handled and confirm whether our operation is being received and dispatched appropriately. We'll need to confirm what the ioctl number and associated data are.
Then we have `nbd_genl_size_set`. This suggests the function relates to General Netlink and the ability to set the block device size. This is a very interesting piece of functionality because it enables the dynamic resizing of a network block device. If I'm looking for issues related to device sizing, capacity limits, or unexpected behavior after a resize, this function would immediately be on my radar. Its interaction with user space would be critical to understand.
Finally, `nbd_start_device`. This one's pretty straightforward, but crucial. This function is likely the one that orchestrates the overall activation of the NBD device. In case of issues, I'd trace the execution of this function, looking for any failure points, error conditions, or race conditions. Also, I'd check the prerequisites before activation, such as configuration of the target server, any internal data structures, and the state of the associated networking components. I'd pay close attention to the sequencing and resource allocation done within this function. These three are all potentially high-impact areas, so they're the obvious starting points for deeper investigation.
|
| 112/4 |
2026/05/10 03:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:__nbd_ioctl]
Results: map[SourceCode:1592: /* Must be called with config_lock held */
1593: static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1594: unsigned int cmd, unsigned long arg)
1595: {
1596: struct nbd_config *config = nbd->config;
1597: loff_t bytesize;
1598:
1599: switch (cmd) {
1600: case NBD_DISCONNECT:
1601: return nbd_disconnect(nbd);
1602: case NBD_CLEAR_SOCK:
1603: nbd_clear_sock_ioctl(nbd);
1604: return 0;
1605: case NBD_SET_SOCK:
1606: return nbd_add_socket(nbd, arg, false);
1607: case NBD_SET_BLKSIZE:
1608: return nbd_set_size(nbd, config->bytesize, arg);
1609: case NBD_SET_SIZE:
1610: return nbd_set_size(nbd, arg, nbd_blksize(config));
1611: case NBD_SET_SIZE_BLOCKS:
1612: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1613: return -EINVAL;
1614: return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1615: case NBD_SET_TIMEOUT:
1616: nbd_set_cmd_timeout(nbd, arg);
1617: return 0;
1618:
1619: case NBD_SET_FLAGS:
1620: config->flags = arg;
1621: return 0;
1622: case NBD_DO_IT:
1623: return nbd_start_device_ioctl(nbd);
1624: case NBD_CLEAR_QUE:
1625: /*
1626: * This is for compatibility only. The queue is always cleared
1627: * by NBD_DO_IT or NBD_CLEAR_SOCK.
1628: */
1629: return 0;
1630: case NBD_PRINT_DEBUG:
1631: /*
1632: * For compatibility only, we no longer keep a list of
1633: * outstanding requests.
1634: */
1635: return 0;
1636: }
1637: return -ENOTTY;
1638: }
SourceFile:drivers/block/nbd.c]
|
| 113/4 |
2026/05/10 03:10 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 12999
output: 41
thoughts: 26
Thoughts: Okay, here's my take on those thoughts, framed for an expert audience, as if they were my own mental process:
**Diving into the NBD Ioctl Landscape**
Alright, I see a function call: `__nbd_ioctl` being invoked by `nbd_ioctl`. Naturally, my first instinct is to understand the calling function, `nbd_ioctl`. Knowing this, I need to understand its behavior. The relationships between these functions are the key to understanding the NBD driver's interaction with user space through the `ioctl` interface.
|
| 114/4 |
2026/05/10 03:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_ioctl]
Results: map[SourceCode:1640: static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1641: unsigned int cmd, unsigned long arg)
1642: {
1643: struct nbd_device *nbd = bdev->bd_disk->private_data;
1644: struct nbd_config *config = nbd->config;
1645: int error = -EINVAL;
1646:
1647: if (!capable(CAP_SYS_ADMIN))
1648: return -EPERM;
1649:
1650: /* The block layer will pass back some non-nbd ioctls in case we have
1651: * special handling for them, but we don't so just return an error.
1652: */
1653: if (_IOC_TYPE(cmd) != 0xab)
1654: return -EINVAL;
1655:
1656: mutex_lock(&nbd->config_lock);
1657:
1658: /* Don't allow ioctl operations on a nbd device that was created with
1659: * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1660: */
1661: if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1662: (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1663: error = __nbd_ioctl(bdev, nbd, cmd, arg);
1664: else
1665: dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1666: mutex_unlock(&nbd->config_lock);
1667: return error;
1668: }
SourceFile:drivers/block/nbd.c]
|
| 115/4 |
2026/05/10 03:10 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 13716
output: 23
thoughts: 374
Thoughts: **Analyzing the Loop Driver's Block Size Configuration**
Okay, so I'm looking at this `loop_set_block_size` function within the loop driver. My immediate thought is, it's pretty straightforward. It's designed to set the logical block size of a loop device. I see it starts by checking the device state; it needs to be bound. Then, it validates the proposed block size, ensuring it's within a reasonable range (512 to `PAGE_SIZE`) and is a power of 2, as is typical for block devices.
The function then compares the proposed block size, *`arg`*, against the current size. If they are equal, it returns early. The function proceeds to flush the device, and invalidate its cache, before entering a block size change.
The queue is frozen and block size validation is performed. The function then updates the queue limits (logical, physical, and I/O minimum block sizes) using `queue_limits_start_update` and `queue_limits_commit_update_frozen`, which is critical. It updates the `lo->lo_logical_block_size` if everything is good, and unfrozen.
Now, I'm just curious. This made me think. Where is the loop driver checking `bd_prepare_to_claim`? Is it in `loop_configure` or is it in `loop_set_block_size`? I don't see it here, so I need to go look. I need to open `drivers/block/loop.c` and hunt it down. I suspect it's likely a part of the initial device configuration, but I'll make sure and see what I can find.
|
| 116/4 |
2026/05/10 03:11 |
tool |
grepper |
0m
Args: map[Expression:bd_prepare_to_claim.*loop]
Results: map[Output:block/bdev.c=590=int bd_prepare_to_claim(struct block_device *bdev, void *holder,
--
block/bdev.c-621-}
block/bdev.c:622:EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
block/bdev.c-623-
--
drivers/block/loop.c=981=static int loop_configure(struct loop_device *lo, blk_mode_t mode,
--
drivers/block/loop.c-1010- if (!(mode & BLK_OPEN_EXCL)) {
drivers/block/loop.c:1011: error = bd_prepare_to_claim(bdev, loop_configure, NULL);
drivers/block/loop.c-1012- if (error)
--
drivers/block/loop.c=1445=static int loop_set_block_size(struct loop_device *lo, blk_mode_t mode,
--
drivers/block/loop.c-1456- if (!(mode & BLK_OPEN_EXCL)) {
drivers/block/loop.c:1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
drivers/block/loop.c-1458- if (err)
]
|
| 117/4 |
2026/05/10 03:11 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 14830
output: 18
thoughts: 318
Thoughts: **Investigating the Use of `bd_prepare_to_claim` in `nbd.c`**
Okay, so `bd_prepare_to_claim` is exported, but the comment specifically says it's for the loop driver. This raises a flag. Should I try to use it in `nbd.c`, or is there a better, more appropriate method?
Looking at the function signature, it takes `bdev`, `holder`, and `hops` as arguments. In the context of `nbd.c`, `bdev` is readily available within `nbd_ioctl`, which is good. However, I need to consider `nbd_set_size`, which is *also* called from `netlink` through `nbd_genl_size_set`. The netlink path lacks a file descriptor, so there isn't a corresponding `bdev` or `mode` available. This is a potential hurdle.
Aha, `nbd_genl_size_set` is a netlink command. Since it's not file-descriptor based, it won't have the standard file system mode available.
Now I need to think about how to handle the exclusivity. If the device is exclusively claimed, could `disk_openers(disk)` be greater than one? Or perhaps `bdev->bd_writers` holds the key? I need a reliable way to determine if there are active users of the block device.
Right, the suggestion makes sense: Implement an exclusive claim check within `nbd_set_size()`, or prevent geometry changes when `disk_openers(nbd->disk) > 1`. This should prevent a race condition and safeguard against concurrent modifications while the device is mounted.
So, I'll need to explore `disk_openers`, `bdev_is_claimed`, or some other similar mechanism. I need to make sure I am preventing modifications of the device that are unsafe in the presence of other users.
|
| 118/4 |
2026/05/10 03:11 |
tool |
grepper |
0m
Args: map[Expression:disk_openers]
Results: map[Output:arch/um/drivers/ubd_kern.c=993=static int ubd_remove(int n, char **error_out)
--
arch/um/drivers/ubd_kern.c-1007- err = -EBUSY;
arch/um/drivers/ubd_kern.c:1008: if (disk_openers(ubd_dev->disk))
arch/um/drivers/ubd_kern.c-1009- goto out;
--
drivers/block/loop.c=1192=static int loop_clr_fd(struct loop_device *lo)
--
drivers/block/loop.c-1218- lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
drivers/block/loop.c:1219: if (disk_openers(lo->lo_disk) == 1)
drivers/block/loop.c-1220- WRITE_ONCE(lo->lo_state, Lo_rundown);
--
drivers/block/loop.c=1730=static void lo_release(struct gendisk *disk)
--
drivers/block/loop.c-1734-
drivers/block/loop.c:1735: if (disk_openers(disk) > 0)
drivers/block/loop.c-1736- return;
--
drivers/block/loop.c=2143=static int loop_control_remove(int idx)
--
drivers/block/loop.c-2169- goto mark_visible;
drivers/block/loop.c:2170: if (lo->lo_state != Lo_unbound || disk_openers(lo->lo_disk) > 0) {
drivers/block/loop.c-2171- mutex_unlock(&lo->lo_mutex);
--
drivers/block/nbd.c=1375=static void nbd_bdev_reset(struct nbd_device *nbd)
drivers/block/nbd.c-1376-{
drivers/block/nbd.c:1377: if (disk_openers(nbd->disk) > 1)
drivers/block/nbd.c-1378- return;
--
drivers/block/nbd.c=1748=static void nbd_release(struct gendisk *disk)
--
drivers/block/nbd.c-1752- if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
drivers/block/nbd.c:1753: disk_openers(disk) == 0)
drivers/block/nbd.c-1754- nbd_disconnect_and_put(nbd);
--
drivers/block/ublk_drv.c=4858=static int ublk_ctrl_try_stop_dev(struct ublk_device *ub)
--
drivers/block/ublk_drv.c-4867- mutex_lock(&disk->open_mutex);
drivers/block/ublk_drv.c:4868: if (disk_openers(disk) > 0) {
drivers/block/ublk_drv.c-4869- ret = -EBUSY;
--
drivers/block/zram/zram_drv.c=2900=static ssize_t reset_store(struct device *dev,
--
drivers/block/zram/zram_drv.c-2919- /* Do not reset an active device or claimed device */
drivers/block/zram/zram_drv.c:2920: if (disk_openers(disk) || zram->claim) {
drivers/block/zram/zram_drv.c-2921- mutex_unlock(&disk->open_mutex);
--
drivers/block/zram/zram_drv.c=3102=static int zram_remove(struct zram *zram)
--
drivers/block/zram/zram_drv.c-3106- mutex_lock(&zram->disk->open_mutex);
drivers/block/zram/zram_drv.c:3107: if (disk_openers(zram->disk)) {
drivers/block/zram/zram_drv.c-3108- mutex_unlock(&zram->disk->open_mutex);
--
include/linux/blkdev.h=146=struct gendisk {
--
include/linux/blkdev.h-233-/**
include/linux/blkdev.h:234: * disk_openers - returns how many openers are there for a disk
include/linux/blkdev.h-235- * @disk: disk to check
--
include/linux/blkdev.h-242- */
include/linux/blkdev.h:243:static inline unsigned int disk_openers(struct gendisk *disk)
include/linux/blkdev.h-244-{
]
|
| 119/4 |
2026/05/10 03:11 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 16834
output: 44
thoughts: 209
Thoughts: **Analyzing Open Disk Handles in NBD Driver**
Okay, so I'm looking at how the Network Block Device (NBD) driver handles disk operations, specifically around setting the size. I was thinking about using `disk_openers(disk)` to check if the underlying disk is already open before modifying its size in `nbd_set_size`. The idea was to prevent conflicts, but then it hit me. `disk_openers` returns the number of openers, and the ioctl itself holds a file descriptor, so the count will always be at least one, right?
But wait a minute, what if this `nbd_set_size` is called from netlink? If so, `disk_openers` could return 0 or 1. Okay, scratch that.
Then I considered that if `disk_openers(nbd->disk) > 1`, it means another process has the disk open. But that doesn't tell the whole story, it doesn't account for exclusive opens. I need something more robust than just a non-exclusive open.
Ah, right! `bd_prepare_to_claim`! That checks for exclusive access, which is exactly what I need. That's a much better approach.
Hang on... I'm pretty sure I've seen something similar already. I seem to recall something already using `disk_openers(nbd->disk) > 1`. Let me check `nbd_bdev_reset`. I bet it's in `drivers/block/nbd.c`. I should probably confirm if that logic is correct before changing anything in `nbd_set_size`.
|
| 120/4 |
2026/05/10 03:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_bdev_reset]
Results: map[SourceCode:1375: static void nbd_bdev_reset(struct nbd_device *nbd)
1376: {
1377: if (disk_openers(nbd->disk) > 1)
1378: return;
1379: set_capacity(nbd->disk, 0);
1380: }
SourceFile:drivers/block/nbd.c]
|
| 121/4 |
2026/05/10 03:11 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 17565
output: 42
thoughts: 69
Thoughts: **Navigating the bdev and nbd Connection**
Okay, so I'm working with this `bd_prepare_to_claim` function, and it's immediately clear that it requires a `bdev` argument. Right, that makes sense. But then I'm thinking about `nbd_set_size`, and I realize it doesn't *directly* take a `bdev`. Hmm... where is the `bdev` hiding? Ah ha! I think I've got it. I recall that `nbd->disk->part0` is, in fact, the `bdev` we're after. That seems like the correct connection. Just to be absolutely sure, let's quickly double-check the signature of `bd_prepare_to_claim` to make sure there are no gotchas. Better safe than sorry when dealing with block devices.
|
| 122/4 |
2026/05/10 03:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:bd_prepare_to_claim]
Results: map[SourceCode: 577: /**
578: * bd_prepare_to_claim - claim a block device
579: * @bdev: block device of interest
580: * @holder: holder trying to claim @bdev
581: * @hops: holder ops.
582: *
583: * Claim @bdev. This function fails if @bdev is already claimed by another
584: * holder and waits if another claiming is in progress. return, the caller
585: * has ownership of bd_claiming and bd_holder[s].
586: *
587: * RETURNS:
588: * 0 if @bdev can be claimed, -EBUSY otherwise.
589: */
590: int bd_prepare_to_claim(struct block_device *bdev, void *holder,
591: const struct blk_holder_ops *hops)
592: {
593: struct block_device *whole = bdev_whole(bdev);
594:
595: if (WARN_ON_ONCE(!holder))
596: return -EINVAL;
597: retry:
598: mutex_lock(&bdev_lock);
599: /* if someone else claimed, fail */
600: if (!bd_may_claim(bdev, holder, hops)) {
601: mutex_unlock(&bdev_lock);
602: return -EBUSY;
603: }
604:
605: /* if claiming is already in progress, wait for it to finish */
606: if (whole->bd_claiming) {
607: wait_queue_head_t *wq = __var_waitqueue(&whole->bd_claiming);
608: DEFINE_WAIT(wait);
609:
610: prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
611: mutex_unlock(&bdev_lock);
612: schedule();
613: finish_wait(wq, &wait);
614: goto retry;
615: }
616:
617: /* yay, all mine */
618: whole->bd_claiming = holder;
619: mutex_unlock(&bdev_lock);
620: return 0;
621: }
SourceFile:block/bdev.c]
|
| 123/4 |
2026/05/10 03:11 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 18555
output: 43
thoughts: 583
Thoughts: **Analyzing Device Claiming and Block Size Changes**
Okay, so I'm diving into this `bd_prepare_to_claim` function. It seems it *actually* claims the device, which means we *must* call `bd_abort_claiming` or `bd_finish_claiming` later. Now, I see the loop driver uses it, but it's only exported for that purpose, so that's not ideal.
My initial thought was to find a better way to check for exclusive access. I looked at `bdev_is_claimed` or something similar, and then considered `disk_openers(nbd->disk) > 1`. That looks like a good check because it's safe and simple.
Thinking a bit more, `disk_openers` gives the number of openers, meaning if we're in `nbd_ioctl`, the caller *already* has the device open, so `disk_openers` will be at least 1. If it's greater than 1, someone *else* has it open. However, if we're in `nbd_genl_size_set` (netlink), the caller *might not* have the device open, so `disk_openers` could be 0. If someone else is using it, then it's greater than 0.
But wait, if I just check `disk_openers(nbd->disk) > 1` in `nbd_set_size`, what happens if the netlink call happens when `disk_openers` is exactly 1? It'd succeed, which seems wrong. If someone has the device open, should netlink be allowed to change its size? Probably not.
So, maybe `disk_openers(nbd->disk) > 1` in `nbd_ioctl`, but `disk_openers(nbd->disk) > 0` in netlink? Hold on... `nbd_set_size` is called from `nbd_start_device`, which is called from the `NBD_DO_IT` ioctl. Let's trace that path and look at `nbd_start_device` to see how that context works.
|
| 124/4 |
2026/05/10 03:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device]
Results: map[SourceCode:1471: static int nbd_start_device(struct nbd_device *nbd)
1472: {
1473: struct nbd_config *config = nbd->config;
1474: int num_connections = config->num_connections;
1475: int error = 0, i;
1476:
1477: if (nbd->pid)
1478: return -EBUSY;
1479: if (!config->socks)
1480: return -EINVAL;
1481: if (num_connections > 1 &&
1482: !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1483: dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1484: return -EINVAL;
1485: }
1486:
1487: retry:
1488: mutex_unlock(&nbd->config_lock);
1489: blk_mq_update_nr_hw_queues(&nbd->tag_set, num_connections);
1490: mutex_lock(&nbd->config_lock);
1491:
1492: /* if another code path updated nr_hw_queues, retry until succeed */
1493: if (num_connections != config->num_connections) {
1494: num_connections = config->num_connections;
1495: goto retry;
1496: }
1497:
1498: nbd->pid = task_pid_nr(current);
1499:
1500: nbd_parse_flags(nbd);
1501:
1502: error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1503: if (error) {
1504: dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1505: return error;
1506: }
1507: set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1508:
1509: nbd_dev_dbg_init(nbd);
1510: for (i = 0; i < num_connections; i++) {
1511: struct recv_thread_args *args;
1512:
1513: args = kzalloc_obj(*args);
1514: if (!args) {
1515: sock_shutdown(nbd);
1516: /*
1517: * If num_connections is m (2 < m),
1518: * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1519: * But NO.(n + 1) failed. We still have n recv threads.
1520: * So, add flush_workqueue here to prevent recv threads
1521: * dropping the last config_refs and trying to destroy
1522: * the workqueue from inside the workqueue.
1523: */
1524: if (i)
1525: flush_workqueue(nbd->recv_workq);
1526: return -ENOMEM;
1527: }
1528: sk_set_memalloc(config->socks[i]->sock->sk);
1529: if (nbd->tag_set.timeout)
1530: config->socks[i]->sock->sk->sk_sndtimeo =
1531: nbd->tag_set.timeout;
1532: atomic_inc(&config->recv_threads);
1533: refcount_inc(&nbd->config_refs);
1534: INIT_WORK(&args->work, recv_work);
1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
SourceFile:drivers/block/nbd.c]
|
| 125/4 |
2026/05/10 03:11 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 20849
output: 43
thoughts: 431
Thoughts: **Analyzing the Race Condition in `nbd_set_size`**
Okay, so I'm digging into this `nbd_set_size` function, and something's bugging me. I see that it's called at the *very* end of `nbd_start_device`. The issue is, what happens if `disk_openers(nbd->disk) > 1` when `nbd_set_size` gets called? If `nbd_start_device` is initiated through the `NBD_DO_IT` ioctl, the caller *does* have the device open. And if another process has it open – say, it's mounted – then `disk_openers` will indeed be greater than one.
The real problem is, if we return an error from `nbd_set_size` in that scenario, `nbd_start_device` returns an error, but the receive threads have *already* been started! Damn. That's a leak or potential resource issue waiting to happen. Since `nbd_set_size` is called last in `nbd_start_device`, we don't clean up the receive threads or `nbd->pid` if it fails.
So, the ideal solution would be to check `disk_openers` *before* we start the device, or handle the error *cleanly* in `nbd_set_size` itself. Alternatively, we could do an early check in `nbd_start_device`.
But wait, there's more. I just remembered that `nbd_set_size` is also called by the `NBD_SET_BLKSIZE` and `NBD_SET_SIZE` ioctls. Checking `disk_openers` in `nbd_set_size` is also going to return `-EBUSY` for those calls, and that's not what we want. Gotta go back and re-evaluate `nbd_set_size`.
|
| 126/4 |
2026/05/10 03:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_set_size]
Results: map[SourceCode: 334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
335: {
336: struct queue_limits lim;
337: int error;
338:
339: if (!blksize)
340: blksize = 1u << NBD_DEF_BLKSIZE_BITS;
341:
342: if (blk_validate_block_size(blksize))
343: return -EINVAL;
344:
345: if (bytesize < 0)
346: return -EINVAL;
347:
348: nbd->config->bytesize = bytesize;
349: nbd->config->blksize_bits = __ffs(blksize);
350:
351: if (!nbd->pid)
352: return 0;
353:
354: lim = queue_limits_start_update(nbd->disk->queue);
355: if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
356: lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
357: else
358: lim.max_hw_discard_sectors = 0;
359: if (!(nbd->config->flags & NBD_FLAG_SEND_FLUSH)) {
360: lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
361: } else if (nbd->config->flags & NBD_FLAG_SEND_FUA) {
362: lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
363: } else {
364: lim.features |= BLK_FEAT_WRITE_CACHE;
365: lim.features &= ~BLK_FEAT_FUA;
366: }
367: if (nbd->config->flags & NBD_FLAG_ROTATIONAL)
368: lim.features |= BLK_FEAT_ROTATIONAL;
369: if (nbd->config->flags & NBD_FLAG_SEND_WRITE_ZEROES)
370: lim.max_write_zeroes_sectors = UINT_MAX >> SECTOR_SHIFT;
371:
372: lim.logical_block_size = blksize;
373: lim.physical_block_size = blksize;
374: error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
375: if (error)
376: return error;
377:
378: if (max_part)
379: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
380: if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
381: kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
382: return 0;
383: }
SourceFile:drivers/block/nbd.c]
|
| 127/4 |
2026/05/10 03:11 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 22655
output: 43
thoughts: 456
Thoughts: **Analyzing the nbd_set_size and Device Start Flow**
Okay, let's break this down. First, `nbd_set_size` is setting `bytesize` and `blksize_bits` unconditionally, which seems reasonable. Then, it immediately checks if the device is started using `nbd->pid`. If it's *not* started, it just updates the configuration and returns 0. That makes sense, as the device isn't active.
My main concern is the `NBD_SET_BLKSIZE` ioctl. It seems like this could be called *before* the device is actually started, meaning `nbd->pid` would likely be zero. If this is the case, `nbd_set_size` just updates the config and that's it. However, the block size update to the block layer, and therefore queue limits, might not be happening *at that moment*.
It looks like the real change to queue limits is handled either during `NBD_DO_IT` (via `nbd_start_device`) or via netlink `nbd_genl_size_set`, and it's always followed by a call to `nbd_set_size`. So, the block size changes really happen when the device is started via `NBD_DO_IT` or changed via netlink while the device is running.
Therefore, checking `disk_openers` in `nbd_set_size` only makes sense if `nbd->pid` is set, because that's when we're actually changing queue limits. But wait, since `nbd_start_device` is the place where `nbd->pid` is first set, shouldn't we check `disk_openers(nbd->disk) > 1` *before* the call to `nbd_set_size` in that function? I mean, if someone else has the device open, should we even allow starting the device with new values? We probably shouldn't.
And if we fail `nbd_start_device`, we need to ensure all threads and the PID are cleaned up properly. That's a must.
Thinking it through, the best place to perform the check seems to be at the *beginning* of `nbd_start_device` -- before anything else happens. Let's revisit the implementation of `nbd_start_device`.
|
| 128/4 |
2026/05/10 03:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device]
Results: map[SourceCode:1471: static int nbd_start_device(struct nbd_device *nbd)
1472: {
1473: struct nbd_config *config = nbd->config;
1474: int num_connections = config->num_connections;
1475: int error = 0, i;
1476:
1477: if (nbd->pid)
1478: return -EBUSY;
1479: if (!config->socks)
1480: return -EINVAL;
1481: if (num_connections > 1 &&
1482: !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1483: dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1484: return -EINVAL;
1485: }
1486:
1487: retry:
1488: mutex_unlock(&nbd->config_lock);
1489: blk_mq_update_nr_hw_queues(&nbd->tag_set, num_connections);
1490: mutex_lock(&nbd->config_lock);
1491:
1492: /* if another code path updated nr_hw_queues, retry until succeed */
1493: if (num_connections != config->num_connections) {
1494: num_connections = config->num_connections;
1495: goto retry;
1496: }
1497:
1498: nbd->pid = task_pid_nr(current);
1499:
1500: nbd_parse_flags(nbd);
1501:
1502: error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1503: if (error) {
1504: dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1505: return error;
1506: }
1507: set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1508:
1509: nbd_dev_dbg_init(nbd);
1510: for (i = 0; i < num_connections; i++) {
1511: struct recv_thread_args *args;
1512:
1513: args = kzalloc_obj(*args);
1514: if (!args) {
1515: sock_shutdown(nbd);
1516: /*
1517: * If num_connections is m (2 < m),
1518: * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1519: * But NO.(n + 1) failed. We still have n recv threads.
1520: * So, add flush_workqueue here to prevent recv threads
1521: * dropping the last config_refs and trying to destroy
1522: * the workqueue from inside the workqueue.
1523: */
1524: if (i)
1525: flush_workqueue(nbd->recv_workq);
1526: return -ENOMEM;
1527: }
1528: sk_set_memalloc(config->socks[i]->sock->sk);
1529: if (nbd->tag_set.timeout)
1530: config->socks[i]->sock->sk->sk_sndtimeo =
1531: nbd->tag_set.timeout;
1532: atomic_inc(&config->recv_threads);
1533: refcount_inc(&nbd->config_refs);
1534: INIT_WORK(&args->work, recv_work);
1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
SourceFile:drivers/block/nbd.c]
|
| 129/4 |
2026/05/10 03:11 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 24854
output: 19
thoughts: 532
Thoughts: **Analyzing Device Openers and Claiming in the NBD Driver**
Okay, so I'm thinking about how we're currently handling device opening and exclusivity within the NBD driver, specifically when it comes to things like setting the device size. Right now, if we put that `if` statement at the beginning of `nbd_start_device` and check `disk_openers(nbd->disk) > 1`, that seems straightforward *until* you consider the different entry points. `nbd_start_device` gets called from both the `ioctl` path *and* the Netlink (`nbd_genl_connect`) path.
The problem is, if we enter through the Netlink path, the caller might not have a file descriptor open on the device. So, `disk_openers` might be 0 or 1. If *someone* has it open, `disk_openers` is > 0. For Netlink specifically, `disk_openers(nbd->disk) > 0` looks like it'd be the right check.
But wait, hold on. `nbd_genl_connect` might be called by a userspace program that doesn't have an open file *at all*. If another program *does* have it open (like if it's mounted), `disk_openers` will be > 0.
Okay, what if we move the check to `nbd_set_size`? We could do something like `if (nbd->pid && disk_openers(nbd->disk) > 1) return -EBUSY;`. But then I remember that `nbd_set_size` can be called from `nbd_genl_size_set`. And again, if it's mounted, `disk_openers` could be 1, so the `> 1` condition would be wrong!
So, the conclusion is that checking `disk_openers > 1` is *only* going to work if the *current thread* actually holds an open file descriptor on the device. That's a critical detail.
Then I recalled that the loop driver uses `bd_prepare_to_claim`, which checks if the device is *exclusively* claimed, meaning something like a filesystem has taken exclusive control. If it's just *opened*, like with `fdisk`, it's not exclusively claimed. Is that what we want?
Wait, yes, `bd_prepare_to_claim` checks for exclusive claim. But how can we check that? Can we use `bdev_is_claimed(bdev)`? Hmmm, no... I can't find that function. Maybe it's not exported. Let's check `include/linux/blkdev.h` or `block/bdev.c` for those claiming-related functions.
|
| 130/4 |
2026/05/10 03:11 |
tool |
grepper |
0m
Args: map[Expression:bd_may_claim]
Results: map[Output:block/bdev.c=524=long nr_blockdev_pages(void)
--
block/bdev.c-537-/**
block/bdev.c:538: * bd_may_claim - test whether a block device can be claimed
block/bdev.c-539- * @bdev: block device of interest
--
block/bdev.c-547- */
block/bdev.c:548:static bool bd_may_claim(struct block_device *bdev, void *holder,
block/bdev.c-549- const struct blk_holder_ops *hops)
--
block/bdev.c-567- /*
block/bdev.c:568: * If the whole devices holder is set to bd_may_claim, a partition on
block/bdev.c-569- * the device is claimed, but not the whole device.
--
block/bdev.c-571- if (whole != bdev &&
block/bdev.c:572: whole->bd_holder && whole->bd_holder != bd_may_claim)
block/bdev.c-573- return false;
--
block/bdev.c=590=int bd_prepare_to_claim(struct block_device *bdev, void *holder,
--
block/bdev.c-599- /* if someone else claimed, fail */
block/bdev.c:600: if (!bd_may_claim(bdev, holder, hops)) {
block/bdev.c-601- mutex_unlock(&bdev_lock);
--
block/bdev.c=642=static void bd_finish_claiming(struct block_device *bdev, void *holder,
--
block/bdev.c-647- mutex_lock(&bdev_lock);
block/bdev.c:648: BUG_ON(!bd_may_claim(bdev, holder, hops));
block/bdev.c-649- /*
block/bdev.c-650- * Note that for a whole device bd_holders will be incremented twice,
block/bdev.c:651: * and bd_holder will be set to bd_may_claim before being set to holder
block/bdev.c-652- */
block/bdev.c-653- whole->bd_holders++;
block/bdev.c:654: whole->bd_holder = bd_may_claim;
block/bdev.c-655- bdev->bd_holders++;
]
|
| 131/4 |
2026/05/10 03:12 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 26686
output: 17
thoughts: 97
Thoughts: **Block Device Conundrum**
Okay, so I'm trying to figure out if this block device is currently in use. My initial thought is to check `bdev->bd_holder`. If it's claimed, that pointer, `bdev->bd_holder`, should be pointing to something other than NULL. But, hold on a second... can I even *access* `bdev->bd_holder` directly if the device isn't exported? That feels like a potential access violation waiting to happen.
Hmm, I need a reliable way to determine if a block device is in use, especially in the kernel, because direct pointer access might not be the right answer. There *has* to be a function, or at least a macro, to determine if a block device is "claimed" or not.
Right, let's go to the source. I'll need to check `include/linux/blkdev.h` and search for either `bd_holder` itself, or maybe a function related to "claim" or "claimed". That should give me a solid way to proceed with this check and avoid any potential issues.
|
| 132/4 |
2026/05/10 03:12 |
tool |
grepper |
0m
Args: map[Expression:bd_holder]
Results: map[Output:Documentation/filesystems/porting.rst=990=underdocumented however:
--
Documentation/filesystems/porting.rst-1005- filesystem type the mounter would reuse the block device and allocate a new
Documentation/filesystems/porting.rst:1006: superblock (the bd_holder point may still be set to the filesystem type).
Documentation/filesystems/porting.rst-1007-
--
Documentation/filesystems/porting.rst=1021=filesystem type is now moved to a later point when the devices are closed:
--
Documentation/filesystems/porting.rst-1032- list of superblocks of the filesystem type. The mounter will allocate a new
Documentation/filesystems/porting.rst:1033: superblock and grab ownership of the block device (the bd_holder pointer of
Documentation/filesystems/porting.rst-1034- the block device will be set to the newly allocated superblock).
--
Documentation/filesystems/porting.rst-1039- superblock of the filesystem type anymore then it has given up ownership of
Documentation/filesystems/porting.rst:1040: all associated block devices (the bd_holder pointer is NULL).
Documentation/filesystems/porting.rst-1041-
--
block/bdev.c=301=int bdev_freeze(struct block_device *bdev)
--
block/bdev.c-311-
block/bdev.c:312: mutex_lock(&bdev->bd_holder_lock);
block/bdev.c:313: if (bdev->bd_holder_ops && bdev->bd_holder_ops->freeze) {
block/bdev.c:314: error = bdev->bd_holder_ops->freeze(bdev);
block/bdev.c:315: lockdep_assert_not_held(&bdev->bd_holder_lock);
block/bdev.c-316- } else {
block/bdev.c:317: mutex_unlock(&bdev->bd_holder_lock);
block/bdev.c-318- error = sync_blockdev(bdev);
--
block/bdev.c=337=int bdev_thaw(struct block_device *bdev)
--
block/bdev.c-354-
block/bdev.c:355: mutex_lock(&bdev->bd_holder_lock);
block/bdev.c:356: if (bdev->bd_holder_ops && bdev->bd_holder_ops->thaw) {
block/bdev.c:357: error = bdev->bd_holder_ops->thaw(bdev);
block/bdev.c:358: lockdep_assert_not_held(&bdev->bd_holder_lock);
block/bdev.c-359- } else {
block/bdev.c:360: mutex_unlock(&bdev->bd_holder_lock);
block/bdev.c-361- }
--
block/bdev.c=464=struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
--
block/bdev.c-479- spin_lock_init(&bdev->bd_size_lock);
block/bdev.c:480: mutex_init(&bdev->bd_holder_lock);
block/bdev.c-481- atomic_set(&bdev->__bd_flags, partno);
--
block/bdev.c=548=static bool bd_may_claim(struct block_device *bdev, void *holder,
--
block/bdev.c-554-
block/bdev.c:555: if (bdev->bd_holder) {
block/bdev.c-556- /*
--
block/bdev.c-558- */
block/bdev.c:559: if (bdev->bd_holder == holder) {
block/bdev.c:560: if (WARN_ON_ONCE(bdev->bd_holder_ops != hops))
block/bdev.c-561- return false;
--
block/bdev.c-571- if (whole != bdev &&
block/bdev.c:572: whole->bd_holder && whole->bd_holder != bd_may_claim)
block/bdev.c-573- return false;
--
block/bdev.c-584- * holder and waits if another claiming is in progress. return, the caller
block/bdev.c:585: * has ownership of bd_claiming and bd_holder[s].
block/bdev.c-586- *
--
block/bdev.c=642=static void bd_finish_claiming(struct block_device *bdev, void *holder,
--
block/bdev.c-649- /*
block/bdev.c:650: * Note that for a whole device bd_holders will be incremented twice,
block/bdev.c:651: * and bd_holder will be set to bd_may_claim before being set to holder
block/bdev.c-652- */
block/bdev.c:653: whole->bd_holders++;
block/bdev.c:654: whole->bd_holder = bd_may_claim;
block/bdev.c:655: bdev->bd_holders++;
block/bdev.c:656: mutex_lock(&bdev->bd_holder_lock);
block/bdev.c:657: bdev->bd_holder = holder;
block/bdev.c:658: bdev->bd_holder_ops = hops;
block/bdev.c:659: mutex_unlock(&bdev->bd_holder_lock);
block/bdev.c-660- bd_clear_claiming(whole, holder);
--
block/bdev.c=681=static void bd_end_claim(struct block_device *bdev, void *holder)
--
block/bdev.c-690- mutex_lock(&bdev_lock);
block/bdev.c:691: WARN_ON_ONCE(bdev->bd_holder != holder);
block/bdev.c:692: WARN_ON_ONCE(--bdev->bd_holders < 0);
block/bdev.c:693: WARN_ON_ONCE(--whole->bd_holders < 0);
block/bdev.c:694: if (!bdev->bd_holders) {
block/bdev.c:695: mutex_lock(&bdev->bd_holder_lock);
block/bdev.c:696: bdev->bd_holder = NULL;
block/bdev.c:697: bdev->bd_holder_ops = NULL;
block/bdev.c:698: mutex_unlock(&bdev->bd_holder_lock);
block/bdev.c-699- if (bdev_test_flag(bdev, BD_WRITE_HOLDER))
--
block/bdev.c-701- }
block/bdev.c:702: if (!whole->bd_holders)
block/bdev.c:703: whole->bd_holder = NULL;
block/bdev.c-704- mutex_unlock(&bdev_lock);
--
block/bdev.c=716=static void blkdev_flush_mapping(struct block_device *bdev)
block/bdev.c-717-{
block/bdev.c:718: WARN_ON_ONCE(bdev->bd_holders);
block/bdev.c-719- sync_blockdev(bdev);
--
block/bdev.c=1246=void bdev_mark_dead(struct block_device *bdev, bool surprise)
block/bdev.c-1247-{
block/bdev.c:1248: mutex_lock(&bdev->bd_holder_lock);
block/bdev.c:1249: if (bdev->bd_holder_ops && bdev->bd_holder_ops->mark_dead)
block/bdev.c:1250: bdev->bd_holder_ops->mark_dead(bdev, surprise);
block/bdev.c-1251- else {
block/bdev.c:1252: mutex_unlock(&bdev->bd_holder_lock);
block/bdev.c-1253- sync_blockdev(bdev);
--
block/genhd.c=431=static int __add_disk(struct device *parent, struct gendisk *disk,
--
block/genhd.c-515-
block/genhd.c:516: disk->part0->bd_holder_dir =
block/genhd.c-517- kobject_create_and_add("holders", &ddev->kobj);
block/genhd.c:518: if (!disk->part0->bd_holder_dir) {
block/genhd.c-519- ret = -ENOMEM;
--
block/genhd.c-561-out_put_holder_dir:
block/genhd.c:562: kobject_put(disk->part0->bd_holder_dir);
block/genhd.c-563-out_del_block_link:
--
block/genhd.c=693=static void __del_gendisk(struct gendisk *disk)
--
block/genhd.c-744-
block/genhd.c:745: kobject_put(disk->part0->bd_holder_dir);
block/genhd.c-746- kobject_put(disk->slave_dir);
--
block/holder.c-4-
block/holder.c:5:struct bd_holder_disk {
block/holder.c-6- struct list_head list;
--
block/holder.c=11=static DEFINE_MUTEX(blk_holder_mutex);
block/holder.c-12-
block/holder.c:13:static struct bd_holder_disk *bd_find_holder_disk(struct block_device *bdev,
block/holder.c-14- struct gendisk *disk)
block/holder.c-15-{
block/holder.c:16: struct bd_holder_disk *holder;
block/holder.c-17-
block/holder.c-18- list_for_each_entry(holder, &disk->slave_bdevs, list)
block/holder.c:19: if (holder->holder_dir == bdev->bd_holder_dir)
block/holder.c-20- return holder;
--
block/holder.c=62=int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk)
block/holder.c-63-{
block/holder.c:64: struct bd_holder_disk *holder;
block/holder.c-65- int ret = 0;
--
block/holder.c-73- /*
block/holder.c:74: * del_gendisk drops the initial reference to bd_holder_dir, so we
block/holder.c-75- * need to keep our own here to allow for cleanup past that point.
--
block/holder.c-81- }
block/holder.c:82: kobject_get(bdev->bd_holder_dir);
block/holder.c-83- mutex_unlock(&bdev->bd_disk->open_mutex);
--
block/holder.c-85- mutex_lock(&blk_holder_mutex);
block/holder.c:86: WARN_ON_ONCE(!bdev->bd_holder);
block/holder.c-87-
--
block/holder.c-89- if (holder) {
block/holder.c:90: kobject_put(bdev->bd_holder_dir);
block/holder.c-91- holder->refcnt++;
--
block/holder.c-102- holder->refcnt = 1;
block/holder.c:103: holder->holder_dir = bdev->bd_holder_dir;
block/holder.c-104-
--
block/holder.c-107- goto out_free_holder;
block/holder.c:108: ret = add_symlink(bdev->bd_holder_dir, &disk_to_dev(disk)->kobj);
block/holder.c-109- if (ret)
--
block/holder.c-122- if (ret)
block/holder.c:123: kobject_put(bdev->bd_holder_dir);
block/holder.c-124- return ret;
--
block/holder.c=138=void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk)
block/holder.c-139-{
block/holder.c:140: struct bd_holder_disk *holder;
block/holder.c-141-
--
block/ioctl.c=512=static int blkdev_flushbuf(struct block_device *bdev, unsigned cmd,
--
block/ioctl.c-517-
block/ioctl.c:518: mutex_lock(&bdev->bd_holder_lock);
block/ioctl.c:519: if (bdev->bd_holder_ops && bdev->bd_holder_ops->sync)
block/ioctl.c:520: bdev->bd_holder_ops->sync(bdev);
block/ioctl.c-521- else {
block/ioctl.c:522: mutex_unlock(&bdev->bd_holder_lock);
block/ioctl.c-523- sync_blockdev(bdev);
--
block/partitions/core.c=273=void drop_partition(struct block_device *part)
--
block/partitions/core.c-277- xa_erase(&part->bd_disk->part_tbl, bdev_partno(part));
block/partitions/core.c:278: kobject_put(part->bd_holder_dir);
block/partitions/core.c-279-
--
block/partitions/core.c=295=static struct block_device *add_partition(struct gendisk *disk, int partno,
--
block/partitions/core.c-371- err = -ENOMEM;
block/partitions/core.c:372: bdev->bd_holder_dir = kobject_create_and_add("holders", &pdev->kobj);
block/partitions/core.c:373: if (!bdev->bd_holder_dir)
block/partitions/core.c-374- goto out_del;
--
block/partitions/core.c-397-out_del:
block/partitions/core.c:398: kobject_put(bdev->bd_holder_dir);
block/partitions/core.c-399- device_del(pdev);
--
block/partitions/core.c=459=int bdev_del_partition(struct gendisk *disk, int partno)
--
block/partitions/core.c-474- * We verified that @part->bd_openers is zero above and so
block/partitions/core.c:475: * @part->bd_holder{_ops} can't be set. And since we hold
block/partitions/core.c-476- * @disk->open_mutex the device can't be claimed by anyone.
block/partitions/core.c-477- *
block/partitions/core.c:478: * So no need to call @part->bd_holder_ops->mark_dead() here.
block/partitions/core.c-479- * Just delete the partition and invalidate it.
--
fs/super.c=1410=EXPORT_SYMBOL(sget_dev);
--
fs/super.c-1415- * pointer if we successfully locked the superblock and it is alive. Otherwise
fs/super.c:1416: * we return NULL and just unlock bdev->bd_holder_lock.
fs/super.c-1417- *
fs/super.c:1418: * The function must be called with bdev->bd_holder_lock and releases it.
fs/super.c-1419- */
fs/super.c=1420=static struct super_block *bdev_super_lock(struct block_device *bdev, bool excl)
fs/super.c:1421: __releases(&bdev->bd_holder_lock)
fs/super.c-1422-{
fs/super.c:1423: struct super_block *sb = bdev->bd_holder;
fs/super.c-1424- bool locked;
fs/super.c-1425-
fs/super.c:1426: lockdep_assert_held(&bdev->bd_holder_lock);
fs/super.c-1427- lockdep_assert_not_held(&sb->s_umount);
--
fs/super.c-1434-
fs/super.c:1435: mutex_unlock(&bdev->bd_holder_lock);
fs/super.c-1436-
--
include/linux/blk_types.h=41=struct block_device {
--
include/linux/blk_types.h-62- void * bd_claiming;
include/linux/blk_types.h:63: void * bd_holder;
include/linux/blk_types.h:64: const struct blk_holder_ops *bd_holder_ops;
include/linux/blk_types.h:65: struct mutex bd_holder_lock;
include/linux/blk_types.h:66: int bd_holders;
include/linux/blk_types.h:67: struct kobject *bd_holder_dir;
include/linux/blk_types.h-68-
]
|
| 133/4 |
2026/05/10 03:12 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 31666
output: 17
thoughts: 83
Thoughts: Okay, let me think this through.
**Analyzing Block Device Claiming in the Kernel**
Right, so I'm trying to figure out how to determine if a block device is exclusively claimed, and it seems like `bdev->bd_holders` is the key. That would be the number of exclusive claims on the device. Simple: If it's greater than zero, then it's exclusively claimed. But wait a minute... I seem to recall that variable not being directly exported. Darn, that means I can't access it directly.
Okay, no problem. Let's see if there's a helper function available. I'll need to check `include/linux/blkdev.h`. Specifically, I'll be looking for `bd_holders` or something with `bdev_is_claimed` in the name. Hopefully, there's a nicely packaged function in there to handle this check for me. That would be much cleaner. Let's dig in and see what's what.
|
| 134/4 |
2026/05/10 03:12 |
tool |
grepper |
0m
Args: map[Expression:bd_holders]
Results: map[Output:block/bdev.c=642=static void bd_finish_claiming(struct block_device *bdev, void *holder,
--
block/bdev.c-649- /*
block/bdev.c:650: * Note that for a whole device bd_holders will be incremented twice,
block/bdev.c-651- * and bd_holder will be set to bd_may_claim before being set to holder
block/bdev.c-652- */
block/bdev.c:653: whole->bd_holders++;
block/bdev.c-654- whole->bd_holder = bd_may_claim;
block/bdev.c:655: bdev->bd_holders++;
block/bdev.c-656- mutex_lock(&bdev->bd_holder_lock);
--
block/bdev.c=681=static void bd_end_claim(struct block_device *bdev, void *holder)
--
block/bdev.c-691- WARN_ON_ONCE(bdev->bd_holder != holder);
block/bdev.c:692: WARN_ON_ONCE(--bdev->bd_holders < 0);
block/bdev.c:693: WARN_ON_ONCE(--whole->bd_holders < 0);
block/bdev.c:694: if (!bdev->bd_holders) {
block/bdev.c-695- mutex_lock(&bdev->bd_holder_lock);
--
block/bdev.c-701- }
block/bdev.c:702: if (!whole->bd_holders)
block/bdev.c-703- whole->bd_holder = NULL;
--
block/bdev.c=716=static void blkdev_flush_mapping(struct block_device *bdev)
block/bdev.c-717-{
block/bdev.c:718: WARN_ON_ONCE(bdev->bd_holders);
block/bdev.c-719- sync_blockdev(bdev);
--
include/linux/blk_types.h=41=struct block_device {
--
include/linux/blk_types.h-65- struct mutex bd_holder_lock;
include/linux/blk_types.h:66: int bd_holders;
include/linux/blk_types.h-67- struct kobject *bd_holder_dir;
]
|
| 135/4 |
2026/05/10 03:12 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 32622
output: 46
thoughts: 783
Thoughts: **Analyzing Device Size Modification in the NBD Driver**
Okay, so I'm looking at how we handle size changes in the NBD driver. The current code avoids using `bd_prepare_to_claim`, as it's meant specifically for the loop driver. Instead, I was considering using `disk_openers(disk) > 1` to prevent size changes if someone else has the device open. That seems appropriate.
I started to dig into similar implementations. I see that both `zram_drv.c` and `ublk_drv.c` correctly use `disk_openers` to block operations if a device is already busy. In `nbd.c`, the `nbd_bdev_reset` function also uses `disk_openers(nbd->disk) > 1`, but it doesn't block the operation.
My initial thought was to implement `disk_openers(nbd->disk) > 1` in `nbd_set_size`. But then I hit a potential snag when considering `nbd_genl_size_set`, which is called from netlink. Here, the caller *doesn't* have the device open. So, `disk_openers` could be 1, because the device might be mounted. If I checked `> 1` as initially planned, it would allow a size change even if the device is mounted! I had to verify the assumptions.
I confirmed that when a device is mounted using `mount`, `disk_openers` increments to 1, because the mount operation opens the device. Therefore, with `nbd_genl_size_set` using netlink, the mount operation would keep the `disk_openers` to `1`.
If I implemented `disk_openers > 1`, it would allow the size change in `nbd_genl_size_set` because `disk_openers` would be 1. This is wrong! Now I need to see if the caller has the device open.
On the other hand, `nbd_ioctl` *does* have the device open, and if it's mounted, `disk_openers` would be 2. So with `nbd_ioctl`, `disk_openers > 1` is correct.
So, in essence, `disk_openers > 1` is correct for `nbd_ioctl`, but not for `nbd_genl_size_set`. The function `nbd_set_size` doesn't know who is calling it. But, wait, I can check the `config->runtime_flags` by checking the bit `NBD_RT_BOUND`. Let me go check `nbd_genl_size_set`.
|
| 136/4 |
2026/05/10 03:12 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_genl_size_set]
Results: map[SourceCode:2056: static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
2057: {
2058: struct nbd_config *config = nbd->config;
2059: u64 bsize = nbd_blksize(config);
2060: u64 bytes = config->bytesize;
2061:
2062: if (info->attrs[NBD_ATTR_SIZE_BYTES])
2063: bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
2064:
2065: if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
2066: bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
2067:
2068: if (bytes != config->bytesize || bsize != nbd_blksize(config))
2069: return nbd_set_size(nbd, bytes, bsize);
2070: return 0;
2071: }
SourceFile:drivers/block/nbd.c]
|
| 137/4 |
2026/05/10 03:12 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 34382
output: 45
thoughts: 41
Thoughts: Here's my take on the thought process:
**Diving into the Network Block Device Reconfiguration**
Okay, so I'm digging into this Network Block Device code, and I see `nbd_genl_size_set` popping up. That rings a bell... I believe it's used within `nbd_genl_reconfigure`. It seems like we're looking at a size change as part of the reconfigure process, right? Let me switch gears and immediately go check out `nbd_genl_reconfigure` to figure out what's really happening here. Need to understand the broader context of the size setting within the reconfiguration sequence.
|
| 138/4 |
2026/05/10 03:13 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_genl_reconfigure]
Results: map[SourceCode:2310: static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2311: {
2312: struct nbd_device *nbd = NULL;
2313: struct nbd_config *config;
2314: int index;
2315: int ret = 0;
2316: bool put_dev = false;
2317:
2318: if (!netlink_capable(skb, CAP_SYS_ADMIN))
2319: return -EPERM;
2320:
2321: if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2322: pr_err("must specify a device to reconfigure\n");
2323: return -EINVAL;
2324: }
2325: index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2326: mutex_lock(&nbd_index_mutex);
2327: nbd = idr_find(&nbd_index_idr, index);
2328: if (!nbd) {
2329: mutex_unlock(&nbd_index_mutex);
2330: pr_err("couldn't find a device at index %d\n", index);
2331: return -EINVAL;
2332: }
2333: if (nbd->backend) {
2334: if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2335: if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2336: nbd->backend)) {
2337: mutex_unlock(&nbd_index_mutex);
2338: dev_err(nbd_to_dev(nbd),
2339: "backend image doesn't match with %s\n",
2340: nbd->backend);
2341: return -EINVAL;
2342: }
2343: } else {
2344: mutex_unlock(&nbd_index_mutex);
2345: dev_err(nbd_to_dev(nbd), "must specify backend\n");
2346: return -EINVAL;
2347: }
2348: }
2349: if (!refcount_inc_not_zero(&nbd->refs)) {
2350: mutex_unlock(&nbd_index_mutex);
2351: pr_err("device at index %d is going down\n", index);
2352: return -EINVAL;
2353: }
2354: mutex_unlock(&nbd_index_mutex);
2355:
2356: config = nbd_get_config_unlocked(nbd);
2357: if (!config) {
2358: dev_err(nbd_to_dev(nbd),
2359: "not configured, cannot reconfigure\n");
2360: nbd_put(nbd);
2361: return -EINVAL;
2362: }
2363:
2364: mutex_lock(&nbd->config_lock);
2365: if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2366: !nbd->pid) {
2367: dev_err(nbd_to_dev(nbd),
2368: "not configured, cannot reconfigure\n");
2369: ret = -EINVAL;
2370: goto out;
2371: }
2372:
2373: ret = nbd_genl_size_set(info, nbd);
2374: if (ret)
2375: goto out;
2376:
2377: if (info->attrs[NBD_ATTR_TIMEOUT])
2378: nbd_set_cmd_timeout(nbd,
2379: nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2380: if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2381: config->dead_conn_timeout =
2382: nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2383: config->dead_conn_timeout *= HZ;
2384: }
2385: if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2386: u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2387: if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2388: if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2389: &nbd->flags))
2390: put_dev = true;
2391: } else {
2392: if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2393: &nbd->flags))
2394: refcount_inc(&nbd->refs);
2395: }
2396:
2397: if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2398: set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2399: &config->runtime_flags);
2400: } else {
2401: clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2402: &config->runtime_flags);
2403: }
2404: }
2405:
2406: if (info->attrs[NBD_ATTR_SOCKETS]) {
2407: struct nlattr *attr;
2408: int rem, fd;
2409:
2410: nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2411: rem) {
2412: struct nlattr *socks[NBD_SOCK_MAX+1];
2413:
2414: if (nla_type(attr) != NBD_SOCK_ITEM) {
2415: pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2416: ret = -EINVAL;
2417: goto out;
2418: }
2419: ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2420: attr,
2421: nbd_sock_policy,
2422: info->extack);
2423: if (ret != 0) {
2424: pr_err("error processing sock list\n");
2425: ret = -EINVAL;
2426: goto out;
2427: }
2428: if (!socks[NBD_SOCK_FD])
2429: continue;
2430: fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2431: ret = nbd_reconnect_socket(nbd, fd);
2432: if (ret) {
2433: if (ret == -ENOSPC)
2434: ret = 0;
2435: goto out;
2436: }
2437: dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2438: }
2439: }
2440: out:
2441: mutex_unlock(&nbd->config_lock);
2442: nbd_config_put(nbd);
2443: nbd_put(nbd);
2444: if (put_dev)
2445: nbd_put(nbd);
2446: return ret;
2447: }
SourceFile:drivers/block/nbd.c]
|
| 139/4 |
2026/05/10 03:13 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 36828
output: 25
thoughts: 944
Thoughts: **Analyzing Block Size Reconfiguration with NBD**
Alright, let's break this down. I'm looking at how we prevent changes to the block size of an NBD device while it's in use, specifically, preventing it from being modified when mounted. It seems `nbd_genl_reconfigure` is the key entry point via netlink, and it's where we need to implement the restriction. My initial thought was to check if the device is exclusively claimed, but `bdev_is_claimed` isn't available. I remember we were using `disk_openers` before, but there are nuances.
Initially, I considered checking `disk_openers(nbd->disk) > 1`. However, if the `nbd_genl_reconfigure` path is triggered by a netlink call, the caller doesn't have the device open; it's the kernel doing the reconfiguration. So, if `disk_openers(nbd->disk) > 0`, it would indicate *someone* has it open. But here's the catch: the `disk_openers` count includes the caller when the device is accessed via `nbd_ioctl`, but not with netlink. That is, `disk_openers` would be 1 when the device is mounted, and therefore allow the change because the comparison `disk_openers > 1` is false.
I then explored checking `disk_openers` within `nbd_set_size`, which is called from both ioctl and netlink paths. But that won't work either! The `disk_openers` count would include the ioctl caller, but not the netlink caller. So we can't use `disk_openers > 1` in `nbd_set_size` because it'll fail the netlink call.
I also considered checking `disk_openers > 0` at the netlink entry points (`nbd_genl_connect`, `nbd_genl_reconfigure`) and `disk_openers > 1` in the ioctl path. However, a userspace program (like `nbd-client`) could open the device first and then use netlink. That's a valid scenario! In this case, `disk_openers` would be 1. Checking `> 0` would then inappropriately block the netlink reconfiguration.
So, I'm stuck. We can't rely solely on `disk_openers`. It does not provide the correct level of granularity for the netlink path. It will allow a reconfiguration when it should not be allowed.
Thinking harder, I am now considering `bd_prepare_to_claim`, which is part of the block device claim mechanism. In `nbd_ioctl`, we have the `bdev` struct. With netlink, we only have `nbd->disk->part0`. But `bd_prepare_to_claim` is specifically exported for the loop driver (?!). Can we even use this in `nbd.c`? We'll have to see if the symbol is exported with a suitable macro like `EXPORT_SYMBOL` or `EXPORT_SYMBOL_GPL`.
|
| 140/4 |
2026/05/10 03:13 |
tool |
grepper |
0m
Args: map[Expression:EXPORT_SYMBOL.*bd_prepare_to_claim]
Results: map[Output:block/bdev.c=590=int bd_prepare_to_claim(struct block_device *bdev, void *holder,
--
block/bdev.c-621-}
block/bdev.c:622:EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
block/bdev.c-623-
]
|
| 141/4 |
2026/05/10 03:13 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 38585
output: 23
thoughts: 144
Thoughts: **Considering `bd_prepare_to_claim` for NBD**
Okay, so I see this `EXPORT_SYMBOL_GPL(bd_prepare_to_claim);` thing. It's marked for the loop driver, but I'm thinking about using it in `nbd.c`. The comment's a little misleading; the core problem is likely the same here. `nbd.c` *is* a block driver, just like `loop.c`, so functionally, there shouldn't be a problem. This should be fine, and I can always refactor the code later.
However, if I'm going to use `bd_prepare_to_claim`, then I *have* to remember to call `bd_abort_claiming` if, for whatever reason, I don't actually end up claiming the block device. It's important to keep the system consistent. Gotta make sure everything gets cleaned up properly. Okay, let me quickly double-check the definition of `bd_abort_claiming` to make sure there are no gotchas.
|
| 142/4 |
2026/05/10 03:14 |
tool |
grepper |
0m
Args: map[Expression:EXPORT_SYMBOL.*bd_abort_claiming]
Results: map[Output:block/bdev.c=673=void bd_abort_claiming(struct block_device *bdev, void *holder)
--
block/bdev.c-678-}
block/bdev.c:679:EXPORT_SYMBOL(bd_abort_claiming);
block/bdev.c-680-
]
|
| 143/4 |
2026/05/10 03:14 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 39071
output: 43
thoughts: 26
Thoughts: Here's my take on the thought process, as requested:
**Digging into the `bd_abort_claiming` Export**
Okay, so I've confirmed that `bd_abort_claiming` *is* indeed exported. Now, the real question is how it's actually being *used*. Time to dive into `loop.c`. Understanding its implementation and its interaction with `bd_abort_claiming` will tell me a lot. The context in `loop.c` must be where the core logic exists. Let's see if this answers the original problem.
|
| 144/4 |
2026/05/10 03:14 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/loop.c IncludeLines:true Name:loop_set_block_size]
Results: map[SourceCode:1445: static int loop_set_block_size(struct loop_device *lo, blk_mode_t mode,
1446: struct block_device *bdev, unsigned long arg)
1447: {
1448: struct queue_limits lim;
1449: unsigned int memflags;
1450: int err = 0;
1451:
1452: /*
1453: * If we don't hold exclusive handle for the device, upgrade to it
1454: * here to avoid changing device under exclusive owner.
1455: */
1456: if (!(mode & BLK_OPEN_EXCL)) {
1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
1458: if (err)
1459: return err;
1460: }
1461:
1462: err = mutex_lock_killable(&lo->lo_mutex);
1463: if (err)
1464: goto abort_claim;
1465:
1466: if (lo->lo_state != Lo_bound) {
1467: err = -ENXIO;
1468: goto unlock;
1469: }
1470:
1471: if (lo->lo_queue->limits.logical_block_size == arg)
1472: goto unlock;
1473:
1474: sync_blockdev(lo->lo_device);
1475: invalidate_bdev(lo->lo_device);
1476:
1477: lim = queue_limits_start_update(lo->lo_queue);
1478: loop_update_limits(lo, &lim, arg);
1479:
1480: memflags = blk_mq_freeze_queue(lo->lo_queue);
1481: err = queue_limits_commit_update(lo->lo_queue, &lim);
1482: loop_update_dio(lo);
1483: blk_mq_unfreeze_queue(lo->lo_queue, memflags);
1484:
1485: unlock:
1486: mutex_unlock(&lo->lo_mutex);
1487: abort_claim:
1488: if (!(mode & BLK_OPEN_EXCL))
1489: bd_abort_claiming(bdev, loop_set_block_size);
1490: return err;
1491: }
SourceFile:drivers/block/loop.c]
|
| 145/4 |
2026/05/10 03:14 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 39981
output: 41
thoughts: 294
Thoughts: **Analyzing Block Device Claiming in NBD**
Okay, so I'm looking at how we handle block size setting and device claiming, specifically in the Network Block Device (NBD) driver. It seems like `loop_set_block_size` has `mode` and `bdev` readily available. However, in `nbd_set_size`, we don't have those straightforwardly. I realize, though, that we *can* get `bdev` from `nbd->disk->part0`. But wait...`nbd->disk->part0` represents the *whole* block device, right?
So, the next thought is if I use `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`, it should check if this device is exclusively claimed. That makes sense. If the device *is* exclusively claimed, then `bd_prepare_to_claim` should return `-EBUSY`. If it isn't, it returns 0 and sets `bd_claiming`, meaning we can proceed with our operations and eventually call `bd_abort_claiming`.
But hold on...What if a caller *already* holds an exclusive claim? That's a potential race condition! For example, is there a scenario where `mount` might call `nbd_set_size`? I don't *think* so...`mount` calls `udf_fill_super`, and I don't recall that calling `nbd_set_size`. So, that specific case should be safe.
Let's see… `nbd_set_size` is called from either `nbd_ioctl` or `nbd_genl_size_set`. Now, does `nbd_ioctl` hold an exclusive claim? That's the key question. We need to check the `nbd_ioctl` mode to know how it might be interacting with the block device claiming.
|
| 146/4 |
2026/05/10 03:16 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_ioctl]
Results: map[SourceCode:1640: static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1641: unsigned int cmd, unsigned long arg)
1642: {
1643: struct nbd_device *nbd = bdev->bd_disk->private_data;
1644: struct nbd_config *config = nbd->config;
1645: int error = -EINVAL;
1646:
1647: if (!capable(CAP_SYS_ADMIN))
1648: return -EPERM;
1649:
1650: /* The block layer will pass back some non-nbd ioctls in case we have
1651: * special handling for them, but we don't so just return an error.
1652: */
1653: if (_IOC_TYPE(cmd) != 0xab)
1654: return -EINVAL;
1655:
1656: mutex_lock(&nbd->config_lock);
1657:
1658: /* Don't allow ioctl operations on a nbd device that was created with
1659: * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1660: */
1661: if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1662: (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1663: error = __nbd_ioctl(bdev, nbd, cmd, arg);
1664: else
1665: dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1666: mutex_unlock(&nbd->config_lock);
1667: return error;
1668: }
SourceFile:drivers/block/nbd.c]
|
| 147/4 |
2026/05/10 03:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 41264
output: 51
thoughts: 795
Thoughts: **Analyzing the BLK_OPEN_EXCL Logic in nbd_ioctl and nbd_set_size**
Okay, so I'm looking at how `nbd_ioctl` handles the `BLK_OPEN_EXCL` flag, and I've spotted a potential issue. Currently, `nbd_ioctl` receives a `mode` value, but crucially, it doesn't pass it down to `__nbd_ioctl`. This could be a problem because if `mode & BLK_OPEN_EXCL` is set, it means the caller *already* has exclusive access to the device.
If we blindly call `bd_prepare_to_claim` with `nbd_set_size` as the claimant, it'll fail with `-EBUSY` because the caller, with the exclusive claim, already "owns" `bdev->bd_holder`. The problem is, without `mode`, we can't tell if we *should* skip `bd_prepare_to_claim`.
I need to figure out when this exclusive claim behavior actually matters. `nbd-client` usually opens the device *without* `O_EXCL`, so it's probably not a common use case.
I see that `loop.c` handles this situation correctly, calling `bd_prepare_to_claim` only if `!(mode & BLK_OPEN_EXCL)`. That's the behavior I'm aiming for. I realize I need to pass the `mode` down to `__nbd_ioctl` and subsequently `nbd_set_size`.
But, wait, what about the netlink path? Netlink doesn't even receive a `mode` parameter. For netlink calls, we can assume that there's *no* exclusive claim, and always proceed to call `bd_prepare_to_claim`. And if the device is already mounted, it will return `-EBUSY` when calling `bd_prepare_to_claim`, which is the correct behaviour!
So if `nbd_ioctl` is called, yes, pass `mode` down to `__nbd_ioctl` and `nbd_set_size`.
Now I need to address the calls to `nbd_set_size` that happen elsewhere, specifically from `nbd_start_device`, which is called from both `nbd_start_device_ioctl` *and* `nbd_genl_connect`. How do I provide the `mode` from these? I can change the signature for `nbd_set_size` to take `bdev` and `mode`.
```c
static int nbd_set_size(struct nbd_device *nbd, struct block_device *bdev,
int mode, loff_t bytesize, loff_t blksize)
```
But, `nbd_start_device` doesn't provide these either. I can get `bdev` from `nbd->disk->part0`, this seems reasonable. I can get `mode` from ioctl or from netlink calls, which I can just set to 0.
Now I need to trace the callers of `nbd_start_device` to be sure I have all the information. I think I'm on the right track now.
|
| 148/4 |
2026/05/10 03:16 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeSnippetLines:0 Name:nbd_start_device SourceTreePrefix:]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_genl_connect SourceFile:drivers/block/nbd.c SourceLine:2239] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_start_device_ioctl SourceFile:drivers/block/nbd.c SourceLine:1548]] TruncatedOutput:false]
|
| 149/4 |
2026/05/10 03:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 42947
output: 45
thoughts: 35
Thoughts: Here's my summary, as the expert:
**Diving into the ioctl Calls for Network Block Devices**
Okay, so I'm tracing down this `nbd_ioctl` thing, and it looks like the kernel is calling `nbd_start_device_ioctl` from within that function. Makes sense, that's where I'd expect the main handling logic to be. Time to dig into `nbd_start_device_ioctl`. I want to understand exactly what happens at this level; I need to know how the network block device is getting started through this specific ioctl path. I'm going to look at the interactions with the specific device and the data flow, paying close attention to any error conditions and resource management. Let's see what's what.
|
| 150/4 |
2026/05/10 03:16 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device_ioctl]
Results: map[SourceCode:1543: static int nbd_start_device_ioctl(struct nbd_device *nbd)
1544: {
1545: struct nbd_config *config = nbd->config;
1546: int ret;
1547:
1548: ret = nbd_start_device(nbd);
1549: if (ret)
1550: return ret;
1551:
1552: if (max_part)
1553: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1554: mutex_unlock(&nbd->config_lock);
1555: ret = wait_event_interruptible(config->recv_wq,
1556: atomic_read(&config->recv_threads) == 0);
1557: if (ret) {
1558: sock_shutdown(nbd);
1559: nbd_clear_que(nbd);
1560: }
1561:
1562: flush_workqueue(nbd->recv_workq);
1563: mutex_lock(&nbd->config_lock);
1564: nbd_bdev_reset(nbd);
1565: /* user requested, ignore socket errors */
1566: if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1567: ret = 0;
1568: if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1569: ret = -ETIMEDOUT;
1570: return ret;
1571: }
SourceFile:drivers/block/nbd.c]
|
| 151/4 |
2026/05/10 03:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 43678
output: 43
thoughts: 240
Thoughts: **Refining the ioctl Handling for NBD**
Okay, so I'm thinking about how to handle the `bdev` and `mode` parameters within the Network Block Device (NBD) ioctl calls. The initial idea was to pass both `bdev` (the block device) and `mode` down to `nbd_ioctl`, which already receives them. Then, `nbd_ioctl` would call `__nbd_ioctl`, and I realized, hold on a second, `__nbd_ioctl` *doesn't* actually take a `mode` argument right now. That's easily fixed, though – we can add it:
```c
static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
blk_mode_t mode, unsigned int cmd, unsigned long arg)
```
Now, within `__nbd_ioctl`, we'd be able to forward `bdev` and `mode` to functions like `nbd_set_size` or something similar, and that would give us the flexibility we need.
But then a thought hits me. Why are we passing `bdev` at all? Isn't `nbd->disk->part0` essentially the same as `bdev` when we're dealing with the entire device? It is! `nbd->disk->part0` *is* the `bdev` representing the whole device. So, we really only need to pass the `mode` parameter. That simplifies things considerably. This looks like a good optimization, especially since the `mode` will be zero for netlink operations.
Okay, let's take another look at the `nbd_set_size` function to be sure this is working exactly as I envision. I want to make sure I'm not overlooking anything.
|
| 152/4 |
2026/05/10 03:16 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_set_size]
Results: map[SourceCode: 334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
335: {
336: struct queue_limits lim;
337: int error;
338:
339: if (!blksize)
340: blksize = 1u << NBD_DEF_BLKSIZE_BITS;
341:
342: if (blk_validate_block_size(blksize))
343: return -EINVAL;
344:
345: if (bytesize < 0)
346: return -EINVAL;
347:
348: nbd->config->bytesize = bytesize;
349: nbd->config->blksize_bits = __ffs(blksize);
350:
351: if (!nbd->pid)
352: return 0;
353:
354: lim = queue_limits_start_update(nbd->disk->queue);
355: if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
356: lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
357: else
358: lim.max_hw_discard_sectors = 0;
359: if (!(nbd->config->flags & NBD_FLAG_SEND_FLUSH)) {
360: lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
361: } else if (nbd->config->flags & NBD_FLAG_SEND_FUA) {
362: lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
363: } else {
364: lim.features |= BLK_FEAT_WRITE_CACHE;
365: lim.features &= ~BLK_FEAT_FUA;
366: }
367: if (nbd->config->flags & NBD_FLAG_ROTATIONAL)
368: lim.features |= BLK_FEAT_ROTATIONAL;
369: if (nbd->config->flags & NBD_FLAG_SEND_WRITE_ZEROES)
370: lim.max_write_zeroes_sectors = UINT_MAX >> SECTOR_SHIFT;
371:
372: lim.logical_block_size = blksize;
373: lim.physical_block_size = blksize;
374: error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
375: if (error)
376: return error;
377:
378: if (max_part)
379: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
380: if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
381: kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
382: return 0;
383: }
SourceFile:drivers/block/nbd.c]
|
| 153/4 |
2026/05/10 03:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 45263
output: 20
thoughts: 1382
Thoughts: **Analyzing the Best Approach for Safe NBD Device Size Changes**
Okay, so I'm diving into this `nbd_set_size` issue, trying to figure out the safest way to prevent race conditions during size changes. Initially, the code seems to use `bd_prepare_to_claim`, but the comment says it's "only for the loop driver." Hmm, that's not ideal.
My first thought was, maybe we could just check `disk_openers(nbd->disk) > 1`. But that has some nuances. `disk_openers` counts how many times the device is open, right? If `nbd_ioctl` is called, the caller has the device open, making `disk_openers` at least 1. If the device is mounted, `disk_openers` is 2. So, `disk_openers > 1` would mean someone else has it open, probably through a mount.
However, if `nbd_genl_size_set` (netlink) is called, the caller *doesn't* have the device open. That means `disk_openers` might be 1 (if mounted). So, checking `disk_openers > 1` would allow a netlink call to change the size when it *shouldn't*, because the device is mounted. That's a problem!
Wait, this gets more complicated when you consider a user-space program using netlink. If the program opens the device and then calls netlink to configure it, `disk_openers` is 1, and the check `disk_openers > 0` may fail. But, often, `nbd-client` uses netlink to configure the device and doesn't need to open the block device. It's usually the safer approach.
So, if `nbd-client` does NOT open the device with netlink, `disk_openers` is 0. If it *does* open the block device, `disk_openers` is 1. If we check `disk_openers > 0` in netlink, it will fail when netlink is used without opening the device. If we use `bd_prepare_to_claim`, it checks if the device is *exclusively claimed*, like when it is mounted or when opened with `O_EXCL`.
Thinking about the options, the prompt actually gives me two: Use `bd_prepare_to_claim` or prevent changes if `disk_openers(nbd->disk) > 1`. But wait, if I use `disk_openers > 1` and netlink is used *while* the device is mounted, `disk_openers` is 1. `> 1` becomes false, and it will NOT prevent the race. So, `disk_openers > 1` will fail. So using `disk_openers(nbd->disk) > 1` doesn't cover all cases.
Here's the problem: `mount` opens the device exclusively, and it increments `disk_openers`. So `disk_openers` is 1. However, the syzkaller reproducer uses `ioctl(NBD_DO_IT)`, which means it opens the device. Therefore, `disk_openers` is greater than 1, and we can prevent changes. This method won't work if syzkaller uses netlink.
So, if we use `bd_prepare_to_claim`, it works for *both* cases. It checks for exclusive claim, whether that's due to a mount or an `O_EXCL` open. Now, let's see if `bdev_is_claimed` exists... That looks like the better and more robust way to solve this!
|
| 154/4 |
2026/05/10 03:16 |
tool |
grepper |
0m
Error:
Args: map[Expression:bdev_is_claimed]
Results:
|
| 155/4 |
2026/05/10 03:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 47495
output: 41
thoughts: 255
Thoughts: **Analyzing the Claiming Strategy**
Okay, so I'm trying to figure out the cleanest way to handle this. My initial thought was a simple "no" – there has to be a better way than what I was doing. Then, the idea of just using `bd_prepare_to_claim` popped up. That seemed promising.
But hold on, `nbd_set_size` doesn't include the necessary `bdev` and `mode` parameters. Okay, so we have a few options there, either change the signature of `nbd_set_size`, or we can just use `nbd->disk->part0` and set `mode = 0` for the netlink part.
Alright, if we go with `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` and it succeeds, we absolutely *must* make sure we call `bd_abort_claiming` to clean up afterwards.
Then, a thought comes up, maybe we can just look at `nbd->disk->part0->bd_holders` and just peek in there to see what it is. Wait, `bd_holders` isn't exported, that could be a problem. Then I remember that `nbd.c` is built-in or module. If it's a module, then it can't be used, right? But wait, `struct block_device` is defined in `include/linux/blk_types.h`! Aha! That means I *can* access `bd_holders`. Time to verify by looking at `include/linux/blk_types.h`.
|
| 156/4 |
2026/05/10 03:16 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/blk_types.h IncludeLines:true Name:block_device]
Results: map[SourceCode: 41: struct block_device {
42: sector_t bd_start_sect;
43: sector_t bd_nr_sectors;
44: struct gendisk * bd_disk;
45: struct request_queue * bd_queue;
46: struct disk_stats __percpu *bd_stats;
47: unsigned long bd_stamp;
48: atomic_t __bd_flags; // partition number + flags
49: #define BD_PARTNO 255 // lower 8 bits; assign-once
50: #define BD_READ_ONLY (1u<<8) // read-only policy
51: #define BD_WRITE_HOLDER (1u<<9)
52: #define BD_HAS_SUBMIT_BIO (1u<<10)
53: #define BD_RO_WARNED (1u<<11)
54: #ifdef CONFIG_FAIL_MAKE_REQUEST
55: #define BD_MAKE_IT_FAIL (1u<<12)
56: #endif
57: dev_t bd_dev;
58: struct address_space *bd_mapping; /* page cache */
59:
60: atomic_t bd_openers;
61: spinlock_t bd_size_lock; /* for bd_inode->i_size updates */
62: void * bd_claiming;
63: void * bd_holder;
64: const struct blk_holder_ops *bd_holder_ops;
65: struct mutex bd_holder_lock;
66: int bd_holders;
67: struct kobject *bd_holder_dir;
68:
69: atomic_t bd_fsfreeze_count; /* number of freeze requests */
70: struct mutex bd_fsfreeze_mutex; /* serialize freeze/thaw */
71:
72: struct partition_meta_info *bd_meta_info;
73: int bd_writers;
74: #ifdef CONFIG_SECURITY
75: void *bd_security;
76: #endif
77: /*
78: * keep this out-of-line as it's both big and not needed in the fast
79: * path
80: */
81: struct device bd_device;
82: } __randomize_layout;
SourceFile:include/linux/blk_types.h]
|
| 157/4 |
2026/05/10 03:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 48837
output: 41
thoughts: 396
Thoughts: **Analyzing Exclusive Device Claims in the NBD Driver**
Okay, so I'm trying to figure out how to handle exclusive device claims within the NBD driver. My initial thought was to directly check the `bd_holders` field. Yes, it *is* accessible, but after digging deeper, I see it's protected by `bdev_lock` within `block/bdev.c`, and that lock isn't exported. However, since `bd_holders` is just an `int`, I could technically read it directly, bypassing the lock. But that feels... risky.
Then it hits me! `bd_prepare_to_claim` is exported. Perfect! We can use this to reliably check if we can safely claim the block device. It's exported, using `EXPORT_SYMBOL_GPL(bd_prepare_to_claim);`, so that’s a go for use in `nbd.c`.
Wait a minute... thinking more critically about the implications. If `nbd_ioctl` is called with a device that's been opened with `O_EXCL`, the caller *already* holds the exclusive claim! `bdev->bd_holder` will be set to the caller, preventing subsequent calls to `bd_prepare_to_claim`. If we call `bd_prepare_to_claim(bdev, nbd_set_size, NULL)` after an `O_EXCL` open, it *will* fail!
So, it's not enough to blindly use `bd_prepare_to_claim`. We need to *know* if the caller already has the exclusive claim. The critical question: How do we figure this out?
Ah! The `nbd_ioctl` function signature! We receive the `mode` parameter. If `mode & BLK_OPEN_EXCL` is true, the caller *does* have exclusive access! So, that's how we'll determine if we need to call `bd_prepare_to_claim` or not. This is key to preventing conflicts.
|
| 158/4 |
2026/05/10 03:17 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_ioctl]
Results: map[SourceCode:1640: static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1641: unsigned int cmd, unsigned long arg)
1642: {
1643: struct nbd_device *nbd = bdev->bd_disk->private_data;
1644: struct nbd_config *config = nbd->config;
1645: int error = -EINVAL;
1646:
1647: if (!capable(CAP_SYS_ADMIN))
1648: return -EPERM;
1649:
1650: /* The block layer will pass back some non-nbd ioctls in case we have
1651: * special handling for them, but we don't so just return an error.
1652: */
1653: if (_IOC_TYPE(cmd) != 0xab)
1654: return -EINVAL;
1655:
1656: mutex_lock(&nbd->config_lock);
1657:
1658: /* Don't allow ioctl operations on a nbd device that was created with
1659: * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1660: */
1661: if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1662: (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1663: error = __nbd_ioctl(bdev, nbd, cmd, arg);
1664: else
1665: dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1666: mutex_unlock(&nbd->config_lock);
1667: return error;
1668: }
SourceFile:drivers/block/nbd.c]
|
| 159/4 |
2026/05/10 03:17 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 50245
output: 51
thoughts: 1065
Thoughts: **Analyzing Size Change Permissions in NBD**
Okay, so I'm digging into how we handle size changes in the Network Block Device (NBD) driver, specifically concerning potential race conditions between ioctl and netlink operations. I'm focusing on the `nbd_set_size` function, and how we can prevent size changes when the device is in use, or exclusively claimed by another process.
First, I see that `nbd_ioctl` *does* have a `mode` parameter. My initial thought was to propagate this `mode` down the call chain, all the way to `nbd_set_size`, through `__nbd_ioctl`. I then realized `nbd_set_size` is also called from `nbd_start_device`, which is itself invoked by both `nbd_start_device_ioctl` and `nbd_genl_connect`. So, passing `mode` to `nbd_start_device` seemed like a direct solution. Then I remembered `nbd_start_device` *doesn't* take a `mode` argument!
My next thought was to check if `disk_openers(nbd->disk) > 1` in `nbd_set_size`. But wait...that works for ioctl, but for netlink, `disk_openers` could be 1, if the device is mounted! So we'd *allow* a size change via netlink even if it's in use. That's a no-go.
I then considered checking `nbd->disk->part0->bd_holders > 0`. This seemed promising, as a value greater than zero indicates that the device has an exclusive claim. However, if `nbd-client` opens with `O_EXCL`, then `bd_holders` is already 1, and so would *reject* the NBD client! I then looked at `loop.c`, and remembered that it uses `bd_prepare_to_claim` and skips it if `mode & BLK_OPEN_EXCL`.
So the problem is: we need a way to determine if the caller holds the *exclusive* claim, and, if so, they are allowed to change the size. Thus, `bd_holders` alone, isn't enough. We *must* pass the `mode` down to `nbd_set_size` to handle the exclusive open correctly!
Now, the question is how to get the `mode` into `nbd_set_size`. I was initially thinking about changing the `nbd_set_size` signature to take `bdev` and `mode`, which is likely how I'd approach this problem.
However, `nbd_set_size` doesn't actually need the `bdev`, it can just use `nbd->disk->part0`. But it *definitely* needs `mode`. I then traced all callers of `nbd_set_size`: `__nbd_ioctl`, `nbd_start_device`, and `nbd_genl_size_set`. Modifying the signature seems invasive. Could I do the check in each of the callers? No, `nbd_set_size` is where the limits are actually set. I still need the `mode` in `nbd_set_size`.
Maybe I can add a `bool exclusively_claimed` argument? Or I can just pass `bdev` and `mode` to `nbd_set_size`. That would be most straightforward. Ultimately, I'll need to update the signature to pass `mode`. That's the cleanest solution.
|
| 160/4 |
2026/05/10 03:18 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeSnippetLines:0 Name:nbd_set_size SourceTreePrefix:]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1608] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1610] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1614] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_genl_size_set SourceFile:drivers/block/nbd.c SourceLine:2069] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_start_device SourceFile:drivers/block/nbd.c SourceLine:1540]] TruncatedOutput:false]
|
| 161/4 |
2026/05/10 03:18 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 52420
output: 43
thoughts: 455
Thoughts: **Refactoring the NBD Size Setting Mechanism**
Okay, so I'm focusing on those five spots where we're setting the NBD device size. The core issue is how to pass the `block_device` and `mode` information into the `nbd_set_size` function to integrate with `bd_prepare_to_claim`.
First, let's start with the immediate change. I think I'll change the signature of `nbd_set_size` to accept the `bytesize` and `blksize` arguments:
```c
static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
```
Wait a second, there's a better way! I can leverage `bd_prepare_to_claim`!
But, to use `bd_prepare_to_claim`, I need to have the `bdev` (block device) and `mode` (access mode) available in `nbd_set_size`. So, I'll need to update the signature to include those parameters.
```c
static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
loff_t blksize, struct block_device *bdev,
blk_mode_t mode)
```
Now, the question is how to pass those new arguments down the call chain. `nbd_start_device` doesn't have `bdev` or `mode` in its signature, which is where things get interesting. Looking at how it's called, I see two entry points: `nbd_start_device_ioctl` and `nbd_genl_connect`.
`nbd_start_device_ioctl` is called from `__nbd_ioctl`, which means I can update `__nbd_ioctl` to supply the `bdev` and `mode` to `nbd_start_device_ioctl`. That should work fine.
`nbd_genl_connect`, on the other hand, doesn't have these available. However, in that context, I can pass `nbd->disk->part0` as the `bdev` and `0` for the `mode`, since that's generally appropriate for this entry path. I'll need to do the same thing for `nbd_genl_size_set` too.
Now, let's take a closer look at `nbd_start_device_ioctl` and `nbd_start_device` and implement the changes.
|
| 162/4 |
2026/05/10 03:18 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device]
Results: map[SourceCode:1471: static int nbd_start_device(struct nbd_device *nbd)
1472: {
1473: struct nbd_config *config = nbd->config;
1474: int num_connections = config->num_connections;
1475: int error = 0, i;
1476:
1477: if (nbd->pid)
1478: return -EBUSY;
1479: if (!config->socks)
1480: return -EINVAL;
1481: if (num_connections > 1 &&
1482: !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1483: dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1484: return -EINVAL;
1485: }
1486:
1487: retry:
1488: mutex_unlock(&nbd->config_lock);
1489: blk_mq_update_nr_hw_queues(&nbd->tag_set, num_connections);
1490: mutex_lock(&nbd->config_lock);
1491:
1492: /* if another code path updated nr_hw_queues, retry until succeed */
1493: if (num_connections != config->num_connections) {
1494: num_connections = config->num_connections;
1495: goto retry;
1496: }
1497:
1498: nbd->pid = task_pid_nr(current);
1499:
1500: nbd_parse_flags(nbd);
1501:
1502: error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1503: if (error) {
1504: dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1505: return error;
1506: }
1507: set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1508:
1509: nbd_dev_dbg_init(nbd);
1510: for (i = 0; i < num_connections; i++) {
1511: struct recv_thread_args *args;
1512:
1513: args = kzalloc_obj(*args);
1514: if (!args) {
1515: sock_shutdown(nbd);
1516: /*
1517: * If num_connections is m (2 < m),
1518: * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1519: * But NO.(n + 1) failed. We still have n recv threads.
1520: * So, add flush_workqueue here to prevent recv threads
1521: * dropping the last config_refs and trying to destroy
1522: * the workqueue from inside the workqueue.
1523: */
1524: if (i)
1525: flush_workqueue(nbd->recv_workq);
1526: return -ENOMEM;
1527: }
1528: sk_set_memalloc(config->socks[i]->sock->sk);
1529: if (nbd->tag_set.timeout)
1530: config->socks[i]->sock->sk->sk_sndtimeo =
1531: nbd->tag_set.timeout;
1532: atomic_inc(&config->recv_threads);
1533: refcount_inc(&nbd->config_refs);
1534: INIT_WORK(&args->work, recv_work);
1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
SourceFile:drivers/block/nbd.c]
|
| 163/4 |
2026/05/10 03:18 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 54668
output: 44
thoughts: 554
Thoughts: **Analyzing the Logic for Size Modification in NBD Devices**
Okay, so I'm digging into how to safely change the size of an NBD device. My initial thought was to modify the `nbd_set_size` function, specifically:
```c
static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
```
But, instead of getting bogged down in that, I'm trying to figure out the *conditions* under which we *should* allow a size change. The core issue is preventing changes to a device that's currently in use, particularly if it's mounted. My first instinct was to check `disk_openers(nbd->disk) > 1`.
Let's think through this carefully. If `nbd_genl_size_set` (which I assume is a Netlink-based size setting) gets called, and the device is mounted (so `disk_openers` is 1), checking `disk_openers > 1` would incorrectly allow the size change! The mount process opens the block device exclusively (yes, I can confirm that `blkdev_get_by_path` increments the counter), increasing `disk_openers` to 1. But Netlink *doesn't* open the block device, so the counter stays at 1. So, that initial idea (`disk_openers > 1`) is *wrong* for the Netlink case.
Now I'm considering `disk_openers > 0`. If `nbd-client` uses Netlink, and it *doesn't* open the block device, `disk_openers` is 0. If it's mounted, `disk_openers` is 1. Checking `disk_openers > 0` *would* prevent the size change when mounted. But, what if the client uses `ioctl`? `ioctl` *does* open the block device. So, `disk_openers` would be 1. If it's also mounted, that makes `disk_openers` be 2. So for `ioctl`, `disk_openers > 1` would work. So, this doesn't work.
So, the key here is knowing *whether* the caller has an open file descriptor. Hmm, what if I check `test_bit(NBD_RT_BOUND, &config->runtime_flags)`? Wait, that flag, `NBD_RT_BOUND`, is specifically set when the device is bound via Netlink. I better check `nbd_genl_connect` to make sure!
|
| 164/4 |
2026/05/10 03:18 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_genl_connect]
Results: map[SourceCode:2073: static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
2074: {
2075: struct nbd_device *nbd;
2076: struct nbd_config *config;
2077: int index = -1;
2078: int ret;
2079: bool put_dev = false;
2080:
2081: if (!netlink_capable(skb, CAP_SYS_ADMIN))
2082: return -EPERM;
2083:
2084: if (info->attrs[NBD_ATTR_INDEX]) {
2085: index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2086:
2087: /*
2088: * Too big first_minor can cause duplicate creation of
2089: * sysfs files/links, since index << part_shift might overflow, or
2090: * MKDEV() expect that the max bits of first_minor is 20.
2091: */
2092: if (index < 0 || index > MINORMASK >> part_shift) {
2093: pr_err("illegal input index %d\n", index);
2094: return -EINVAL;
2095: }
2096: }
2097: if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SOCKETS)) {
2098: pr_err("must specify at least one socket\n");
2099: return -EINVAL;
2100: }
2101: if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_SIZE_BYTES)) {
2102: pr_err("must specify a size in bytes for the device\n");
2103: return -EINVAL;
2104: }
2105: again:
2106: mutex_lock(&nbd_index_mutex);
2107: if (index == -1) {
2108: nbd = nbd_find_get_unused();
2109: } else {
2110: nbd = idr_find(&nbd_index_idr, index);
2111: if (nbd) {
2112: if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
2113: test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
2114: !refcount_inc_not_zero(&nbd->refs)) {
2115: mutex_unlock(&nbd_index_mutex);
2116: pr_err("device at index %d is going down\n",
2117: index);
2118: return -EINVAL;
2119: }
2120: }
2121: }
2122: mutex_unlock(&nbd_index_mutex);
2123:
2124: if (!nbd) {
2125: nbd = nbd_dev_add(index, 2);
2126: if (IS_ERR(nbd)) {
2127: pr_err("failed to add new device\n");
2128: return PTR_ERR(nbd);
2129: }
2130: }
2131:
2132: mutex_lock(&nbd->config_lock);
2133: if (refcount_read(&nbd->config_refs)) {
2134: mutex_unlock(&nbd->config_lock);
2135: nbd_put(nbd);
2136: if (index == -1)
2137: goto again;
2138: pr_err("nbd%d already in use\n", index);
2139: return -EBUSY;
2140: }
2141:
2142: ret = nbd_alloc_and_init_config(nbd);
2143: if (ret) {
2144: mutex_unlock(&nbd->config_lock);
2145: nbd_put(nbd);
2146: pr_err("couldn't allocate config\n");
2147: return ret;
2148: }
2149:
2150: config = nbd->config;
2151: set_bit(NBD_RT_BOUND, &config->runtime_flags);
2152: ret = nbd_genl_size_set(info, nbd);
2153: if (ret)
2154: goto out;
2155:
2156: if (info->attrs[NBD_ATTR_TIMEOUT])
2157: nbd_set_cmd_timeout(nbd,
2158: nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2159: if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2160: config->dead_conn_timeout =
2161: nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2162: config->dead_conn_timeout *= HZ;
2163: }
2164: if (info->attrs[NBD_ATTR_SERVER_FLAGS])
2165: config->flags =
2166: nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
2167: if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2168: u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2169: if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2170: /*
2171: * We have 1 ref to keep the device around, and then 1
2172: * ref for our current operation here, which will be
2173: * inherited by the config. If we already have
2174: * DESTROY_ON_DISCONNECT set then we know we don't have
2175: * that extra ref already held so we don't need the
2176: * put_dev.
2177: */
2178: if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2179: &nbd->flags))
2180: put_dev = true;
2181: } else {
2182: if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2183: &nbd->flags))
2184: refcount_inc(&nbd->refs);
2185: }
2186: if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2187: set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2188: &config->runtime_flags);
2189: }
2190: }
2191:
2192: if (info->attrs[NBD_ATTR_SOCKETS]) {
2193: struct nlattr *attr;
2194: int rem, fd;
2195:
2196: nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2197: rem) {
2198: struct nlattr *socks[NBD_SOCK_MAX+1];
2199:
2200: if (nla_type(attr) != NBD_SOCK_ITEM) {
2201: pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2202: ret = -EINVAL;
2203: goto out;
2204: }
2205: ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2206: attr,
2207: nbd_sock_policy,
2208: info->extack);
2209: if (ret != 0) {
2210: pr_err("error processing sock list\n");
2211: ret = -EINVAL;
2212: goto out;
2213: }
2214: if (!socks[NBD_SOCK_FD])
2215: continue;
2216: fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2217: ret = nbd_add_socket(nbd, fd, true);
2218: if (ret)
2219: goto out;
2220: }
2221: }
2222:
2223: if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2224: nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2225: GFP_KERNEL);
2226: if (!nbd->backend) {
2227: ret = -ENOMEM;
2228: goto out;
2229: }
2230: }
2231: ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2232: if (ret) {
2233: dev_err(disk_to_dev(nbd->disk),
2234: "device_create_file failed for backend!\n");
2235: goto out;
2236: }
2237: set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2238:
2239: ret = nbd_start_device(nbd);
2240: out:
2241: if (!ret) {
2242: set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2243: refcount_inc(&nbd->config_refs);
2244: nbd_connect_reply(info, nbd->index);
2245: }
2246: mutex_unlock(&nbd->config_lock);
2247:
2248: nbd_config_put(nbd);
2249: if (put_dev)
2250: nbd_put(nbd);
2251: return ret;
2252: }
SourceFile:drivers/block/nbd.c]
|
| 165/4 |
2026/05/10 03:18 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 58727
output: 17
thoughts: 1344
Thoughts: **Analyzing NBD Device Size Changes**
Okay, let me think this through. `nbd_genl_connect` calls `nbd_genl_size_set` *before* `nbd_start_device`. If `nbd_genl_size_set` calls `nbd_set_size`, and `nbd->pid` is zero at that point, it just updates the config and returns. The actual size change happens later, within `nbd_start_device`, when `nbd->pid` is set. So `nbd->pid` is the critical flag.
Then `nbd_genl_reconfigure` uses `nbd_genl_size_set` when `nbd->pid` is *not* zero. That means we can change the size while the device is running, via netlink! And also, `nbd_ioctl` can change the size with `NBD_SET_BLKSIZE` and `NBD_SET_SIZE`, but only when `nbd->pid` is zero. Then `NBD_DO_IT` kicks off `nbd_start_device_ioctl`, which ultimately calls `nbd_start_device`, setting `nbd->pid` and updating the size via `nbd_set_size`.
So, the only *real* places where `nbd_set_size` actually adjusts the queue limits (because `nbd->pid` is non-zero) are:
1. `nbd_start_device` (from `NBD_DO_IT` or `nbd_genl_connect`).
2. `nbd_genl_reconfigure` (via `nbd_genl_size_set`).
I thought if I just checked `disk_openers(nbd->disk) > 1` in `nbd_set_size` when `nbd->pid` is set, that would do it. With `nbd_genl_connect` it would work, because `disk_openers` is zero at that point. Similarly with `nbd_genl_reconfigure` and `NBD_DO_IT`.
But what if the device is *mounted*? If netlink was used, `disk_openers` would be 1! `disk_openers > 1` is false. So my initial approach would *allow* `nbd_genl_reconfigure` to change the size while it's mounted! That's the problem. `disk_openers > 1` isn't sufficient for netlink!
Wait a minute... if netlink is used, `nbd-client` doesn't open the device. The mount does. So `disk_openers` is 0 at connect and becomes 1 when mounted. When `nbd_genl_reconfigure` is called, `disk_openers` will be 1, and so the size change will be allowed! But we *must* prevent size changes when mounted. So I need to check if the device is exclusively claimed, or mounted.
How to check for exclusive claim? If `nbd->disk->part0->bd_holders > 0`, that's it! Wait, `bd_holders` is an integer, so checking `bd_holders > 0` is safe. Is `bd_holders` accessible? Yes, it's in `struct block_device`. Wait, is it safe to read `bd_holders` without `bdev_lock`? Yes, it's just an integer. I can do `READ_ONCE(bdev->bd_holders)`. The actual modification occurs under `bdev_lock` and `bd_holder_lock`. But I'm only reading it to prevent the size change.
What if `nbd-client` uses ioctl? `nbd-client` opens the device, but it *doesn't* use `O_EXCL`. So `bd_holders` is zero initially. `mount` opens it and `bd_holders` becomes 1. So `bd_holders > 0` perfectly distinguishes between an unmounted device and a mounted (or exclusively claimed) one!
Okay, let's verify if `nbd-client` opens with `O_EXCL`. If it did, `bd_holders` would be 1 and size changes would be rejected right away! I know `nbd-client` *shouldn't* be using `O_EXCL`, but let's be sure. Looking at the `nbd-client` source code online, it does `open(device, O_RDWR)`. No `O_EXCL`.
|
| 166/4 |
2026/05/10 03:19 |
tool |
grepper |
0m
Args: map[Expression:bd_holders]
Results: map[Output:block/bdev.c=642=static void bd_finish_claiming(struct block_device *bdev, void *holder,
--
block/bdev.c-649- /*
block/bdev.c:650: * Note that for a whole device bd_holders will be incremented twice,
block/bdev.c-651- * and bd_holder will be set to bd_may_claim before being set to holder
block/bdev.c-652- */
block/bdev.c:653: whole->bd_holders++;
block/bdev.c-654- whole->bd_holder = bd_may_claim;
block/bdev.c:655: bdev->bd_holders++;
block/bdev.c-656- mutex_lock(&bdev->bd_holder_lock);
--
block/bdev.c=681=static void bd_end_claim(struct block_device *bdev, void *holder)
--
block/bdev.c-691- WARN_ON_ONCE(bdev->bd_holder != holder);
block/bdev.c:692: WARN_ON_ONCE(--bdev->bd_holders < 0);
block/bdev.c:693: WARN_ON_ONCE(--whole->bd_holders < 0);
block/bdev.c:694: if (!bdev->bd_holders) {
block/bdev.c-695- mutex_lock(&bdev->bd_holder_lock);
--
block/bdev.c-701- }
block/bdev.c:702: if (!whole->bd_holders)
block/bdev.c-703- whole->bd_holder = NULL;
--
block/bdev.c=716=static void blkdev_flush_mapping(struct block_device *bdev)
block/bdev.c-717-{
block/bdev.c:718: WARN_ON_ONCE(bdev->bd_holders);
block/bdev.c-719- sync_blockdev(bdev);
--
include/linux/blk_types.h=41=struct block_device {
--
include/linux/blk_types.h-65- struct mutex bd_holder_lock;
include/linux/blk_types.h:66: int bd_holders;
include/linux/blk_types.h-67- struct kobject *bd_holder_dir;
]
|
| 167/4 |
2026/05/10 03:19 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 61755
output: 43
thoughts: 1408
Thoughts: **Reflecting on NBD Size Changes**
Okay, so I'm diving into this `nbd_set_size` function, and I need to figure out how to handle block device claiming. First, I noticed that no other driver directly accesses `bd_holders`, which is a good sign. But if I use `bd_prepare_to_claim`, even though the comment says it's for the loop driver, it's still an exported function via `EXPORT_SYMBOL_GPL`. Hmm, so I need to figure out the `mode`. If I don't get the `mode`, can I assume `mode = 0`? If so, `bd_prepare_to_claim` will ALWAYS get called. This will cause problems if `nbd-client` opens the device with `O_EXCL`, because the call to claim the block device will fail. But it doesn't use `O_EXCL`.
What if it *did* use `O_EXCL`? Then `NBD_DO_IT` could fail. Is that a problem? If someone opens `/dev/nbd0` with `O_EXCL` and then runs `NBD_DO_IT`, `bd_prepare_to_claim` will return `-EBUSY`. Now, `loop.c` explicitly checks `!(mode & BLK_OPEN_EXCL)` to deal with this, which is good. If we don't check `mode`, we might break userspace that opens with `O_EXCL`.
Wait, does `nbd-client` open with `O_EXCL`? Let's check if we can pass down `mode` from the original call. We have the `mode` parameter in `nbd_ioctl`. But `nbd_set_size` is called from `nbd_start_device`, which is called from `nbd_start_device_ioctl`. We can pass `mode` to `nbd_start_device_ioctl` and `nbd_start_device`. Let's see about adding `mode` to `nbd_start_device`. Wait, `nbd_start_device` is also called from `nbd_genl_connect`. For `nbd_genl_connect`, `mode` can be 0.
So the plan is: let's trace the changes. Instead of `mode`, we can pass a boolean `excl` (true if the caller holds exclusive claim). In `nbd_ioctl`, `excl = !!(mode & BLK_OPEN_EXCL)`. In `nbd_genl_connect` and `nbd_genl_reconfigure`, `excl = false`.
Then in `nbd_set_size`:
```c
if (!excl) {
error = bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL);
if (error)
return error;
}
...
if (!excl)
bd_abort_claiming(nbd->disk->part0, nbd_set_size);
```
Wait, if `excl` is true, the caller ALREADY holds the exclusive claim! So we *don't* need to claim it again. This is identical to how `loop.c` works.
Could we use `bdev->bd_holders > 0` instead of `bd_prepare_to_claim`? If we just check `bdev->bd_holders > 0`, we're just checking if someone has the block device claimed. So, if `excl` is true, `bdev->bd_holders` is at least 1. If `excl` is false, `bdev->bd_holders` should be 0. If it's > 0, someone else claimed it. So we can just check:
```c
if (!excl && nbd->disk->part0->bd_holders)
return -EBUSY;
```
Wait, `bd_holders` is an integer. Is it safe to read it without locks? Yes, `READ_ONCE(nbd->disk->part0->bd_holders)` is safe. But `bd_prepare_to_claim` is the *official* API to do this, and it prevents races! If we just check `bd_holders`, there is a race condition. We check it, it's 0, someone mounts it, then we change the size! `bd_prepare_to_claim` actually CLAIMS the device. So `mount` will wait or fail until we call `bd_abort_claiming`! That prevents the race condition perfectly! So
|
| 168/4 |
2026/05/10 03:21 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_set_size]
Results: map[SourceCode: 334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
335: {
336: struct queue_limits lim;
337: int error;
338:
339: if (!blksize)
340: blksize = 1u << NBD_DEF_BLKSIZE_BITS;
341:
342: if (blk_validate_block_size(blksize))
343: return -EINVAL;
344:
345: if (bytesize < 0)
346: return -EINVAL;
347:
348: nbd->config->bytesize = bytesize;
349: nbd->config->blksize_bits = __ffs(blksize);
350:
351: if (!nbd->pid)
352: return 0;
353:
354: lim = queue_limits_start_update(nbd->disk->queue);
355: if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
356: lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
357: else
358: lim.max_hw_discard_sectors = 0;
359: if (!(nbd->config->flags & NBD_FLAG_SEND_FLUSH)) {
360: lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
361: } else if (nbd->config->flags & NBD_FLAG_SEND_FUA) {
362: lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
363: } else {
364: lim.features |= BLK_FEAT_WRITE_CACHE;
365: lim.features &= ~BLK_FEAT_FUA;
366: }
367: if (nbd->config->flags & NBD_FLAG_ROTATIONAL)
368: lim.features |= BLK_FEAT_ROTATIONAL;
369: if (nbd->config->flags & NBD_FLAG_SEND_WRITE_ZEROES)
370: lim.max_write_zeroes_sectors = UINT_MAX >> SECTOR_SHIFT;
371:
372: lim.logical_block_size = blksize;
373: lim.physical_block_size = blksize;
374: error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
375: if (error)
376: return error;
377:
378: if (max_part)
379: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
380: if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
381: kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
382: return 0;
383: }
SourceFile:drivers/block/nbd.c]
|
| 169/4 |
2026/05/10 03:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 65135
output: 42
thoughts: 1265
Thoughts: **Refining the NBD Size Change Logic**
Okay, so I'm revisiting this NBD size change implementation, and I need to make sure I get the locking and exclusivity right. I was initially thinking about using `disk_openers` but I quickly realized that's a mess, especially considering the different ways userspace interacts with the device via ioctl and netlink. The netlink case really throws a wrench into the simplistic `disk_openers > 1` check. That's clearly wrong for netlink when the device is mounted.
Then I considered `disk_openers > 0` and, again, it faltered. I got trapped with the various flags that `nbd-client` uses (like with/without `O_EXCL`), and which means the caller is, or is not the 'open-er'. If I check `disk_openers > 0` for netlink, and `disk_openers > 1` for ioctl? But that's complicated and relies on knowing the caller type. I could add an extra boolean, something like `from_ioctl`, to help but that seemed kludgy. It's too complex and fragile.
I can't assume which method will be used, because a user can mix and match.
Then it hit me: `bd_prepare_to_claim`! It's designed for this kind of exclusivity. If `nbd-client` opens the device *without* `O_EXCL`, the device is not exclusively claimed, and `bd_prepare_to_claim` will succeed. If it's mounted, it *is* exclusively claimed, and `bd_prepare_to_claim` will correctly fail. That's exactly the behavior I want! `bd_prepare_to_claim` is the clean solution.
So I'll add `bool excl` to `nbd_set_size`.
If `excl` is false (meaning the device wasn't opened with `O_EXCL`), I can call `bd_prepare_to_claim` using `nbd->disk->part0`. Then change the size, then `bd_abort_claiming`. If `excl` is true, I don't need to call it because the user is claiming exclusive access. This will work seamlessly for both ioctl and netlink, and correctly handle all the open modes and mount states.
I need to trace the callers and add the `excl` flag now. This is definitely the cleanest and most robust approach. Perfect!
|
| 170/4 |
2026/05/10 03:21 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:__nbd_ioctl]
Results: map[SourceCode:1592: /* Must be called with config_lock held */
1593: static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1594: unsigned int cmd, unsigned long arg)
1595: {
1596: struct nbd_config *config = nbd->config;
1597: loff_t bytesize;
1598:
1599: switch (cmd) {
1600: case NBD_DISCONNECT:
1601: return nbd_disconnect(nbd);
1602: case NBD_CLEAR_SOCK:
1603: nbd_clear_sock_ioctl(nbd);
1604: return 0;
1605: case NBD_SET_SOCK:
1606: return nbd_add_socket(nbd, arg, false);
1607: case NBD_SET_BLKSIZE:
1608: return nbd_set_size(nbd, config->bytesize, arg);
1609: case NBD_SET_SIZE:
1610: return nbd_set_size(nbd, arg, nbd_blksize(config));
1611: case NBD_SET_SIZE_BLOCKS:
1612: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1613: return -EINVAL;
1614: return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1615: case NBD_SET_TIMEOUT:
1616: nbd_set_cmd_timeout(nbd, arg);
1617: return 0;
1618:
1619: case NBD_SET_FLAGS:
1620: config->flags = arg;
1621: return 0;
1622: case NBD_DO_IT:
1623: return nbd_start_device_ioctl(nbd);
1624: case NBD_CLEAR_QUE:
1625: /*
1626: * This is for compatibility only. The queue is always cleared
1627: * by NBD_DO_IT or NBD_CLEAR_SOCK.
1628: */
1629: return 0;
1630: case NBD_PRINT_DEBUG:
1631: /*
1632: * For compatibility only, we no longer keep a list of
1633: * outstanding requests.
1634: */
1635: return 0;
1636: }
1637: return -ENOTTY;
1638: }
SourceFile:drivers/block/nbd.c]
|
| 171/4 |
2026/05/10 03:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 67737
output: 43
thoughts: 85
Thoughts: Okay, here's my take on those changes, viewed through the lens of my expertise in block device driver design:
**Refactoring NBD IOCTL Handling for Enhanced Control**
Alright, I'm looking at this NBD code and it's clear we need a more robust way to handle exclusive access modes. My initial thought is to modify `__nbd_ioctl` to accept a boolean flag, perhaps `excl`, or maybe even a `blk_mode_t mode` for more granular control. That would give us a straightforward mechanism for specifying whether a connection is exclusive or shared right at the IOCTL level.
But, hang on... `nbd_start_device_ioctl` is also going to need that exclusivity information, because it's the gateway to `nbd_start_device`. And that's where things get interesting because `nbd_start_device` calls `nbd_set_size`, which is definitely something we'd want to control based on access mode.
So, the cleaner solution here is to pass that `excl` flag directly down into `nbd_start_device`. It gives us more control in the early stages and keeps things consistent. This makes the most sense. This will allow for the most flexibility going forward.
|
| 172/4 |
2026/05/10 03:21 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device]
Results: map[SourceCode:1471: static int nbd_start_device(struct nbd_device *nbd)
1472: {
1473: struct nbd_config *config = nbd->config;
1474: int num_connections = config->num_connections;
1475: int error = 0, i;
1476:
1477: if (nbd->pid)
1478: return -EBUSY;
1479: if (!config->socks)
1480: return -EINVAL;
1481: if (num_connections > 1 &&
1482: !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1483: dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1484: return -EINVAL;
1485: }
1486:
1487: retry:
1488: mutex_unlock(&nbd->config_lock);
1489: blk_mq_update_nr_hw_queues(&nbd->tag_set, num_connections);
1490: mutex_lock(&nbd->config_lock);
1491:
1492: /* if another code path updated nr_hw_queues, retry until succeed */
1493: if (num_connections != config->num_connections) {
1494: num_connections = config->num_connections;
1495: goto retry;
1496: }
1497:
1498: nbd->pid = task_pid_nr(current);
1499:
1500: nbd_parse_flags(nbd);
1501:
1502: error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1503: if (error) {
1504: dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1505: return error;
1506: }
1507: set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1508:
1509: nbd_dev_dbg_init(nbd);
1510: for (i = 0; i < num_connections; i++) {
1511: struct recv_thread_args *args;
1512:
1513: args = kzalloc_obj(*args);
1514: if (!args) {
1515: sock_shutdown(nbd);
1516: /*
1517: * If num_connections is m (2 < m),
1518: * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1519: * But NO.(n + 1) failed. We still have n recv threads.
1520: * So, add flush_workqueue here to prevent recv threads
1521: * dropping the last config_refs and trying to destroy
1522: * the workqueue from inside the workqueue.
1523: */
1524: if (i)
1525: flush_workqueue(nbd->recv_workq);
1526: return -ENOMEM;
1527: }
1528: sk_set_memalloc(config->socks[i]->sock->sk);
1529: if (nbd->tag_set.timeout)
1530: config->socks[i]->sock->sk->sk_sndtimeo =
1531: nbd->tag_set.timeout;
1532: atomic_inc(&config->recv_threads);
1533: refcount_inc(&nbd->config_refs);
1534: INIT_WORK(&args->work, recv_work);
1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
SourceFile:drivers/block/nbd.c]
|
| 173/4 |
2026/05/10 03:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 69319
output: 448
thoughts: 7
Thoughts: Okay, here's the summary, formatted as requested:
**Preparing the Edits**
Alright, time to get this done. I need to focus. First, I'll mentally map out the changes that need to be made. I need to be precise, ensuring accuracy and consistency with the overall message, which I'll keep in mind as I approach this. I'll read through the document meticulously, identifying any areas that require improvement in clarity, structure, or tone. I'll flag any inconsistencies with established practices, protocols, or stylistic guidelines. The objective is to make the piece even stronger.
I'll be looking specifically for opportunities to refine the arguments and bolster the evidence presented. Any vague statements or unsubstantiated claims need immediate attention. I'll need to double-check all references and ensure they're up-to-date and correctly formatted according to the required style. The terminology has to be flawless; I'll need to ensure the language is precise, and that the audience understands, from the ground up, what I am communicating.
Finally, I'll take a step back and review the entire piece, considering its overall impact and whether it effectively achieves its intended purpose. Once satisfied, I'll implement these edits and prepare for the final review. Now, let's get started.
|
| 174/4 |
2026/05/10 03:21 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
{
struct queue_limits lim;
int error;
if (!blksize)
blksize = 1u << NBD_DEF_BLKSIZE_BITS;
if (blk_validate_block_size(blksize))
return -EINVAL;
if (bytesize < 0)
return -EINVAL;
nbd->config->bytesize = bytesize;
nbd->config->blksize_bits = __ffs(blksize);
if (!nbd->pid)
return 0;
lim = queue_limits_start_update(nbd->disk->queue); NewCode:static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
loff_t blksize, bool excl)
{
struct queue_limits lim;
int error;
if (!blksize)
blksize = 1u << NBD_DEF_BLKSIZE_BITS;
if (blk_validate_block_size(blksize))
return -EINVAL;
if (bytesize < 0)
return -EINVAL;
nbd->config->bytesize = bytesize;
nbd->config->blksize_bits = __ffs(blksize);
if (!nbd->pid)
return 0;
if (!excl) {
error = bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL);
if (error)
return error;
}
lim = queue_limits_start_update(nbd->disk->queue); SourceFile:drivers/block/nbd.c]
Results:
|
| 175/4 |
2026/05/10 03:21 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 70054
output: 363
thoughts: 13
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:
**Navigating the `nbd_set_size` Implementation (Part 2)**
Alright, so we're diving back into the `nbd_set_size` function, specifically the second part. I'm already mentally running through the architectural implications here. This isn't just a trivial adjustment; setting the size of an NBD device fundamentally impacts data structures and access patterns. I'm thinking about the potential ripple effects, especially concerning existing data, block allocation strategies, and potential metadata updates. Where is this size value ultimately used? Are we talking about a simple truncation, a more complex expansion scenario with potential reallocation, or something in between?
My immediate concern is ensuring data integrity. Are we checking for enough free space if expanding the device? Is there a risk of exposing uninitialized data if we shrink it? What about the implications for any snapshots or clones that might exist? We can't just blithely change the size; we need to be incredibly careful about preserving data consistency, particularly if the client-side might not be aware of this change immediately. I'm also questioning the locking strategy; are we using sufficient locking to prevent race conditions during this potentially disruptive operation?
The previous parts probably covered a lot of groundwork, so I'm quickly trying to recall the overall design. Am I looking at changes to the backing store, the in-memory device representation, or both? I need to understand how this function integrates with the other NBD operations, such as reads, writes, and disconnect handling. Is this part responsible for updating any device metadata in persistent storage? If so, what is the atomicity, and what are the recovery mechanisms if something goes wrong during the commit? I'm hoping it's designed with robust error handling, because the consequences of a failed size update can be severe.
|
| 176/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode: lim.logical_block_size = blksize;
lim.physical_block_size = blksize;
error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
if (error)
return error;
if (max_part)
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
return 0;
} NewCode: lim.logical_block_size = blksize;
lim.physical_block_size = blksize;
error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
if (!excl)
bd_abort_claiming(nbd->disk->part0, nbd_set_size);
if (error)
return error;
if (max_part)
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
return 0;
} SourceFile:drivers/block/nbd.c]
Results:
|
| 177/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 70836
output: 784
thoughts: 8
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Navigating the `__nbd_ioctl` Landscape**
Right, so I'm diving into the `__nbd_ioctl` function. Naturally, I'm thinking about the standard ioctl interface, the fundamental tool of communication between userspace and the kernel in this context. My initial focus is always on the security implications; what can go wrong? Malicious userspace applications are always lurking. I need to quickly identify potential vulnerabilities. The primary concern with ioctls is often the unchecked data being passed in from user space, so that's where I will begin my dive.
First, I'm tracing the argument processing. I'm looking for where the actual data structures are being populated, whether there are checks to limit the size of inputs, if buffer overflows are possible, or format string vulnerabilities. I need to understand the control flow based on the `cmd` argument, what the specific ioctl command is. I'm keeping an eye out for potential integer overflows when calculating buffer sizes or indexing arrays, especially if sizes are derived from user-provided data.
I'm thinking about potential race conditions. Are there any shared resources being accessed? Are there locking mechanisms in place to protect against concurrent access? Does any state change influence any other operations later on, and could this sequence become problematic?
And, of course, I'm thinking about the common pitfalls. Null pointer dereferences are always a concern, and memory leaks are an ever-present threat. It's a matter of looking at where memory is allocated and deallocated, and how it's done.
I need to understand the interactions with the underlying block device itself, NBD itself. Are there any assumptions made about the block device? Anything it will let this interface do? Any implicit assumptions about the device’s capabilities? Will malicious input affect its state?
Finally, I'm considering the edge cases. What happens with invalid commands? What about extremely large or small data sizes? Are there any undocumented behaviors that might be exploitable? Any of these issues could be security holes. Essentially, I'm trying to break the function, poking at it from every angle, to see where it might fail. Only then will I have a good handle on its safety and robustness.
|
| 178/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode:/* Must be called with config_lock held */
static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
unsigned int cmd, unsigned long arg)
{
struct nbd_config *config = nbd->config;
loff_t bytesize;
switch (cmd) {
case NBD_DISCONNECT:
return nbd_disconnect(nbd);
case NBD_CLEAR_SOCK:
nbd_clear_sock_ioctl(nbd);
return 0;
case NBD_SET_SOCK:
return nbd_add_socket(nbd, arg, false);
case NBD_SET_BLKSIZE:
return nbd_set_size(nbd, config->bytesize, arg);
case NBD_SET_SIZE:
return nbd_set_size(nbd, arg, nbd_blksize(config));
case NBD_SET_SIZE_BLOCKS:
if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
return -EINVAL;
return nbd_set_size(nbd, bytesize, nbd_blksize(config));
case NBD_SET_TIMEOUT:
nbd_set_cmd_timeout(nbd, arg);
return 0;
case NBD_SET_FLAGS:
config->flags = arg;
return 0;
case NBD_DO_IT:
return nbd_start_device_ioctl(nbd); NewCode:/* Must be called with config_lock held */
static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
unsigned int cmd, unsigned long arg, bool excl)
{
struct nbd_config *config = nbd->config;
loff_t bytesize;
switch (cmd) {
case NBD_DISCONNECT:
return nbd_disconnect(nbd);
case NBD_CLEAR_SOCK:
nbd_clear_sock_ioctl(nbd);
return 0;
case NBD_SET_SOCK:
return nbd_add_socket(nbd, arg, false);
case NBD_SET_BLKSIZE:
return nbd_set_size(nbd, config->bytesize, arg, excl);
case NBD_SET_SIZE:
return nbd_set_size(nbd, arg, nbd_blksize(config), excl);
case NBD_SET_SIZE_BLOCKS:
if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
return -EINVAL;
return nbd_set_size(nbd, bytesize, nbd_blksize(config), excl);
case NBD_SET_TIMEOUT:
nbd_set_cmd_timeout(nbd, arg);
return 0;
case NBD_SET_FLAGS:
config->flags = arg;
return 0;
case NBD_DO_IT:
return nbd_start_device_ioctl(nbd, excl); SourceFile:drivers/block/nbd.c]
Results:
|
| 179/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 72128
output: 368
thoughts: 7
Thoughts: Okay, let's dive into this `nbd_ioctl` situation. Here's my take, based on my expert understanding:
**Analyzing the `nbd_ioctl` Landscape**
Right, so we're looking at `nbd_ioctl`. That means we're interacting with the Network Block Device driver through the standard `ioctl` interface. Immediately, my mind starts ticking through the implications. We're talking about a user-space program communicating directly with a kernel module. I need to consider the security implications right off the bat – what kind of data are we passing, and how is it validated? Any missteps there, and we're looking at potential vulnerabilities.
The `ioctl` system call itself is notoriously flexible, a strength and a weakness. The flexibility allows for a huge range of operations, but that means careful attention needs to be paid to the command numbers. Each `_IO` or `_IOR` or `_IOW` macro represents a specific request, and that request has to be robust. I start thinking about the potential for buffer overflows if the size checks are insufficient. The `nbd_ioctl` implementation has to be *very* careful about user-provided data.
I'm mentally mapping the common `ioctl` flows. We're likely dealing with requests for things like: connection establishment and teardown; sending and receiving block data; potentially managing the device's configuration (e.g., setting the block size, enabling read-only access). Each of these functions has to be implemented meticulously, with error handling at every stage. We need to be resilient to unexpected inputs and potentially malicious requests.
I wonder what's being done around the transport layer here. Is there any protection in place during transmission? The traditional NBD protocol is relatively basic, so I'd be looking closely at any implementation details of encryption, authentication, or even just basic integrity checks. This can easily impact performance, so there may be trade-offs in design.
The kernel-side interface, I'm sure, needs to be well-designed to prevent resource exhaustion and starvation. Threads might be needed for concurrent processing, but this adds complexity. I'd be examining the locking mechanisms, how the driver handles multiple connections, and how it deals with asynchronous operations. I'm going to want to check any details around any queueing mechanism, specifically the locking strategy employed.
All in all, it's a critical interface. Any bug here can potentially lead to crashes, security breaches, or data corruption. I am considering these items from the start. I need to deeply understand the data structures involved, the validation routines, the error handling, and the overall security posture. Let's delve in, then.
|
| 180/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode: /* Don't allow ioctl operations on a nbd device that was created with
* netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
*/
if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
(cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
error = __nbd_ioctl(bdev, nbd, cmd, arg);
else
dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
mutex_unlock(&nbd->config_lock);
return error;
} NewCode: /* Don't allow ioctl operations on a nbd device that was created with
* netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
*/
if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
(cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
error = __nbd_ioctl(bdev, nbd, cmd, arg,
mode & BLK_OPEN_EXCL);
else
dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
mutex_unlock(&nbd->config_lock);
return error;
} SourceFile:drivers/block/nbd.c]
Results:
|
| 181/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 73075
output: 174
thoughts: 11
Thoughts: Okay, here's my attempt at summarizing the thought process, as if it were my own, assuming I'm an expert in the field:
**Diving into the `nbd_start_device_ioctl` Function**
Alright, let's see. My mental gears are shifting; it's time to dive into `nbd_start_device_ioctl`. I know this function is the crucial entry point for an NBD device. This is where the magic starts, right? I'm anticipating this involves parsing the incoming IOCTL request, validating it, and then initiating the appropriate action. We're likely talking about commands to connect or disconnect, configure the device, or maybe manage specific export parameters. I need to make sure the request is well-formed and that the user has the necessary permissions. Thinking about the usual suspects, I'm expecting checks for the device's state; if it's already running, shutting it down, or in some intermediary state. I'll need to handle potential race conditions gracefully, as this is multi-threaded territory. From here, I would expect it to determine the function to hand-off control, depending on the requested IOCTL number. This can get complex fast, so my immediate thought is to find a clear execution flow through the rest of the code. Let's see what we're looking at.
|
| 182/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_start_device_ioctl(struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
int ret;
ret = nbd_start_device(nbd);
if (ret)
return ret; NewCode:static int nbd_start_device_ioctl(struct nbd_device *nbd, bool excl)
{
struct nbd_config *config = nbd->config;
int ret;
ret = nbd_start_device(nbd, excl);
if (ret)
return ret; SourceFile:drivers/block/nbd.c]
Results:
|
| 183/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 73551
output: 154
thoughts: 9
Thoughts: Okay, here's my attempt at summarizing the thought process, as if it were my own, assuming I'm an expert in the field:
**Initiating the Network Block Device**
Alright, let's dive into this. The function we're looking at now is `nbd_start_device`. This is where the rubber meets the road, isn't it? The core of getting the Network Block Device up and running. I need to mentally walk through the critical steps. We're essentially initializing the interface between the client and server. What are the key components we need to address? Obviously, setting up the socket connection is primary. Beyond that, memory management and error handling are paramount. I need to make sure we're correctly allocating buffers for data transfer, managing the request queue, and handling potential socket failures gracefully. Consider the implications of each failure point and what fallback mechanisms we'll need to employ. The client also has to establish a connection using the network server which will provide block access. There are also flags that need to be considered.
|
| 184/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_start_device(struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
int num_connections = config->num_connections;
int error = 0, i; NewCode:static int nbd_start_device(struct nbd_device *nbd, bool excl)
{
struct nbd_config *config = nbd->config;
int num_connections = config->num_connections;
int error = 0, i; SourceFile:drivers/block/nbd.c]
Results:
|
| 185/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 73941
output: 151
thoughts: 12
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Wrapping Up `nbd_start_device`**
So, here we are, staring at the end of `nbd_start_device`. It's a critical function, no doubt, and I need to make sure I've truly addressed all the corner cases before calling it a day. Let's recap: we've handled the device setup, registered the NBD device, initialized the necessary structures, and potentially dealt with any initialization errors. I need to double-check that the error handling is comprehensive; a missed error here can propagate silently and cause real headaches down the line. We need robust error logging to pinpoint exactly where things go wrong, and this has to be very precise.
Thinking through my notes... Did I ensure the proper synchronization primitives are in place *before* handing the device control over? Race conditions are the bane of any concurrent system, and a flaw here will be very hard to debug. That spinlock on the device struct... yup, that should cover the essentials. Okay, and how about resource cleanup? Did I properly free memory allocated, regardless of the success or failure of the preceding steps? I need to make sure to free the device if things fail.
Before I can move on to the next task I need to make sure that I've ensured a clean and complete initial setup of the device, with all pieces working together. Now that I am at the end, I need to make certain this device is really ready for `nbd_thread` to take over. I have to go through the code again. Let me just take one more pass...just to be sure.
|
| 186/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode: args->index = i;
queue_work(nbd->recv_workq, &args->work);
}
return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
} NewCode: args->index = i;
queue_work(nbd->recv_workq, &args->work);
}
return nbd_set_size(nbd, config->bytesize, nbd_blksize(config), excl);
} SourceFile:drivers/block/nbd.c]
Results:
|
| 187/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 74471
output: 463
thoughts: 12
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm an expert in this field, presented as a first-person summary:
**Working with `nbd_genl_size_set`**
Alright, let's see, we're focusing on the `nbd_genl_size_set` function right now. Thinking about it, this is a crucial piece of the puzzle. I know the general idea: it's about setting the size, or the number of sectors, for a particular NBD (Network Block Device) generic netlink interface. This directly affects the amount of storage presented by the device.
Let's quickly recap what goes into this function. I'm assuming it receives some input parameters, likely including the netlink socket connection information and details about the block device to modify. I also anticipate it needs to validate the new size request. Is it a valid size? Does it fall within the acceptable ranges defined for this particular NBD setup, and are there permissions to modify the disk?
The most critical part here is what happens when this new size is set. I need to consider all the implications. Are there any existing connections that need to be handled? Should we warn people about the potential for data loss when decreasing the size of a disk? I would want to make sure all data writes complete before the new size is set, or there'll be data corruption. Are we accounting for existing, pending I/O operations and any need for synchronization to maintain data integrity when modifying the disk? It's essential to handle this with extreme caution.
Also, I have to ensure the changes are atomic, so the system is not left in a half-configured state in case of a crash or interruption. And what about metadata updates? The underlying filesystem, or the virtual disk layer, might need adjustments. Those operations need to be part of the same transaction as the size change.
Finally, I'm thinking about error handling. What happens if setting the new size fails? How do we report the error back through the netlink interface so the user gets meaningful feedback? Are there specific error codes to return?
So, yeah, `nbd_genl_size_set`... it’s not just about changing a number. It’s about a careful, controlled transition of an NBD device. I need to get this right.
|
| 188/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
u64 bsize = nbd_blksize(config);
u64 bytes = config->bytesize;
if (info->attrs[NBD_ATTR_SIZE_BYTES])
bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
if (bytes != config->bytesize || bsize != nbd_blksize(config))
return nbd_set_size(nbd, bytes, bsize);
return 0;
} NewCode:static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
u64 bsize = nbd_blksize(config);
u64 bytes = config->bytesize;
if (info->attrs[NBD_ATTR_SIZE_BYTES])
bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
if (bytes != config->bytesize || bsize != nbd_blksize(config))
return nbd_set_size(nbd, bytes, bsize, false);
return 0;
} SourceFile:drivers/block/nbd.c]
Results:
|
| 189/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 75447
output: 445
thoughts: 10
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm deep in the weeds of network block device code:
**Diving into `nbd_genl_connect`**
Alright, let's get down to it. The next thing on the list is clearly `nbd_genl_connect`. That tells me we're dealing with the generic netlink interface here, which means we're connecting to a Netlink socket for NBD communication. I need to figure out what happens in this function. This is where the client (probably the kernel-side NBD driver) initiates the connection with the server (the NBD server, likely in userspace). I suspect this handles the initial handshake, perhaps setting up any necessary security context, exchanging capabilities, or negotiating protocol parameters. I should expect to find code that handles socket creation, binding, and potentially some kind of authentication or handshake. I'll need to look carefully at the data structures being passed back and forth, especially the Netlink message format used for this connection. Understanding the flow control and error handling within this function will be crucial, too. Let's see how they handle potential connection failures and re-tries. Digging into the code will reveal the intricacies of how this connection is established and the subsequent communication is structured.
|
| 190/4 |
2026/05/10 03:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode: if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
GFP_KERNEL);
if (!nbd->backend) {
ret = -ENOMEM;
goto out;
}
}
ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
if (ret) {
dev_err(disk_to_dev(nbd->disk),
"device_create_file failed for backend!\n");
goto out;
}
set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
ret = nbd_start_device(nbd);
out:
if (!ret) { NewCode: if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
GFP_KERNEL);
if (!nbd->backend) {
ret = -ENOMEM;
goto out;
}
}
ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
if (ret) {
dev_err(disk_to_dev(nbd->disk),
"device_create_file failed for backend!\n");
goto out;
}
set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
ret = nbd_start_device(nbd, false);
out:
if (!ret) { SourceFile:drivers/block/nbd.c]
Results:
|
| 191/4 |
2026/05/10 03:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 76180
output: 22
thoughts: 647
Thoughts: **Reviewing the Size Setting Logic**
Okay, let's break this down. The core change revolves around how we handle setting the size, specifically the new `excl` boolean in `nbd_set_size`. The logic is as follows: if `!excl`, the code calls `bd_prepare_to_claim` with the block device, `nbd_set_size` as the holder (makes sense), and `NULL` for the holder operations. If that call succeeds, the code updates limits and then calls `bd_abort_claiming` (seems right, releasing the claim). If the `bd_prepare_to_claim` fails, the error is immediately returned.
The concern arose when I considered the `nbd_genl_size_set` function's call to `nbd_set_size` where `nbd->pid` might be 0. I need to make sure this doesn't create a race condition or incorrect behavior. Here's what I observed:
```c
if (!nbd->pid)
return 0;
if (!excl) {
error = bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL);
if (error)
return error;
}
```
The code now returns 0 when `nbd->pid` is 0. This is the correct behavior because the queue limits are not actually modified in this case, only the `nbd->config` is updated. That's fine because when `nbd_start_device` is subsequently called, `nbd->pid` will *not* be 0 and the proper claiming and limit update process will occur. Phew, that's good!
I confirmed that the `bd_prepare_to_claim` and `bd_abort_claiming` signatures are correct with the block device, holder function pointer, and NULL for the operations, so no issues there.
Now, I need to make sure I've caught all the calls to `nbd_set_size`. After using `codesearch-find-references`, I confirmed 5 instances:
1. `__nbd_ioctl` (3 times)
2. `nbd_start_device` (1 time)
3. `nbd_genl_size_set` (1 time)
I updated all five call sites to take the `excl` boolean. Since `nbd_start_device_ioctl` is called from `__nbd_ioctl`, I updated it to take `excl`. Also `nbd_start_device` which is called from `nbd_start_device_ioctl` and `nbd_genl_connect` and I updated it as well.
|
| 192/4 |
2026/05/10 03:24 |
tool |
grepper |
0m
Args: map[Expression:nbd_start_device_ioctl]
Results: map[Output:drivers/block/nbd.c=1471=static int nbd_start_device(struct nbd_device *nbd)
--
drivers/block/nbd.c-1542-
drivers/block/nbd.c:1543:static int nbd_start_device_ioctl(struct nbd_device *nbd)
drivers/block/nbd.c-1544-{
--
drivers/block/nbd.c=1593=static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
--
drivers/block/nbd.c-1622- case NBD_DO_IT:
drivers/block/nbd.c:1623: return nbd_start_device_ioctl(nbd);
drivers/block/nbd.c-1624- case NBD_CLEAR_QUE:
]
|
| 193/4 |
2026/05/10 03:24 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 77682
output: 22
thoughts: 66
Thoughts: **Function Declaration Sequencing Analysis**
Okay, here's what's running through my mind as I examine this code. Immediately, the lack of forward declarations for `nbd_start_device_ioctl` and `nbd_start_device` jumps out at me. That's unusual and could definitely lead to issues, especially in larger codebases. I need to understand the control flow, so the lack of forward declarations is a concern.
Then, I see that `nbd_set_size` is defined *before* `__nbd_ioctl` and `nbd_start_device`. Huh, that's a bit odd, isn't it? Generally, related functions would be grouped together or, at least, defined in a logical order that reflects their dependency. This suggests a potential for either a design quirk or a compilation-order dependency I need to fully grasp.
My immediate reaction is to verify the function call and dependency sequence. I need to carefully check the order in which these functions are defined and called to understand why they are placed this way. I need to make sure there are no unintended consequences and that everything compiles and links as expected. Time to dive into the code and map out the control flow to determine what the proper order is for the given functions.
|
| 194/4 |
2026/05/10 03:24 |
tool |
grepper |
0m
Args: map[Expression:static int nbd_set_size]
Results: map[Output:drivers/block/nbd.c=305=static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
--
drivers/block/nbd.c-333-
drivers/block/nbd.c:334:static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
drivers/block/nbd.c-335-{
]
|
| 195/4 |
2026/05/10 03:24 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 78170
output: 17
thoughts: 194
Thoughts: **Navigating the NBD Codebase**
Okay, let's see, `nbd_set_size` is indeed at line 334. Good. And `nbd_start_device` is at 1471, followed by `nbd_start_device_ioctl` at 1543. Then we have `__nbd_ioctl` at 1593, and `nbd_ioctl` at 1640. Finally, `nbd_genl_size_set` is at 2056, and `nbd_genl_connect` at 2073. Alright, the function call order within the code seems to be lining up as expected, no red flags there.
Now, I need to confirm something related to module exports. I'm wondering if `bd_prepare_to_claim` is exposed to other kernel modules. Yes, looks like it's `EXPORT_SYMBOL_GPL(bd_prepare_to_claim);` which is precisely what I was looking for. Now, a follow-up: is the NBD module itself licensed under GPL? Need to make sure the licensing is consistent. Let's quickly check the `MODULE_LICENSE` in `nbd.c` to verify that.
|
| 196/4 |
2026/05/10 03:24 |
tool |
grepper |
0m
Args: map[Expression:MODULE_LICENSE]
Results: map[Output:
Full output is too long, showing 500 out of 45274 lines.
Use more precise expression if possible.
[Documentation/admin-guide/tainted-kernels.rst=110=More detailed explanation for tainting
--
Documentation/admin-guide/tainted-kernels.rst-114- any proprietary module has been loaded. Modules without a
Documentation/admin-guide/tainted-kernels.rst:115: MODULE_LICENSE or with a MODULE_LICENSE that is not recognised by
Documentation/admin-guide/tainted-kernels.rst-116- insmod as GPL compatible are assumed to be proprietary.
--
Documentation/core-api/local_ops.rst=136=Here is a sample module which implements a basic per cpu counter using
--
Documentation/core-api/local_ops.rst-199-
Documentation/core-api/local_ops.rst:200: MODULE_LICENSE("GPL");
Documentation/core-api/local_ops.rst-201- MODULE_AUTHOR("Mathieu Desnoyers");
--
Documentation/core-api/symbol-namespaces.rst=123=It is advisable to add the MODULE_IMPORT_NS() statement close to other module
Documentation/core-api/symbol-namespaces.rst:124:metadata definitions like MODULE_AUTHOR() or MODULE_LICENSE().
Documentation/core-api/symbol-namespaces.rst-125-
--
Documentation/dev-tools/kselftest.rst=370=A bare bones test module might look like this:
--
Documentation/dev-tools/kselftest.rst-397- MODULE_AUTHOR("John Developer <jd@fooman.org>");
Documentation/dev-tools/kselftest.rst:398: MODULE_LICENSE("GPL");
Documentation/dev-tools/kselftest.rst-399- MODULE_INFO(test, "Y");
--
Documentation/dev-tools/kunit/start.rst=216=Now we are ready to write the test cases.
--
Documentation/dev-tools/kunit/start.rst-252-
Documentation/dev-tools/kunit/start.rst:253: MODULE_LICENSE("GPL");
Documentation/dev-tools/kunit/start.rst-254-
--
Documentation/driver-api/virtio/writing_virtio_drivers.rst=25=like this::
--
Documentation/driver-api/virtio/writing_virtio_drivers.rst-107- MODULE_DESCRIPTION("Dummy virtio driver");
Documentation/driver-api/virtio/writing_virtio_drivers.rst:108: MODULE_LICENSE("GPL");
Documentation/driver-api/virtio/writing_virtio_drivers.rst-109-
--
Documentation/i2c/writing-clients.rst=255=Driver Information
--
Documentation/i2c/writing-clients.rst-264- /* a few non-GPL license types are also allowed */
Documentation/i2c/writing-clients.rst:265: MODULE_LICENSE("GPL");
Documentation/i2c/writing-clients.rst-266-
--
Documentation/kernel-hacking/hacking.rst=588=exported by EXPORT_SYMBOL_GPL() can only be seen by
Documentation/kernel-hacking/hacking.rst:589:modules with a MODULE_LICENSE() that specifies a GPLv2
Documentation/kernel-hacking/hacking.rst-590-compatible license. It implies that the function is considered an
--
Documentation/process/license-rules.rst=426=organizations, e.g. the `FSFE REUSE initiative <https://reuse.software/>`_.
Documentation/process/license-rules.rst-427-
Documentation/process/license-rules.rst:428:_`MODULE_LICENSE`
Documentation/process/license-rules.rst-429------------------
Documentation/process/license-rules.rst-430-
Documentation/process/license-rules.rst:431: Loadable kernel modules also require a MODULE_LICENSE() tag. This tag is
Documentation/process/license-rules.rst-432- neither a replacement for proper source code license information
--
Documentation/process/license-rules.rst-440-
Documentation/process/license-rules.rst:441: The valid license strings for MODULE_LICENSE() are:
Documentation/process/license-rules.rst-442-
--
Documentation/sound/kernel-api/writing-an-alsa-driver.rst=3914=module license as GPL, etc., otherwise the system is shown as “tainted”::
--
Documentation/sound/kernel-api/writing-an-alsa-driver.rst-3916- MODULE_DESCRIPTION("Sound driver for My Chip");
Documentation/sound/kernel-api/writing-an-alsa-driver.rst:3917: MODULE_LICENSE("GPL");
Documentation/sound/kernel-api/writing-an-alsa-driver.rst-3918-
--
Documentation/translations/it_IT/core-api/symbol-namespaces.rst=110=Si consiglia di posizionare la dichiarazione MODULE_IMPORT_NS() vicino
Documentation/translations/it_IT/core-api/symbol-namespaces.rst:111:ai metadati del modulo come MODULE_AUTHOR() o MODULE_LICENSE().
Documentation/translations/it_IT/core-api/symbol-namespaces.rst-112-
--
Documentation/translations/it_IT/kernel-hacking/hacking.rst=622=utilizzati solo dai moduli che hanno dichiarato una licenza compatibile
Documentation/translations/it_IT/kernel-hacking/hacking.rst:623:con la GPL attraverso :c:func:`MODULE_LICENSE()`. Questo implica che la
Documentation/translations/it_IT/kernel-hacking/hacking.rst-624-funzione esportata è considerata interna, e non una vera e propria interfaccia.
--
Documentation/translations/it_IT/process/license-rules.rst=438=REUSE <https://reuse.software/>`_.
Documentation/translations/it_IT/process/license-rules.rst-439-
Documentation/translations/it_IT/process/license-rules.rst:440:_`MODULE_LICENSE`
Documentation/translations/it_IT/process/license-rules.rst-441------------------
Documentation/translations/it_IT/process/license-rules.rst-442-
Documentation/translations/it_IT/process/license-rules.rst:443: I moduli del kernel necessitano di un'etichetta MODULE_LICENSE(). Questa
Documentation/translations/it_IT/process/license-rules.rst-444- etichetta non sostituisce le informazioni sulla licenza del codice sorgente
--
Documentation/translations/it_IT/process/license-rules.rst-451-
Documentation/translations/it_IT/process/license-rules.rst:452: Le stringe di licenza valide per MODULE_LICENSE() sono:
Documentation/translations/it_IT/process/license-rules.rst-453-
--
Documentation/translations/zh_CN/admin-guide/tainted-kernels.rst=25=BUG、Oops或Panics消息中的污染标志
--
Documentation/translations/zh_CN/admin-guide/tainted-kernels.rst-108- 0) ``G`` 加载的所有模块都有GPL或兼容许可证, ``P`` 加载了任何专有模块。
Documentation/translations/zh_CN/admin-guide/tainted-kernels.rst:109: 没有MODULE_LICENSE(模块许可证)或MODULE_LICENSE未被insmod认可为GPL
Documentation/translations/zh_CN/admin-guide/tainted-kernels.rst-110- 兼容的模块被认为是专有的。
--
Documentation/translations/zh_CN/core-api/local_ops.rst=51=UP之间没有不同的行为,在你的架构的 ``local.h`` 中包括 ``asm-generic/local.h``
--
Documentation/translations/zh_CN/core-api/local_ops.rst-193-
Documentation/translations/zh_CN/core-api/local_ops.rst:194: MODULE_LICENSE("GPL");
Documentation/translations/zh_CN/core-api/local_ops.rst-195- MODULE_AUTHOR("Mathieu Desnoyers");
--
Documentation/translations/zh_CN/core-api/symbol-namespaces.rst-92-建议将 MODULE_IMPORT_NS() 语句添加到靠近其他模块元数据定义的地方,
Documentation/translations/zh_CN/core-api/symbol-namespaces.rst:93:如 MODULE_AUTHOR() 或 MODULE_LICENSE() 。
Documentation/translations/zh_CN/core-api/symbol-namespaces.rst-94-
--
Documentation/translations/zh_CN/kernel-hacking/hacking.rst=467=true;这些对于原子设置标志特别有用。
--
Documentation/translations/zh_CN/kernel-hacking/hacking.rst-492-类似于 :c:func:`EXPORT_SYMBOL()`,只是 :c:func:`EXPORT_SYMBOL_GPL()` 导出的
Documentation/translations/zh_CN/kernel-hacking/hacking.rst:493:符号只能由具有由 :c:func:`MODULE_LICENSE()` 指定GPL兼容许可证的模块看到。这
Documentation/translations/zh_CN/kernel-hacking/hacking.rst-494-意味着此函数被认为是一个内部实现问题,而不是一个真正的接口。一些维护人员和
--
Documentation/translations/zh_CN/process/license-rules.rst=330=_`模块许可`
--
Documentation/translations/zh_CN/process/license-rules.rst-332-
Documentation/translations/zh_CN/process/license-rules.rst:333: 可加载内核模块还需要MODULE_LICENSE()标记。此标记既不替代正确的源代码
Documentation/translations/zh_CN/process/license-rules.rst-334- 许可证信息(SPDX-License-Identifier),也不以任何方式表示或确定提供模块
--
Documentation/translations/zh_CN/process/license-rules.rst-339-
Documentation/translations/zh_CN/process/license-rules.rst:340: MODULE_LICENSE()的有效许可证字符串是:
Documentation/translations/zh_CN/process/license-rules.rst-341-
--
Documentation/translations/zh_TW/admin-guide/tainted-kernels.rst=28=BUG、Oops或Panics消息中的污染標誌
--
Documentation/translations/zh_TW/admin-guide/tainted-kernels.rst-111- 0) ``G`` 加載的所有模塊都有GPL或兼容許可證, ``P`` 加載了任何專有模塊。
Documentation/translations/zh_TW/admin-guide/tainted-kernels.rst:112: 沒有MODULE_LICENSE(模塊許可證)或MODULE_LICENSE未被insmod認可爲GPL
Documentation/translations/zh_TW/admin-guide/tainted-kernels.rst-113- 兼容的模塊被認爲是專有的。
--
Documentation/translations/zh_TW/process/license-rules.rst=331=_`模塊許可`
--
Documentation/translations/zh_TW/process/license-rules.rst-333-
Documentation/translations/zh_TW/process/license-rules.rst:334: 可加載內核模塊還需要MODULE_LICENSE()標記。此標記既不替代正確的源代碼
Documentation/translations/zh_TW/process/license-rules.rst-335- 許可證信息(SPDX-License-Identifier),也不以任何方式表示或確定提供模塊
--
Documentation/translations/zh_TW/process/license-rules.rst-340-
Documentation/translations/zh_TW/process/license-rules.rst:341: MODULE_LICENSE()的有效許可證字符串是:
Documentation/translations/zh_TW/process/license-rules.rst-342-
--
arch/alpha/kernel/srm_env.c=32=MODULE_DESCRIPTION("Accessing Alpha SRM environment through procfs interface");
arch/alpha/kernel/srm_env.c:33:MODULE_LICENSE("GPL");
arch/alpha/kernel/srm_env.c-34-
--
arch/alpha/math-emu/math.c=51=MODULE_DESCRIPTION("FP Software completion module");
arch/alpha/math-emu/math.c:52:MODULE_LICENSE("GPL v2");
arch/alpha/math-emu/math.c-53-
--
arch/arc/kernel/perf_event.c=844=module_platform_driver(arc_pmu_driver);
arch/arc/kernel/perf_event.c-845-
arch/arc/kernel/perf_event.c:846:MODULE_LICENSE("GPL");
arch/arc/kernel/perf_event.c-847-MODULE_AUTHOR("Mischa Jonker <mjonker@synopsys.com>");
--
arch/arm/common/bL_switcher_dummy_if.c=58=MODULE_AUTHOR("Nicolas Pitre <nico@linaro.org>");
arch/arm/common/bL_switcher_dummy_if.c:59:MODULE_LICENSE("GPL v2");
arch/arm/common/bL_switcher_dummy_if.c-60-MODULE_DESCRIPTION("big.LITTLE switcher dummy user interface");
--
arch/arm/common/locomo.c=884=MODULE_DESCRIPTION("Sharp LoCoMo core driver");
arch/arm/common/locomo.c:885:MODULE_LICENSE("GPL");
arch/arm/common/locomo.c-886-MODULE_AUTHOR("John Lenz <lenz@cs.wisc.edu>");
--
arch/arm/common/sa1111.c=1412=MODULE_DESCRIPTION("Intel Corporation SA1111 core driver");
arch/arm/common/sa1111.c:1413:MODULE_LICENSE("GPL");
--
arch/arm/crypto/aes-ce-glue.c=20=MODULE_AUTHOR("Ard Biesheuvel <ard.biesheuvel@linaro.org>");
arch/arm/crypto/aes-ce-glue.c:21:MODULE_LICENSE("GPL v2");
arch/arm/crypto/aes-ce-glue.c-22-
--
arch/arm/crypto/aes-neonbs-glue.c=17=MODULE_DESCRIPTION("Bit sliced AES using NEON instructions");
arch/arm/crypto/aes-neonbs-glue.c:18:MODULE_LICENSE("GPL v2");
arch/arm/crypto/aes-neonbs-glue.c-19-
--
arch/arm/crypto/ghash-ce-glue.c=28=MODULE_AUTHOR("Ard Biesheuvel <ardb@kernel.org>");
arch/arm/crypto/ghash-ce-glue.c:29:MODULE_LICENSE("GPL");
arch/arm/crypto/ghash-ce-glue.c-30-MODULE_ALIAS_CRYPTO("gcm(aes)");
--
arch/arm/mach-omap1/ocpi.c=95=MODULE_DESCRIPTION("OMAP OCPI bus controller module");
arch/arm/mach-omap1/ocpi.c:96:MODULE_LICENSE("GPL");
arch/arm/mach-omap1/ocpi.c-97-module_init(omap_ocpi_init);
--
arch/arm/mach-omap1/omap-dma.c=852=MODULE_DESCRIPTION("OMAP SYSTEM DMA DRIVER");
arch/arm/mach-omap1/omap-dma.c:853:MODULE_LICENSE("GPL");
arch/arm/mach-omap1/omap-dma.c-854-MODULE_AUTHOR("Texas Instruments Inc");
--
arch/arm/mach-pxa/am200epd.c=394=MODULE_AUTHOR("Jaya Kumar");
arch/arm/mach-pxa/am200epd.c:395:MODULE_LICENSE("GPL");
--
arch/arm/mach-pxa/am300epd.c=295=MODULE_AUTHOR("Jaya Kumar");
arch/arm/mach-pxa/am300epd.c:296:MODULE_LICENSE("GPL");
--
arch/arm/mach-sa1100/ssp.c=229=MODULE_DESCRIPTION("SA11x0 SSP PIO driver");
arch/arm/mach-sa1100/ssp.c:230:MODULE_LICENSE("GPL");
arch/arm/mach-sa1100/ssp.c-231-
--
arch/arm/nwfpe/fpmodule.c=173=MODULE_DESCRIPTION("NWFPE floating point emulator (" NWFPE_BITS " precision)");
arch/arm/nwfpe/fpmodule.c:174:MODULE_LICENSE("GPL");
arch/arm/nwfpe/fpmodule.c-175-
--
arch/arm/probes/kprobes/test-core.c=1665=module_exit(kprobe_test_exit)
arch/arm/probes/kprobes/test-core.c:1666:MODULE_LICENSE("GPL");
arch/arm/probes/kprobes/test-core.c-1667-
--
arch/arm64/crypto/aes-ce-ccm-glue.c=322=MODULE_AUTHOR("Ard Biesheuvel <ardb@kernel.org>");
arch/arm64/crypto/aes-ce-ccm-glue.c:323:MODULE_LICENSE("GPL v2");
arch/arm64/crypto/aes-ce-ccm-glue.c-324-MODULE_ALIAS_CRYPTO("ccm(aes)");
--
arch/arm64/crypto/aes-glue.c=68=MODULE_IMPORT_NS("CRYPTO_INTERNAL");
arch/arm64/crypto/aes-glue.c:69:MODULE_LICENSE("GPL v2");
arch/arm64/crypto/aes-glue.c-70-
--
arch/arm64/crypto/aes-neonbs-glue.c=20=MODULE_IMPORT_NS("CRYPTO_INTERNAL");
arch/arm64/crypto/aes-neonbs-glue.c:21:MODULE_LICENSE("GPL v2");
arch/arm64/crypto/aes-neonbs-glue.c-22-
--
arch/arm64/crypto/ghash-ce-glue.c=26=MODULE_AUTHOR("Ard Biesheuvel <ard.biesheuvel@linaro.org>");
arch/arm64/crypto/ghash-ce-glue.c:27:MODULE_LICENSE("GPL v2");
arch/arm64/crypto/ghash-ce-glue.c-28-MODULE_ALIAS_CRYPTO("gcm(aes)");
--
arch/arm64/crypto/sm4-ce-ccm-glue.c=284=MODULE_AUTHOR("Tianjia Zhang <tianjia.zhang@linux.alibaba.com>");
arch/arm64/crypto/sm4-ce-ccm-glue.c:285:MODULE_LICENSE("GPL v2");
--
arch/arm64/crypto/sm4-ce-cipher-glue.c=15=MODULE_AUTHOR("Ard Biesheuvel <ard.biesheuvel@linaro.org>");
arch/arm64/crypto/sm4-ce-cipher-glue.c:16:MODULE_LICENSE("GPL v2");
arch/arm64/crypto/sm4-ce-cipher-glue.c-17-
--
arch/arm64/crypto/sm4-ce-gcm-glue.c=261=MODULE_AUTHOR("Tianjia Zhang <tianjia.zhang@linux.alibaba.com>");
arch/arm64/crypto/sm4-ce-gcm-glue.c:262:MODULE_LICENSE("GPL v2");
--
arch/arm64/crypto/sm4-ce-glue.c=718=MODULE_AUTHOR("Tianjia Zhang <tianjia.zhang@linux.alibaba.com>");
arch/arm64/crypto/sm4-ce-glue.c:719:MODULE_LICENSE("GPL v2");
--
arch/arm64/crypto/sm4-neon-glue.c=247=MODULE_AUTHOR("Tianjia Zhang <tianjia.zhang@linux.alibaba.com>");
arch/arm64/crypto/sm4-neon-glue.c:248:MODULE_LICENSE("GPL v2");
--
arch/arm64/kernel/reloc_test_core.c=77=MODULE_DESCRIPTION("Relocation testing module");
arch/arm64/kernel/reloc_test_core.c:78:MODULE_LICENSE("GPL v2");
--
arch/m68k/emu/nfblock.c=198=MODULE_DESCRIPTION("Atari NatFeat block device driver");
arch/m68k/emu/nfblock.c:199:MODULE_LICENSE("GPL");
--
arch/m68k/emu/nfcon.c=176=MODULE_DESCRIPTION("Atari NatFeat console driver");
arch/m68k/emu/nfcon.c:177:MODULE_LICENSE("GPL");
--
arch/m68k/emu/nfeth.c=48=MODULE_DESCRIPTION("Atari NFeth driver");
arch/m68k/emu/nfeth.c:49:MODULE_LICENSE("GPL");
arch/m68k/emu/nfeth.c-50-
--
arch/mips/cavium-octeon/flash_setup.c=142=late_initcall(octeon_flash_init);
arch/mips/cavium-octeon/flash_setup.c-143-
arch/mips/cavium-octeon/flash_setup.c:144:MODULE_LICENSE("GPL");
--
arch/mips/cavium-octeon/oct_ilm.c=170=MODULE_DESCRIPTION("Measures interrupt latency on Octeon chips.");
arch/mips/cavium-octeon/oct_ilm.c:171:MODULE_LICENSE("GPL");
--
arch/mips/kernel/rtlx.c=408=MODULE_AUTHOR("Elizabeth Oldham, MIPS Technologies, Inc.");
arch/mips/kernel/rtlx.c:409:MODULE_LICENSE("GPL");
--
arch/mips/kernel/vpe.c=899=MODULE_AUTHOR("Elizabeth Oldham, MIPS Technologies, Inc.");
arch/mips/kernel/vpe.c:900:MODULE_LICENSE("GPL");
--
arch/mips/sibyte/common/sb_tbprof.c=592=MODULE_DESCRIPTION("Support for ZBbus profiling");
arch/mips/sibyte/common/sb_tbprof.c:593:MODULE_LICENSE("GPL");
--
arch/powerpc/crypto/aes-gcm-p10-glue.c=31=MODULE_AUTHOR("Danny Tsen <dtsen@linux.ibm.com");
arch/powerpc/crypto/aes-gcm-p10-glue.c:32:MODULE_LICENSE("GPL v2");
arch/powerpc/crypto/aes-gcm-p10-glue.c-33-MODULE_ALIAS_CRYPTO("aes");
--
arch/powerpc/crypto/aes-spe-glue.c=434=module_exit(ppc_aes_mod_fini);
arch/powerpc/crypto/aes-spe-glue.c-435-
arch/powerpc/crypto/aes-spe-glue.c:436:MODULE_LICENSE("GPL");
arch/powerpc/crypto/aes-spe-glue.c-437-MODULE_DESCRIPTION("AES-ECB/CBC/CTR/XTS, SPE optimized");
--
arch/powerpc/crypto/vmx.c=58=MODULE_DESCRIPTION("IBM VMX cryptographic acceleration instructions "
arch/powerpc/crypto/vmx.c-59- "support on Power 8");
arch/powerpc/crypto/vmx.c:60:MODULE_LICENSE("GPL");
arch/powerpc/crypto/vmx.c-61-MODULE_VERSION("1.0.0");
--
arch/powerpc/kernel/rtas_flash.c=752=MODULE_DESCRIPTION("PPC procfs firmware flash interface");
arch/powerpc/kernel/rtas_flash.c:753:MODULE_LICENSE("GPL");
--
arch/powerpc/kvm/book3s_hv.c=6700=MODULE_DESCRIPTION("KVM on Book3S (POWER8 and later) in hypervisor mode");
arch/powerpc/kvm/book3s_hv.c:6701:MODULE_LICENSE("GPL");
arch/powerpc/kvm/book3s_hv.c-6702-MODULE_ALIAS_MISCDEV(KVM_MINOR);
--
arch/powerpc/kvm/book3s_pr.c=2111=MODULE_DESCRIPTION("KVM on Book3S without using hypervisor mode");
arch/powerpc/kvm/book3s_pr.c:2112:MODULE_LICENSE("GPL");
arch/powerpc/kvm/book3s_pr.c-2113-MODULE_ALIAS_MISCDEV(KVM_MINOR);
--
arch/powerpc/kvm/test-guest-state-buffer.c=542=MODULE_DESCRIPTION("KUnit tests for Guest State Buffer APIs");
arch/powerpc/kvm/test-guest-state-buffer.c:543:MODULE_LICENSE("GPL");
--
arch/powerpc/perf/kvm-hv-pmu.c=434=MODULE_AUTHOR("Vaibhav Jain <vaibhav@linux.ibm.com>");
arch/powerpc/perf/kvm-hv-pmu.c:435:MODULE_LICENSE("GPL");
--
arch/powerpc/perf/vpa-pmu.c=203=MODULE_AUTHOR("Madhavan Srinivasan <maddy@linux.ibm.com>");
arch/powerpc/perf/vpa-pmu.c:204:MODULE_LICENSE("GPL");
--
arch/powerpc/platforms/512x/mpc512x_lpbfifo.c=515=MODULE_DESCRIPTION("MPC512x LocalPlus Bus FIFO device driver");
arch/powerpc/platforms/512x/mpc512x_lpbfifo.c:516:MODULE_LICENSE("GPL v2");
--
arch/powerpc/platforms/52xx/mpc52xx_gpt.c=73=MODULE_AUTHOR("Sascha Hauer, Grant Likely, Albrecht Dreß");
arch/powerpc/platforms/52xx/mpc52xx_gpt.c:74:MODULE_LICENSE("GPL");
arch/powerpc/platforms/52xx/mpc52xx_gpt.c-75-
--
arch/powerpc/platforms/83xx/mcu_mpc8349emitx.c=228=MODULE_AUTHOR("Anton Vorontsov <avorontsov@ru.mvista.com>");
arch/powerpc/platforms/83xx/mcu_mpc8349emitx.c:229:MODULE_LICENSE("GPL");
--
arch/powerpc/platforms/85xx/sgy_cts1000.c=153=MODULE_AUTHOR("Ben Collins <ben.c@servergy.com>");
arch/powerpc/platforms/85xx/sgy_cts1000.c:154:MODULE_LICENSE("GPL");
--
arch/powerpc/platforms/85xx/t1042rdb_diu.c=152=MODULE_DESCRIPTION("Freescale T1042 DIU driver");
arch/powerpc/platforms/85xx/t1042rdb_diu.c:153:MODULE_LICENSE("GPL");
--
arch/powerpc/platforms/cell/spufs/inode.c=812=MODULE_DESCRIPTION("SPU file system");
arch/powerpc/platforms/cell/spufs/inode.c:813:MODULE_LICENSE("GPL");
arch/powerpc/platforms/cell/spufs/inode.c-814-MODULE_AUTHOR("Arnd Bergmann <arndb@de.ibm.com>");
--
arch/powerpc/platforms/chrp/nvram.c=95=MODULE_DESCRIPTION("PPC NVRAM device driver");
arch/powerpc/platforms/chrp/nvram.c:96:MODULE_LICENSE("GPL v2");
--
arch/powerpc/platforms/pasemi/gpio_mdio.c=321=module_exit(gpio_mdio_exit);
arch/powerpc/platforms/pasemi/gpio_mdio.c-322-
arch/powerpc/platforms/pasemi/gpio_mdio.c:323:MODULE_LICENSE("GPL");
arch/powerpc/platforms/pasemi/gpio_mdio.c-324-MODULE_AUTHOR("Olof Johansson <olof@lixom.net>");
--
arch/powerpc/platforms/powernv/opal-prd.c=452=MODULE_DESCRIPTION("PowerNV OPAL runtime diagnostic driver");
arch/powerpc/platforms/powernv/opal-prd.c:453:MODULE_LICENSE("GPL");
--
arch/powerpc/platforms/pseries/cmm.c=55=MODULE_DESCRIPTION("IBM System p Collaborative Memory Manager");
arch/powerpc/platforms/pseries/cmm.c:56:MODULE_LICENSE("GPL");
arch/powerpc/platforms/pseries/cmm.c-57-MODULE_VERSION(CMM_DRIVER_VERSION);
--
arch/powerpc/platforms/pseries/htmdump.c=489=MODULE_DESCRIPTION("PHYP Hardware Trace Macro (HTM) data dumper");
arch/powerpc/platforms/pseries/htmdump.c:490:MODULE_LICENSE("GPL");
--
arch/powerpc/platforms/pseries/hvcserver.c=22=MODULE_DESCRIPTION("IBM hvcs ppc64 API");
arch/powerpc/platforms/pseries/hvcserver.c:23:MODULE_LICENSE("GPL");
arch/powerpc/platforms/pseries/hvcserver.c-24-MODULE_VERSION(HVCS_ARCH_VERSION);
--
arch/powerpc/platforms/pseries/papr_scm.c=1540=MODULE_DESCRIPTION("PAPR Storage Class Memory interface driver");
arch/powerpc/platforms/pseries/papr_scm.c:1541:MODULE_LICENSE("GPL");
arch/powerpc/platforms/pseries/papr_scm.c-1542-MODULE_AUTHOR("IBM Corporation");
--
arch/powerpc/platforms/pseries/pseries_energy.c=367=MODULE_AUTHOR("Vaidyanathan Srinivasan");
arch/powerpc/platforms/pseries/pseries_energy.c:368:MODULE_LICENSE("GPL");
--
arch/powerpc/sysdev/cpm_gpio.c=78=MODULE_DESCRIPTION("Driver for CPM GPIO");
arch/powerpc/sysdev/cpm_gpio.c:79:MODULE_LICENSE("GPL");
arch/powerpc/sysdev/cpm_gpio.c-80-MODULE_ALIAS("platform:cpm-gpio");
--
arch/powerpc/sysdev/fsl_mpic_timer_wakeup.c=156=MODULE_DESCRIPTION("Freescale MPIC global timer wakeup driver");
arch/powerpc/sysdev/fsl_mpic_timer_wakeup.c:157:MODULE_LICENSE("GPL v2");
arch/powerpc/sysdev/fsl_mpic_timer_wakeup.c-158-MODULE_AUTHOR("Wang Dongsheng <dongsheng.wang@freescale.com>");
--
arch/powerpc/sysdev/rtc_cmos_setup.c=69=MODULE_DESCRIPTION("PPC RTC CMOS driver");
arch/powerpc/sysdev/rtc_cmos_setup.c:70:MODULE_LICENSE("GPL");
--
arch/riscv/crypto/aes-riscv64-glue.c=559=MODULE_AUTHOR("Jerry Shih <jerry.shih@sifive.com>");
arch/riscv/crypto/aes-riscv64-glue.c:560:MODULE_LICENSE("GPL");
arch/riscv/crypto/aes-riscv64-glue.c-561-MODULE_ALIAS_CRYPTO("aes");
--
arch/riscv/crypto/sm4-riscv64-glue.c=105=MODULE_AUTHOR("Heiko Stuebner <heiko.stuebner@vrull.eu>");
arch/riscv/crypto/sm4-riscv64-glue.c:106:MODULE_LICENSE("GPL");
arch/riscv/crypto/sm4-riscv64-glue.c-107-MODULE_ALIAS_CRYPTO("sm4");
--
arch/riscv/kernel/tests/kprobes/test-kprobes.c=56=kunit_test_suites(&kprobes_test_suite);
arch/riscv/kernel/tests/kprobes/test-kprobes.c-57-
arch/riscv/kernel/tests/kprobes/test-kprobes.c:58:MODULE_LICENSE("GPL");
arch/riscv/kernel/tests/kprobes/test-kprobes.c-59-MODULE_DESCRIPTION("KUnit test for riscv kprobes");
--
arch/riscv/kernel/tests/module_test/test_module_linking_main.c-10-
arch/riscv/kernel/tests/module_test/test_module_linking_main.c:11:MODULE_LICENSE("GPL");
arch/riscv/kernel/tests/module_test/test_module_linking_main.c-12-MODULE_DESCRIPTION("Test module linking");
--
arch/s390/appldata/appldata_mem.c=157=module_exit(appldata_mem_exit);
arch/s390/appldata/appldata_mem.c-158-
arch/s390/appldata/appldata_mem.c:159:MODULE_LICENSE("GPL");
arch/s390/appldata/appldata_mem.c-160-MODULE_AUTHOR("Gerald Schaefer");
--
arch/s390/appldata/appldata_net_sum.c=159=module_exit(appldata_net_exit);
arch/s390/appldata/appldata_net_sum.c-160-
arch/s390/appldata/appldata_net_sum.c:161:MODULE_LICENSE("GPL");
arch/s390/appldata/appldata_net_sum.c-162-MODULE_AUTHOR("Gerald Schaefer");
--
arch/s390/appldata/appldata_os.c=206=module_exit(appldata_os_exit);
arch/s390/appldata/appldata_os.c-207-
arch/s390/appldata/appldata_os.c:208:MODULE_LICENSE("GPL");
arch/s390/appldata/appldata_os.c-209-MODULE_AUTHOR("Gerald Schaefer");
--
arch/s390/crypto/aes_s390.c=1045=MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm");
arch/s390/crypto/aes_s390.c:1046:MODULE_LICENSE("GPL");
--
arch/s390/crypto/hmac_s390.c=425=MODULE_DESCRIPTION("S390 HMAC driver");
arch/s390/crypto/hmac_s390.c:426:MODULE_LICENSE("GPL");
--
arch/s390/crypto/paes_s390.c=1728=MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm with protected keys");
arch/s390/crypto/paes_s390.c:1729:MODULE_LICENSE("GPL");
--
arch/s390/crypto/phmac_s390.c=1073=MODULE_DESCRIPTION("S390 HMAC driver for protected keys");
arch/s390/crypto/phmac_s390.c:1074:MODULE_LICENSE("GPL");
--
arch/s390/crypto/prng.c-29-
arch/s390/crypto/prng.c:30:MODULE_LICENSE("GPL");
arch/s390/crypto/prng.c-31-MODULE_AUTHOR("IBM Corporation");
--
arch/s390/lib/test_kprobes.c=75=MODULE_DESCRIPTION("KUnit tests for kprobes");
arch/s390/lib/test_kprobes.c:76:MODULE_LICENSE("GPL");
--
arch/s390/lib/test_modules.c=32=MODULE_DESCRIPTION("KUnit test that modules with many relocations are loaded properly");
arch/s390/lib/test_modules.c:33:MODULE_LICENSE("GPL");
--
arch/s390/lib/test_unwind.c=522=MODULE_DESCRIPTION("KUnit test for unwind_for_each_frame");
arch/s390/lib/test_unwind.c:523:MODULE_LICENSE("GPL");
--
arch/s390/mm/cmm.c=446=MODULE_DESCRIPTION("Cooperative memory management interface");
arch/s390/mm/cmm.c:447:MODULE_LICENSE("GPL");
--
arch/s390/net/pnet.c=91=MODULE_DESCRIPTION("pnetid determination from utility strings");
arch/s390/net/pnet.c:92:MODULE_LICENSE("GPL");
--
arch/sh/boards/mach-hp6xx/hp6xx_apm.c=108=MODULE_DESCRIPTION("hp6xx Advanced Power Management");
arch/sh/boards/mach-hp6xx/hp6xx_apm.c:109:MODULE_LICENSE("GPL");
--
arch/sh/boards/mach-landisk/gio.c=162=module_exit(gio_exit);
arch/sh/boards/mach-landisk/gio.c-163-
arch/sh/boards/mach-landisk/gio.c:164:MODULE_LICENSE("GPL");
--
arch/sh/drivers/dma/dma-api.c=273=MODULE_DESCRIPTION("DMA API for SuperH");
arch/sh/drivers/dma/dma-api.c:274:MODULE_LICENSE("GPL v2");
--
arch/sh/drivers/dma/dma-g2.c=196=MODULE_DESCRIPTION("G2 bus DMA driver");
arch/sh/drivers/dma/dma-g2.c:197:MODULE_LICENSE("GPL v2");
--
arch/sh/drivers/dma/dma-pvr2.c=101=MODULE_DESCRIPTION("NEC PowerVR 2 DMA driver");
arch/sh/drivers/dma/dma-pvr2.c:102:MODULE_LICENSE("GPL v2");
--
arch/sh/drivers/dma/dma-sh.c=424=MODULE_DESCRIPTION("SuperH On-Chip DMAC Support");
arch/sh/drivers/dma/dma-sh.c:425:MODULE_LICENSE("GPL v2");
--
arch/sh/drivers/push-switch.c=134=MODULE_DESCRIPTION("Generic push-switch framework");
arch/sh/drivers/push-switch.c:135:MODULE_LICENSE("GPL v2");
--
arch/sh/kernel/cpu/sh4/sq.c=412=MODULE_DESCRIPTION("Simple API for SH-4 integrated Store Queues");
arch/sh/kernel/cpu/sh4/sq.c:413:MODULE_LICENSE("GPL");
--
arch/sh/mm/cache-debugfs.c=107=module_init(cache_debugfs_init);
arch/sh/mm/cache-debugfs.c-108-
arch/sh/mm/cache-debugfs.c:109:MODULE_LICENSE("GPL v2");
--
arch/sh/mm/tlb-debugfs.c=158=module_init(tlb_debugfs_init);
arch/sh/mm/tlb-debugfs.c-159-
arch/sh/mm/tlb-debugfs.c:160:MODULE_LICENSE("GPL v2");
--
arch/sparc/crypto/aes_glue.c=337=module_exit(aes_sparc64_mod_fini);
arch/sparc/crypto/aes_glue.c-338-
arch/sparc/crypto/aes_glue.c:339:MODULE_LICENSE("GPL");
arch/sparc/crypto/aes_glue.c-340-MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm, sparc64 aes opcode accelerated");
--
arch/sparc/crypto/camellia_glue.c=286=module_exit(camellia_sparc64_mod_fini);
arch/sparc/crypto/camellia_glue.c-287-
arch/sparc/crypto/camellia_glue.c:288:MODULE_LICENSE("GPL");
arch/sparc/crypto/camellia_glue.c-289-MODULE_DESCRIPTION("Camellia Cipher Algorithm, sparc64 camellia opcode accelerated");
--
arch/sparc/kernel/chmc.c=34=MODULE_DESCRIPTION("UltraSPARC-III memory controller driver");
arch/sparc/kernel/chmc.c:35:MODULE_LICENSE("GPL");
arch/sparc/kernel/chmc.c-36-MODULE_VERSION(DRV_MODULE_VERSION);
--
arch/sparc/kernel/ds.c=37=MODULE_DESCRIPTION("Sun LDOM domain services driver");
arch/sparc/kernel/ds.c:38:MODULE_LICENSE("GPL");
arch/sparc/kernel/ds.c-39-MODULE_VERSION(DRV_MODULE_VERSION);
--
arch/sparc/kernel/led.c=144=MODULE_DESCRIPTION("Provides control of the front LED on SPARC systems.");
arch/sparc/kernel/led.c:145:MODULE_LICENSE("GPL");
arch/sparc/kernel/led.c-146-MODULE_VERSION(LED_VERSION);
--
arch/sparc/video/video-common.c=24=MODULE_DESCRIPTION("Sparc video helpers");
arch/sparc/video/video-common.c:25:MODULE_LICENSE("GPL");
--
arch/um/drivers/harddog_kern.c=52=MODULE_DESCRIPTION("UML hardware watchdog");
arch/um/drivers/harddog_kern.c:53:MODULE_LICENSE("GPL");
arch/um/drivers/harddog_kern.c-54-
--
arch/um/drivers/hostaudio_kern.c=319=MODULE_DESCRIPTION("UML Audio Relay");
arch/um/drivers/hostaudio_kern.c:320:MODULE_LICENSE("GPL");
arch/um/drivers/hostaudio_kern.c-321-
--
arch/um/drivers/random.c=120=MODULE_DESCRIPTION("UML Host Random Number Generator (RNG) driver");
arch/um/drivers/random.c:121:MODULE_LICENSE("GPL");
--
arch/um/drivers/virtio_uml.c=1543=MODULE_DESCRIPTION("UML driver for vhost-user virtio devices");
arch/um/drivers/virtio_uml.c:1544:MODULE_LICENSE("GPL");
--
arch/x86/crypto/aegis128-aesni-glue.c=281=module_exit(crypto_aegis128_aesni_module_exit);
arch/x86/crypto/aegis128-aesni-glue.c-282-
arch/x86/crypto/aegis128-aesni-glue.c:283:MODULE_LICENSE("GPL");
arch/x86/crypto/aegis128-aesni-glue.c-284-MODULE_AUTHOR("Ondrej Mosnacek <omosnacek@gmail.com>");
--
arch/x86/crypto/aesni-intel_glue.c=1671=MODULE_DESCRIPTION("AES cipher and modes, optimized with AES-NI or VAES instructions");
arch/x86/crypto/aesni-intel_glue.c:1672:MODULE_LICENSE("GPL");
arch/x86/crypto/aesni-intel_glue.c-1673-MODULE_ALIAS_CRYPTO("aes");
--
arch/x86/crypto/aria_aesni_avx2_glue.c=239=module_exit(aria_avx2_exit);
arch/x86/crypto/aria_aesni_avx2_glue.c-240-
arch/x86/crypto/aria_aesni_avx2_glue.c:241:MODULE_LICENSE("GPL");
arch/x86/crypto/aria_aesni_avx2_glue.c-242-MODULE_AUTHOR("Taehee Yoo <ap420073@gmail.com>");
--
arch/x86/crypto/aria_aesni_avx_glue.c=219=module_exit(aria_avx_exit);
arch/x86/crypto/aria_aesni_avx_glue.c-220-
arch/x86/crypto/aria_aesni_avx_glue.c:221:MODULE_LICENSE("GPL");
arch/x86/crypto/aria_aesni_avx_glue.c-222-MODULE_AUTHOR("Taehee Yoo <ap420073@gmail.com>");
]
]
|
| 197/4 |
2026/05/10 03:24 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 90042
output: 58
thoughts: 2945
Thoughts: **Final Review and Confidence Check**
Okay, let's consolidate my understanding and confirm that this is the right approach. I've spent considerable time tracing the calls and ensuring the exclusive claim handling is robust. It all boils down to safely preventing concurrent modifications to the NBD device size while it's in use, especially in cases where we can't rely solely on `disk_openers` to indicate exclusivity, which is the netlink scenario.
First, I confirmed that `bd_prepare_to_claim` is indeed permissible because `nbd.c` has `MODULE_LICENSE("GPL");`.
The core of the fix involves propagating an `excl` flag throughout the ioctl path and netlink handlers. Specifically, `nbd_set_size` now accepts `excl`. When `excl` is *false*, `bd_prepare_to_claim` is called before changing size, and `bd_abort_claiming` is called afterward, handling the claim lifecycle. If `excl` is *true*, we skip this claiming step.
I rigorously audited the changes to the function signatures of `nbd_set_size`, `__nbd_ioctl`, `nbd_start_device_ioctl` and `nbd_start_device` as well as their callers. Every single call site in the relevant code paths was reviewed. I examined `nbd_ioctl`, `nbd_genl_size_set`, and `nbd_genl_connect` and `nbd_genl_reconfigure`. I confirmed the exclusive flag is passed correctly based on the `BLK_OPEN_EXCL` mode in the ioctl path, and correctly always set `false` for netlink. The netlink path specifically, which can have one "opener" even while a filesystem is mounted, is where this fixes the race condition that was the root of this exercise. I checked for any missing updates.
I verified the correct usage of `bd_prepare_to_claim` and `bd_abort_claiming`, confirming the correct control flow whether the claim or limit update succeeds or fails. Importantly, I ensured that `bd_abort_claiming` is *always* called after the size change attempt, even if the change itself fails.
I validated that early returns in `nbd_set_size` (due to invalid parameters or an inactive NBD device) all occur *before* the exclusive claim is even attempted, so that there's no claim leakage.
I looked in detail at `nbd_genl_size_set` because it's called from both `nbd_genl_connect` and `nbd_genl_reconfigure`. I made sure both pass the right flag, and that the order of the calls and their relationship to the device's state are correct.
I have confirmed that the `nbd->disk->part0` pointer, which is the target of the `bd_prepare_to_claim` call, is always valid and correctly represents the block device we need to protect. It's allocated in `nbd_alloc_disk`/`nbd_dev_add` and associated with the `bdev` in the ioctl paths, and properly used with the device.
I've cross-referenced with `loop.c` to confirm that the `bd_prepare_to_claim`/`bd_abort_claiming` approach mirrors the established pattern in the kernel for this kind of protection, confirming our approach.
I reviewed the compilation considerations and made sure the necessary headers were present.
My initial premise in the review was validated. I believe the final response will be a succinct summary to reflect that I am confident that the provided fix correctly addresses the race condition in network block devices (NBD) by using the exclusive claim in the `nbd_set_size` function to prevent concurrent modifications while the device is mounted. This robust method utilizes the `bd_prepare_to_claim` and `bd_abort_claiming` kernel functions to ensure the changes are made in a safe manner that is safe from TOCTOU race conditions.
|
| 198/4 |
2026/05/10 03:24 |
tool |
codeexpert |
3m
Args: map[Question:Is there any issue with using `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` in `drivers/block/nbd.c`?]
Results: map[Answer:Using `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` in `drivers/block/nbd.c` (specifically within `nbd_set_size`) introduces several significant issues:
### 1. Potential Deadlock (ABBA)
There is a high risk of an ABBA deadlock between the global `bdev_lock` (used by `bd_prepare_to_claim`) and the NBD-internal `nbd->config_lock`.
* **Thread A (`bdev_open` with `O_EXCL`)**: Takes the claim on the device (setting `bd_claiming` under `bdev_lock`), then calls `nbd_open`, which attempts to acquire `nbd->config_lock`.
* **Thread B (`nbd_ioctl` or Netlink)**: Already holds `nbd->config_lock` and calls `nbd_set_size`. If `nbd_set_size` calls `bd_prepare_to_claim`, it will attempt to acquire `bdev_lock`. If Thread A is currently claiming the device, `bd_prepare_to_claim` will release `bdev_lock` and sleep waiting for the claim to finish. However, Thread A is stuck waiting for `nbd->config_lock` held by Thread B.
### 2. Missing Claim Cleanup
`bd_prepare_to_claim` is designed to be the first half of a claiming process. It must be followed by either `bd_finish_claiming` (to keep the claim) or `bd_abort_claiming` (to release it). If used as a standalone call, the device would remain in the "claiming" state (`bd_claiming` set) indefinitely, which would block all future exclusive opens and other claiming attempts on the device.
### 3. Breakage of Online Resizing
One of the features of NBD is the ability to resize a device while it is in use (e.g., while a filesystem is mounted). If a filesystem is mounted, it has already claimed the block device exclusively. In this state, `bd_prepare_to_claim` will return `-EBUSY`, preventing `nbd_set_size` from proceeding. This would effectively break online resizing for any claimed NBD device.
### 4. Incompatibility with Exclusive Openers
If a userspace tool opens `/dev/nbd0` with `O_EXCL` and then issues an `NBD_SET_SIZE` ioctl, the ioctl would fail. This is because the device is already claimed by the file descriptor's holder, and `bd_prepare_to_claim` would see a holder mismatch (the file holder vs. the `nbd_set_size` function pointer).
### 5. Restricted Usage
The `bd_prepare_to_claim` function is exported specifically for the loop driver (as noted by the comment `EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */` in `block/bdev.c`). Its use in other drivers is generally discouraged unless they share the exact same requirements and have carefully managed the locking order to avoid the deadlocks mentioned above.
### Current Synchronization in NBD
Note that `nbd_set_size` already utilizes `queue_limits_commit_update_frozen()`, which calls `blk_mq_freeze_queue()`. This ensures that the request queue is quiesced and no I/O is in progress while the limits (including block size and capacity) are updated, providing necessary synchronization without the side effects of claiming the block device.]
|
| 199/5 |
2026/05/10 03:24 |
agent |
codeexpert |
3m
Model:
Instruction:
You are a capable Linux kernel developer tasked with researching complex questions
about kernel source code. You will be given a concrete question, and need to provide
a concrete answer.
Use tools extensively while researching the question. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Prefer calling several tools at the same time to save round-trips.
Prompt: Is there any issue with using `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` in `drivers/block/nbd.c`?
Reply: Using `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` in `drivers/block/nbd.c` (specifically within `nbd_set_size`) introduces several significant issues:
### 1. Potential Deadlock (ABBA)
There is a high risk of an ABBA deadlock between the global `bdev_lock` (used by `bd_prepare_to_claim`) and the NBD-internal `nbd->config_lock`.
* **Thread A (`bdev_open` with `O_EXCL`)**: Takes the claim on the device (setting `bd_claiming` under `bdev_lock`), then calls `nbd_open`, which attempts to acquire `nbd->config_lock`.
* **Thread B (`nbd_ioctl` or Netlink)**: Already holds `nbd->config_lock` and calls `nbd_set_size`. If `nbd_set_size` calls `bd_prepare_to_claim`, it will attempt to acquire `bdev_lock`. If Thread A is currently claiming the device, `bd_prepare_to_claim` will release `bdev_lock` and sleep waiting for the claim to finish. However, Thread A is stuck waiting for `nbd->config_lock` held by Thread B.
### 2. Missing Claim Cleanup
`bd_prepare_to_claim` is designed to be the first half of a claiming process. It must be followed by either `bd_finish_claiming` (to keep the claim) or `bd_abort_claiming` (to release it). If used as a standalone call, the device would remain in the "claiming" state (`bd_claiming` set) indefinitely, which would block all future exclusive opens and other claiming attempts on the device.
### 3. Breakage of Online Resizing
One of the features of NBD is the ability to resize a device while it is in use (e.g., while a filesystem is mounted). If a filesystem is mounted, it has already claimed the block device exclusively. In this state, `bd_prepare_to_claim` will return `-EBUSY`, preventing `nbd_set_size` from proceeding. This would effectively break online resizing for any claimed NBD device.
### 4. Incompatibility with Exclusive Openers
If a userspace tool opens `/dev/nbd0` with `O_EXCL` and then issues an `NBD_SET_SIZE` ioctl, the ioctl would fail. This is because the device is already claimed by the file descriptor's holder, and `bd_prepare_to_claim` would see a holder mismatch (the file holder vs. the `nbd_set_size` function pointer).
### 5. Restricted Usage
The `bd_prepare_to_claim` function is exported specifically for the loop driver (as noted by the comment `EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */` in `block/bdev.c`). Its use in other drivers is generally discouraged unless they share the exact same requirements and have carefully managed the locking order to avoid the deadlocks mentioned above.
### Current Synchronization in NBD
Note that `nbd_set_size` already utilizes `queue_limits_commit_update_frozen()`, which calls `blk_mq_freeze_queue()`. This ensures that the request queue is quiesced and no I/O is in progress while the limits (including block size and capacity) are updated, providing necessary synchronization without the side effects of claiming the block device.
|
| 200/6 |
2026/05/10 03:24 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 2296
output: 46
thoughts: 119
Thoughts: Okay, here's my understanding, tailored for an expert audience, as if it were my own thought process:
**Diving into `bd_prepare_to_claim` in the NBD Driver**
Alright, so the user's raising a flag about `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` within the `nbd.c` driver. My immediate thought is, let's dissect this. They're clearly concerned about something related to that function call and its specific arguments. My first step here is to figure out the context.
I need to understand what `bd_prepare_to_claim` actually *does* in relation to the Network Block Device (NBD) setup. Is it something that's already in the code and potentially problematic, or is the user suggesting its inclusion, and raising pre-emptive questions? The best way to begin is to go directly to the source. I'll need to open `drivers/block/nbd.c` and hunt for that specific function call, looking for its usage. This will give me the immediate context of what's happening. From there, I can begin to evaluate the situation. Are we looking at a bug, a potential race condition, or a simply an unusual usage pattern? Time to dig in!
|
| 201/6 |
2026/05/10 03:24 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:1 Name:bd_prepare_to_claim SourceTreePrefix:drivers/block/nbd.c]
Results: map[References:<nil> TruncatedOutput:false]
|
| 202/6 |
2026/05/10 03:24 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 2761
output: 81
thoughts: 106
Thoughts: **Analyzing the Use of `bd_prepare_to_claim` in the NBD Driver Context**
Okay, so initially, it appears that `bd_prepare_to_claim` isn't directly utilized within `drivers/block/nbd.c`. That seems odd, but I'm an expert, I've seen things missed before. I need to make sure I haven't overlooked something subtle. Let me quickly double-check the source code within that file. Perhaps it's called indirectly, or maybe my initial search parameters were too narrow. I should also consider a full tree search, just to be absolutely certain I haven't missed a more obscure usage pattern.
Ah, right, the user's framing the question as a hypothetical or potential change, specifically, "Is there any issue with using...". That context changes my approach. Instead of focusing on *where* it's currently used (or not), I need to understand *how* the function works. I need to delve into the definition and relevant documentation of `bd_prepare_to_claim` to assess its implications within the NBD driver's architecture. I need to fully understand its intended purpose and the potential risks or benefits of using it in this context.
|
| 203/6 |
2026/05/10 03:24 |
tool |
codesearch-definition-comment |
0m
Args: map[ContextFile:fs/block_dev.c Name:bd_prepare_to_claim]
Results: map[Comment:/**
* bd_prepare_to_claim - claim a block device
* @bdev: block device of interest
* @holder: holder trying to claim @bdev
* @hops: holder ops.
*
* Claim @bdev. This function fails if @bdev is already claimed by another
* holder and waits if another claiming is in progress. return, the caller
* has ownership of bd_claiming and bd_holder[s].
*
* RETURNS:
* 0 if @bdev can be claimed, -EBUSY otherwise.
*/
Kind:function]
|
| 204/6 |
2026/05/10 03:24 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/block_dev.c IncludeLines:true Name:bd_prepare_to_claim]
Results: map[SourceCode: 577: /**
578: * bd_prepare_to_claim - claim a block device
579: * @bdev: block device of interest
580: * @holder: holder trying to claim @bdev
581: * @hops: holder ops.
582: *
583: * Claim @bdev. This function fails if @bdev is already claimed by another
584: * holder and waits if another claiming is in progress. return, the caller
585: * has ownership of bd_claiming and bd_holder[s].
586: *
587: * RETURNS:
588: * 0 if @bdev can be claimed, -EBUSY otherwise.
589: */
590: int bd_prepare_to_claim(struct block_device *bdev, void *holder,
591: const struct blk_holder_ops *hops)
592: {
593: struct block_device *whole = bdev_whole(bdev);
594:
595: if (WARN_ON_ONCE(!holder))
596: return -EINVAL;
597: retry:
598: mutex_lock(&bdev_lock);
599: /* if someone else claimed, fail */
600: if (!bd_may_claim(bdev, holder, hops)) {
601: mutex_unlock(&bdev_lock);
602: return -EBUSY;
603: }
604:
605: /* if claiming is already in progress, wait for it to finish */
606: if (whole->bd_claiming) {
607: wait_queue_head_t *wq = __var_waitqueue(&whole->bd_claiming);
608: DEFINE_WAIT(wait);
609:
610: prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
611: mutex_unlock(&bdev_lock);
612: schedule();
613: finish_wait(wq, &wait);
614: goto retry;
615: }
616:
617: /* yay, all mine */
618: whole->bd_claiming = holder;
619: mutex_unlock(&bdev_lock);
620: return 0;
621: }
SourceFile:block/bdev.c]
|
| 205/6 |
2026/05/10 03:24 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4046
output: 43
thoughts: 137
Thoughts: **Navigating the Block Device Landscape**
Okay, first things first, let's get our bearings. The tool output mentioned `block/bdev.c`, so I need to make sure I'm looking in the right place, not in `fs/block_dev.c`. I'm going to trust the output and pivot to the former.
Now, let's shift gears and consider the context of `nbd.c`. The user's prompt mentioned `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`. Since they used `nbd_set_size`, that's likely where the solution lies.
I'll go ahead and pinpoint the function `nbd_set_size`. Time to head over to `drivers/block/nbd.c`. I need to understand how `nbd_set_size` is implemented and how it's being employed in this setup. Let's see what we can find.
|
| 206/6 |
2026/05/10 03:24 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_set_size]
Results: map[SourceCode: 334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
335: {
336: struct queue_limits lim;
337: int error;
338:
339: if (!blksize)
340: blksize = 1u << NBD_DEF_BLKSIZE_BITS;
341:
342: if (blk_validate_block_size(blksize))
343: return -EINVAL;
344:
345: if (bytesize < 0)
346: return -EINVAL;
347:
348: nbd->config->bytesize = bytesize;
349: nbd->config->blksize_bits = __ffs(blksize);
350:
351: if (!nbd->pid)
352: return 0;
353:
354: lim = queue_limits_start_update(nbd->disk->queue);
355: if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
356: lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
357: else
358: lim.max_hw_discard_sectors = 0;
359: if (!(nbd->config->flags & NBD_FLAG_SEND_FLUSH)) {
360: lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
361: } else if (nbd->config->flags & NBD_FLAG_SEND_FUA) {
362: lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
363: } else {
364: lim.features |= BLK_FEAT_WRITE_CACHE;
365: lim.features &= ~BLK_FEAT_FUA;
366: }
367: if (nbd->config->flags & NBD_FLAG_ROTATIONAL)
368: lim.features |= BLK_FEAT_ROTATIONAL;
369: if (nbd->config->flags & NBD_FLAG_SEND_WRITE_ZEROES)
370: lim.max_write_zeroes_sectors = UINT_MAX >> SECTOR_SHIFT;
371:
372: lim.logical_block_size = blksize;
373: lim.physical_block_size = blksize;
374: error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
375: if (error)
376: return error;
377:
378: if (max_part)
379: set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
380: if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
381: kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
382: return 0;
383: }
SourceFile:drivers/block/nbd.c]
|
| 207/6 |
2026/05/10 03:24 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 5346
output: 31
thoughts: 127
Thoughts: Okay, let me think this through.
**Analyzing the `bd_prepare_to_claim` Function Call**
Hold on a second... `nbd_set_size` is a *function*? That feels off. I'm used to seeing the `holder` argument in `bd_prepare_to_claim` being an object, something that *owns* the device or represents the entity that will be claiming it. It's usually a device structure, a partition object, or something similar, not just a function pointer. This use of `nbd_set_size` as the `holder` in `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` strikes me as unusual, and I need to understand it better.
I need to see if this pattern is used anywhere else in the kernel. Let me search for other instances of `bd_prepare_to_claim` calls and analyze what is actually being passed as the `holder` argument in those situations. Understanding the typical usage of that function will hopefully help clarify why `nbd_set_size` is being used here, if it is a specific design pattern or perhaps a case of unusual use.
|
| 208/6 |
2026/05/10 03:25 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:1 Name:bd_prepare_to_claim]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:bdev_open SourceFile:block/bdev.c SourceLine:943 SourceSnippet: 942: mode |= BLK_OPEN_EXCL;
943: ret = bd_prepare_to_claim(bdev, holder, hops);
944: if (ret)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:disk_scan_partitions SourceFile:block/genhd.c SourceLine:380 SourceSnippet: 379: if (!(mode & BLK_OPEN_EXCL)) {
380: ret = bd_prepare_to_claim(disk->part0, disk_scan_partitions,
381: NULL);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:loop_configure SourceFile:drivers/block/loop.c SourceLine:1011 SourceSnippet:1010: if (!(mode & BLK_OPEN_EXCL)) {
1011: error = bd_prepare_to_claim(bdev, loop_configure, NULL);
1012: if (error)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:loop_set_block_size SourceFile:drivers/block/loop.c SourceLine:1457 SourceSnippet:1456: if (!(mode & BLK_OPEN_EXCL)) {
1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
1458: if (err)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:truncate_bdev_range SourceFile:block/bdev.c SourceLine:120 SourceSnippet: 119: if (!(mode & BLK_OPEN_EXCL)) {
120: int err = bd_prepare_to_claim(bdev, truncate_bdev_range, NULL);
121: if (err)
]] TruncatedOutput:false]
|
| 209/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6346
output: 43
thoughts: 254
Thoughts: **Analyzing the Device Claiming Pattern**
Okay, so the user's question about device claiming using function pointers immediately rings a bell. It's a pretty standard approach, actually, when you need exclusive access to a block device for a critical operation. It's about temporarily "grabbing" the device to do something, and then releasing it cleanly. I see a concrete example in `loop.c`:
```c
1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
```
That looks *very* similar to what they're doing with `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`. Hang on, `nbd->disk->part0` is a `struct block_device *`, right? Got it.
Let me take another look at that `nbd_set_size` function because that is a very important part of the code. Oh, right, it calls `set_capacity_and_notify`. And *that* function... well, if we're modifying the device's size, it's pretty obvious that needs to be protected, right? Race conditions would be a nightmare.
And now I remember, a critical aspect of this pattern is that if I am using `bd_prepare_to_claim`, I *must* ensure a subsequent call to `bd_abort_claiming` or `bd_finish_claiming` for cleanup. It's all about resource management. Just to be sure, let's take a quick look at how `loop_set_block_size` handles that.
|
| 210/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/loop.c IncludeLines:true Name:loop_set_block_size]
Results: map[SourceCode:1445: static int loop_set_block_size(struct loop_device *lo, blk_mode_t mode,
1446: struct block_device *bdev, unsigned long arg)
1447: {
1448: struct queue_limits lim;
1449: unsigned int memflags;
1450: int err = 0;
1451:
1452: /*
1453: * If we don't hold exclusive handle for the device, upgrade to it
1454: * here to avoid changing device under exclusive owner.
1455: */
1456: if (!(mode & BLK_OPEN_EXCL)) {
1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
1458: if (err)
1459: return err;
1460: }
1461:
1462: err = mutex_lock_killable(&lo->lo_mutex);
1463: if (err)
1464: goto abort_claim;
1465:
1466: if (lo->lo_state != Lo_bound) {
1467: err = -ENXIO;
1468: goto unlock;
1469: }
1470:
1471: if (lo->lo_queue->limits.logical_block_size == arg)
1472: goto unlock;
1473:
1474: sync_blockdev(lo->lo_device);
1475: invalidate_bdev(lo->lo_device);
1476:
1477: lim = queue_limits_start_update(lo->lo_queue);
1478: loop_update_limits(lo, &lim, arg);
1479:
1480: memflags = blk_mq_freeze_queue(lo->lo_queue);
1481: err = queue_limits_commit_update(lo->lo_queue, &lim);
1482: loop_update_dio(lo);
1483: blk_mq_unfreeze_queue(lo->lo_queue, memflags);
1484:
1485: unlock:
1486: mutex_unlock(&lo->lo_mutex);
1487: abort_claim:
1488: if (!(mode & BLK_OPEN_EXCL))
1489: bd_abort_claiming(bdev, loop_set_block_size);
1490: return err;
1491: }
SourceFile:drivers/block/loop.c]
|
| 211/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7721
output: 43
thoughts: 441
Thoughts: **Analyzing Block Device Claiming in NBD Context**
Okay, so I'm looking at this `loop_set_block_size` function, and the use of `bd_abort_claiming` at the very end is giving me pause. I need to understand the rationale here. Why `bd_abort_claiming` instead of `bd_finish_claiming`? Let's break it down. `bd_prepare_to_claim` sets `whole->bd_claiming` to the "holder", essentially starting the claim. `bd_abort_claiming` then resets it to `NULL`, whereas `bd_finish_claiming` sets `bdev->bd_holder` and clears the claiming pointer.
Ah, I think I'm getting it. If the goal is just to enforce exclusive access *during* the operation and then release the claim afterward, then `bd_abort_claiming` (or just clearing the `bd_claiming` flag) is the correct approach. It’s a temporary claim. It's used to prevent concurrent modifications during a specific operation.
So, `bd_prepare_to_claim` is the initial step to *start* the claim. If you want to *keep* the claim, you call `bd_finish_claiming`. If it's a transient claim, you "abort" it to release the `bd_claiming` pointer. This clarifies the intention.
Now, let's circle back to `nbd_set_size` in `nbd.c`. I see the user questioning the use of `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)` here. The next step is to examine where `nbd_set_size` is called to make sure it's safe to use `bd_prepare_to_claim` there.
From a quick code dive, it seems `nbd_set_size` is invoked from several places: the sysfs store function (`nbd_size_set`), the `nbd_ioctl` handler (for `NBD_SET_SIZE` and `NBD_SET_SIZE_BLOCKS` calls), `nbd_start_device_ioctl`, `nbd_genl_connect`, and `nbd_genl_reconfigure`. Let's start by digging into `nbd_size_set` (the sysfs implementation).
|
| 212/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_size_set]
Results: map[SourceCode: SourceFile:]
|
| 213/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 8742
output: 45
thoughts: 31
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Debugging a Potential Size Mismatch**
Right, so I'm hitting a snag. My initial assumption about the size definition might be off. Perhaps it's being handled internally through a macro, or worse, I've got a typo in the identifier. Before I go too deep down this rabbit hole, I should do a quick check. The best approach is to start with a targeted search. I'll scan the codebase for all instances where `nbd_set_size` is called. That should quickly illuminate where this function is actually being invoked, reveal how the size is being set and what the call's context is, and hopefully, show me what the call is passing. From there, I can trace back to see how `nbd_set_size` is defined and what is happening to the size.
|
| 214/6 |
2026/05/10 03:25 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:5 Name:nbd_set_size SourceTreePrefix:drivers/block/nbd.c]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1608 SourceSnippet:1603: nbd_clear_sock_ioctl(nbd);
1604: return 0;
1605: case NBD_SET_SOCK:
1606: return nbd_add_socket(nbd, arg, false);
1607: case NBD_SET_BLKSIZE:
1608: return nbd_set_size(nbd, config->bytesize, arg);
1609: case NBD_SET_SIZE:
1610: return nbd_set_size(nbd, arg, nbd_blksize(config));
1611: case NBD_SET_SIZE_BLOCKS:
1612: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1613: return -EINVAL;
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1610 SourceSnippet:1605: case NBD_SET_SOCK:
1606: return nbd_add_socket(nbd, arg, false);
1607: case NBD_SET_BLKSIZE:
1608: return nbd_set_size(nbd, config->bytesize, arg);
1609: case NBD_SET_SIZE:
1610: return nbd_set_size(nbd, arg, nbd_blksize(config));
1611: case NBD_SET_SIZE_BLOCKS:
1612: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1613: return -EINVAL;
1614: return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1615: case NBD_SET_TIMEOUT:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:__nbd_ioctl SourceFile:drivers/block/nbd.c SourceLine:1614 SourceSnippet:1609: case NBD_SET_SIZE:
1610: return nbd_set_size(nbd, arg, nbd_blksize(config));
1611: case NBD_SET_SIZE_BLOCKS:
1612: if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1613: return -EINVAL;
1614: return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1615: case NBD_SET_TIMEOUT:
1616: nbd_set_cmd_timeout(nbd, arg);
1617: return 0;
1618:
1619: case NBD_SET_FLAGS:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_genl_size_set SourceFile:drivers/block/nbd.c SourceLine:2069 SourceSnippet:2064:
2065: if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
2066: bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
2067:
2068: if (bytes != config->bytesize || bsize != nbd_blksize(config))
2069: return nbd_set_size(nbd, bytes, bsize);
2070: return 0;
2071: }
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:nbd_start_device SourceFile:drivers/block/nbd.c SourceLine:1540 SourceSnippet:1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
]] TruncatedOutput:false]
|
| 215/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10209
output: 43
thoughts: 133
Thoughts: **Analyzing the nbd_set_size Function Call**
Okay, let's break this down. My initial observation is the mention of `nbd_genl_size_set`, which is a key starting point. The user is specifically concerned about the call to `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`. I see they're using `nbd->disk->part0` within `nbd_set_size`.
My immediate thought is, a potential pitfall here is that `nbd->disk` *could* be NULL or not fully initialized if `nbd_set_size` is triggered prematurely in the device setup sequence. However, in the typical NBD device lifecycle, `nbd->disk` *should* be established when the device itself is brought up.
To get a clearer picture of that initialization sequence, I really need to examine the `nbd_dev_add` function. I will go there next.
|
| 216/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_dev_add]
Results: map[SourceCode:1907: static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1908: {
1909: struct queue_limits lim = {
1910: .max_hw_sectors = 65536,
1911: .io_opt = 256 << SECTOR_SHIFT,
1912: .max_segments = USHRT_MAX,
1913: .max_segment_size = UINT_MAX,
1914: };
1915: struct nbd_device *nbd;
1916: struct gendisk *disk;
1917: int err = -ENOMEM;
1918:
1919: nbd = kzalloc_obj(struct nbd_device);
1920: if (!nbd)
1921: goto out;
1922:
1923: nbd->tag_set.ops = &nbd_mq_ops;
1924: nbd->tag_set.nr_hw_queues = 1;
1925: nbd->tag_set.queue_depth = 128;
1926: nbd->tag_set.numa_node = NUMA_NO_NODE;
1927: nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1928: nbd->tag_set.flags = BLK_MQ_F_BLOCKING;
1929: nbd->tag_set.driver_data = nbd;
1930: INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1931: nbd->backend = NULL;
1932:
1933: err = blk_mq_alloc_tag_set(&nbd->tag_set);
1934: if (err)
1935: goto out_free_nbd;
1936:
1937: mutex_lock(&nbd_index_mutex);
1938: if (index >= 0) {
1939: err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1940: GFP_KERNEL);
1941: if (err == -ENOSPC)
1942: err = -EEXIST;
1943: } else {
1944: err = idr_alloc(&nbd_index_idr, nbd, 0,
1945: (MINORMASK >> part_shift) + 1, GFP_KERNEL);
1946: if (err >= 0)
1947: index = err;
1948: }
1949: nbd->index = index;
1950: mutex_unlock(&nbd_index_mutex);
1951: if (err < 0)
1952: goto out_free_tags;
1953:
1954: disk = blk_mq_alloc_disk(&nbd->tag_set, &lim, NULL);
1955: if (IS_ERR(disk)) {
1956: err = PTR_ERR(disk);
1957: goto out_free_idr;
1958: }
1959: nbd->disk = disk;
1960:
1961: nbd->recv_workq = alloc_workqueue("nbd%d-recv",
1962: WQ_MEM_RECLAIM | WQ_HIGHPRI |
1963: WQ_UNBOUND, 0, nbd->index);
1964: if (!nbd->recv_workq) {
1965: dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1966: err = -ENOMEM;
1967: goto out_err_disk;
1968: }
1969:
1970: mutex_init(&nbd->config_lock);
1971: refcount_set(&nbd->config_refs, 0);
1972: /*
1973: * Start out with a zero references to keep other threads from using
1974: * this device until it is fully initialized.
1975: */
1976: refcount_set(&nbd->refs, 0);
1977: INIT_LIST_HEAD(&nbd->list);
1978: disk->major = NBD_MAJOR;
1979: disk->first_minor = index << part_shift;
1980: disk->minors = 1 << part_shift;
1981: disk->fops = &nbd_fops;
1982: disk->private_data = nbd;
1983: sprintf(disk->disk_name, "nbd%d", index);
1984: err = add_disk(disk);
1985: if (err)
1986: goto out_free_work;
1987:
1988: /*
1989: * Now publish the device.
1990: */
1991: refcount_set(&nbd->refs, refs);
1992: nbd_total_devices++;
1993: return nbd;
1994:
1995: out_free_work:
1996: destroy_workqueue(nbd->recv_workq);
1997: out_err_disk:
1998: put_disk(disk);
1999: out_free_idr:
2000: mutex_lock(&nbd_index_mutex);
2001: idr_remove(&nbd_index_idr, index);
2002: mutex_unlock(&nbd_index_mutex);
2003: out_free_tags:
2004: blk_mq_free_tag_set(&nbd->tag_set);
2005: out_free_nbd:
2006: kfree(nbd);
2007: out:
2008: return ERR_PTR(err);
2009: }
SourceFile:drivers/block/nbd.c]
|
| 217/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 12284
output: 41
thoughts: 342
Thoughts: **My Concerns Regarding `nbd_set_size` and Exclusive Device Access**
Okay, so I've got `nbd->disk` allocated, `add_disk` has been called, and now I'm thinking about how `nbd_set_size` interacts with exclusive access. Specifically, `nbd->disk->part0` is a `struct block_device *`. My concern is that I'm going to claim the whole disk with `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`.
The thing that bugs me is if there's any problem with doing this *inside* `nbd_set_size`. The documentation says that `nbd_set_size` can be called while the device is already open. If someone has `/dev/nbd0` open with `BLK_OPEN_EXCL`, `bd_prepare_to_claim` will return `-EBUSY`.
Looking at the code, in `nbd_set_size`:
```c
334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
```
It doesn't have a `mode` argument like `loop_set_block_size` did, which has me a little worried.
If `nbd_set_size` is called from an ioctl *on* the device itself, the device *is* already open. And if it's open exclusively, then `bd_prepare_to_claim` will fail if we're using a different holder.
But, wait... if it's called from `nbd_ioctl`, who is the holder? If the user opened `/dev/nbd0` with `O_EXCL`, the holder is the file pointer (or something related to the open). So, it seems like the holder has to match or we'll get that `-EBUSY`.
I need to look at `nbd_ioctl` to understand who the holder is.
|
| 218/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_ioctl]
Results: map[SourceCode:1640: static int nbd_ioctl(struct block_device *bdev, blk_mode_t mode,
1641: unsigned int cmd, unsigned long arg)
1642: {
1643: struct nbd_device *nbd = bdev->bd_disk->private_data;
1644: struct nbd_config *config = nbd->config;
1645: int error = -EINVAL;
1646:
1647: if (!capable(CAP_SYS_ADMIN))
1648: return -EPERM;
1649:
1650: /* The block layer will pass back some non-nbd ioctls in case we have
1651: * special handling for them, but we don't so just return an error.
1652: */
1653: if (_IOC_TYPE(cmd) != 0xab)
1654: return -EINVAL;
1655:
1656: mutex_lock(&nbd->config_lock);
1657:
1658: /* Don't allow ioctl operations on a nbd device that was created with
1659: * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1660: */
1661: if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1662: (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1663: error = __nbd_ioctl(bdev, nbd, cmd, arg);
1664: else
1665: dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1666: mutex_unlock(&nbd->config_lock);
1667: return error;
1668: }
SourceFile:drivers/block/nbd.c]
|
| 219/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 13650
output: 42
thoughts: 527
Thoughts: **Thinking Through the NBD Size Change Logic**
Okay, so I'm wrestling with how to handle size changes in the NBD driver, particularly in relation to exclusive access. The initial thought is that `nbd_ioctl` has a `blk_mode_t mode`, and that this mode might be crucial when calling `bd_prepare_to_claim` within `nbd_set_size`. Specifically, the code checks `if (!(mode & BLK_OPEN_EXCL))`. If exclusive access isn't requested, we *should* prepare to claim it.
But here's the rub: `nbd_set_size` is *also* called via Netlink: `nbd_genl_size_set`. And with Netlink, we don't have the luxury of a `blk_mode_t` derived from an open file descriptor. This means that if we call `bd_prepare_to_claim` from the Netlink path, we might fail if someone holds the device open exclusively. Is that *intended* behavior? Should we prevent a size change if someone has exclusive access, or should we allow it?
Ah, looking at `loop_set_block_size` provides a clue:
```c
1456: if (!(mode & BLK_OPEN_EXCL)) {
1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
1458: if (err)
1459: return err;
1460: }
```
If `mode & BLK_OPEN_EXCL` is *true*, the caller already has exclusive access, so it *doesn't* need to claim it. And more importantly, it shouldn't because the claim will fail if we are the current exclusive holder. We already have it.
However, if `mode & BLK_OPEN_EXCL` is true, who *is* the holder? When the block device is opened with `O_EXCL`, the `holder` is passed to `blkdev_get_by_dev`. So, the `mode` in `nbd_ioctl` is provided by the block layer.
With Netlink's `nbd_genl_size_set`, we *don't* have an open file. If we want to change the size, we should still try to claim it to check if there is an exclusive holder.
Okay, here's a wrinkle: `nbd_set_size` calls `set_capacity_and_notify`, which in turn calls `revalidate_disk_size`. Now I need to understand what's happening within `set_capacity_and_notify` and what the behavior of `revalidate_disk_size` is. Time to dig into that function.
|
| 220/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c IncludeLines:true Name:set_capacity_and_notify]
Results: map[SourceCode: 72: /*
73: * Set disk capacity and notify if the size is not currently zero and will not
74: * be set to zero. Returns true if a uevent was sent, otherwise false.
75: */
76: bool set_capacity_and_notify(struct gendisk *disk, sector_t size)
77: {
78: sector_t capacity = get_capacity(disk);
79: char *envp[] = { "RESIZE=1", NULL };
80:
81: set_capacity(disk, size);
82:
83: /*
84: * Only print a message and send a uevent if the gendisk is user visible
85: * and alive. This avoids spamming the log and udev when setting the
86: * initial capacity during probing.
87: */
88: if (size == capacity ||
89: !disk_live(disk) ||
90: (disk->flags & GENHD_FL_HIDDEN))
91: return false;
92:
93: pr_info_ratelimited("%s: detected capacity change from %lld to %lld\n",
94: disk->disk_name, capacity, size);
95:
96: /*
97: * Historically we did not send a uevent for changes to/from an empty
98: * device.
99: */
100: if (!capacity || !size)
101: return false;
102: kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
103: return true;
104: }
SourceFile:block/genhd.c]
|
| 221/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15325
output: 40
thoughts: 372
Thoughts: **Analyzing the `bd_prepare_to_claim` Function's Purpose**
Okay, so I'm looking at this `loop.c` code, and it seems like it's not doing anything *immediately* that requires a claim. That's the initial impression. But then I see this call to `bd_prepare_to_claim`, and I have to ask myself why that's even there. Line 1453 specifically mentions avoiding changes under an exclusive owner. Aha! Now it starts to click.
If a filesystem is mounted on `/dev/nbd0`, for example, the mount process, or the filesystem itself, likely has an exclusive handle on that device. It's essentially "claiming" it. Now, if I try to change the device's size via Netlink or another ioctl *without* using `O_EXCL`, I could be stepping on the toes of that exclusive owner, potentially leading to all sorts of filesystem corruption or instability.
So, if I'm understanding this correctly, `nbd_set_size` is modifying `nbd->config->bytesize` and then calling `set_capacity_and_notify`. This is probably where the potential problem lies. And if I use `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`, it's designed to *fail* if the device is already claimed, like in the case of a mounted filesystem.
But wait a minute... that's not what I normally expect. Usually, resizing a block device while it's mounted, an online resize, is perfectly acceptable. It might even be *necessary* in modern systems. So, if `bd_prepare_to_claim` *fails* when the device is claimed, that seems like it might be *too* restrictive, and could potentially block functionality.
Okay, let's step back a bit and look at this from another angle. I remember there's also `bd_may_claim`. That function should be the one to check if we can claim the device or not. If someone else already has the device claimed, `bd_may_claim` should return `false`.
So, the question is whether `bd_may_claim` provides a more nuanced, and perhaps less restrictive, check. I need to dig into `bd_may_claim` now and see if this is correct. I should check how that function works and see what's what.
|
| 222/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:bd_may_claim]
Results: map[SourceCode: 537: /**
538: * bd_may_claim - test whether a block device can be claimed
539: * @bdev: block device of interest
540: * @holder: holder trying to claim @bdev
541: * @hops: holder ops
542: *
543: * Test whether @bdev can be claimed by @holder.
544: *
545: * RETURNS:
546: * %true if @bdev can be claimed, %false otherwise.
547: */
548: static bool bd_may_claim(struct block_device *bdev, void *holder,
549: const struct blk_holder_ops *hops)
550: {
551: struct block_device *whole = bdev_whole(bdev);
552:
553: lockdep_assert_held(&bdev_lock);
554:
555: if (bdev->bd_holder) {
556: /*
557: * The same holder can always re-claim.
558: */
559: if (bdev->bd_holder == holder) {
560: if (WARN_ON_ONCE(bdev->bd_holder_ops != hops))
561: return false;
562: return true;
563: }
564: return false;
565: }
566:
567: /*
568: * If the whole devices holder is set to bd_may_claim, a partition on
569: * the device is claimed, but not the whole device.
570: */
571: if (whole != bdev &&
572: whole->bd_holder && whole->bd_holder != bd_may_claim)
573: return false;
574: return true;
575: }
SourceFile:block/bdev.c]
|
| 223/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16830
output: 29
thoughts: 161
Thoughts: **Analyzing Device Claiming and Resizing**
Okay, so I'm thinking, right, the key here is this `bdev->bd_holder`. If that's set, and it's *not* the entity trying to claim the device, we get a `false` return. Pretty straightforward. Meaning if a filesystem has the device locked down, `bd_prepare_to_claim` will spit out a `-EBUSY` error.
Now, where this gets interesting is if we're dealing with `nbd` wanting to dynamically resize a device while it's mounted. That `bd_prepare_to_claim` call could be a serious bottleneck *if* we're using it for *every* single resize operation. I need to be sure on this point.
Hold on... I'm reminded `loop_set_block_size` uses this function. Does the `loop` driver handle resizing while mounted? Hmm... wait a minute, `loop_set_block_size` is specifically for altering the *block size* itself. That's not *necessarily* the same thing as changing the overall capacity, though they are related.
Alright, what about `loop_set_capacity`? Does *that* exist? I should check and make sure I know about all the moving parts. This is a very important question.
|
| 224/6 |
2026/05/10 03:25 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:1 Name:loop_set_capacity]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:lo_simple_ioctl SourceFile:drivers/block/loop.c SourceLine:1503 SourceSnippet:1502: case LOOP_SET_CAPACITY:
1503: err = loop_set_capacity(lo);
1504: break;
]] TruncatedOutput:false]
|
| 225/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17423
output: 41
thoughts: 11
Thoughts: Okay, let's dive into this. Here's my take on those thoughts, as if they're my own:
**Analyzing `loop_set_capacity`**
Alright, *loop_set_capacity*. What's this all about? Right away, my expert mind starts to race. This likely relates to managing the resources allocated to a loop, which is a key concept in achieving optimal performance and resource utilization. We need to consider a few things. Does this function control the maximum number of iterations allowed, the size of some internal buffer, or perhaps the maximum memory footprint the loop can use? It's probably some combination of these, and the specifics will impact the control flow and resource consumption.
The name "capacity" is telling. It implies a limit, a boundary. I'm already mentally modeling the potential implications for memory allocation, error handling (what happens if we try to exceed capacity?), and how this function integrates with the loop's overall design. I'm wondering: Is this capacity dynamic, or is it set at compile time? If dynamic, how is it managed? Is there any mechanism for resizing or reallocating resources within the loop based on the capacity changes? Are there any concurrency implications if this is a shared resource?
I'm also curious about the potential "failure modes" of this function. Under what conditions might it fail? Does it throw exceptions, return error codes, or perhaps silently truncate operations? That kind of detail is critical for ensuring robust code. Ultimately, I need to understand this function's exact role in the system. It's time to dig deeper into the code and see how it is actually implemented.
|
| 226/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/loop.c IncludeLines:true Name:loop_set_capacity]
Results: map[SourceCode:1406: static int loop_set_capacity(struct loop_device *lo)
1407: {
1408: loff_t size;
1409:
1410: if (unlikely(lo->lo_state != Lo_bound))
1411: return -ENXIO;
1412:
1413: size = lo_calculate_size(lo, lo->lo_backing_file);
1414: loop_set_size(lo, size);
1415:
1416: return 0;
1417: }
SourceFile:drivers/block/loop.c]
|
| 227/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18009
output: 41
thoughts: 8
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Analyzing the Loop Set Size**
Alright, so I'm thinking about this `loop_set_size` variable. This is clearly a critical parameter in the execution of the algorithm. I need to understand its implications thoroughly. What is it defining? Is it the size of the data being processed in each iteration, or the number of iterations themselves? Knowing that fundamentally impacts the performance characteristics I can expect. A small `loop_set_size` would result in a high iteration overhead, whilst a large `loop_set_size` may increase memory load, possibly triggering cache misses and slowdowns.
I need to quickly assess how this value interacts with the overall system architecture. Is this a system where parallelization can be exploited? Does `loop_set_size` directly influence the amount of work assigned to each thread or core? If so, finding the correct balance is paramount for achieving optimal throughput. If it's a fixed size, I need to know why that size was chosen. Is it a function of a hardware constraint, a memory buffer, or is it a calculated value derived from some internal heuristic?
I'm mentally comparing this to other systems I've worked on, where similar parameters had significant impacts on resource utilization and throughput. I'm wondering if there's any easy way to test or visualize its impact. Perhaps a quick experiment, varying this parameter and measuring performance metrics, would be the quickest way to validate my assumptions and find the 'sweet spot' for it? I should also quickly review the surrounding code to ensure that I have the correct context and that the variable is correctly described.
|
| 228/6 |
2026/05/10 03:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/loop.c IncludeLines:true Name:loop_set_size]
Results: map[SourceCode: 210: /**
211: * loop_set_size() - sets device size and notifies userspace
212: * @lo: struct loop_device to set the size for
213: * @size: new size of the loop device
214: *
215: * Callers must validate that the size passed into this function fits into
216: * a sector_t, eg using loop_validate_size()
217: */
218: static void loop_set_size(struct loop_device *lo, loff_t size)
219: {
220: if (!set_capacity_and_notify(lo->lo_disk, size))
221: kobject_uevent(&disk_to_dev(lo->lo_disk)->kobj, KOBJ_CHANGE);
222: }
SourceFile:drivers/block/loop.c]
|
| 229/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18672
output: 20
thoughts: 535
Thoughts: **Analyzing Block Size and Capacity Changes in NBD and Loop Devices**
Okay, so I'm trying to understand why `loop_set_capacity` doesn't use `bd_prepare_to_claim`, but `loop_set_block_size` does, and why the NBD code might need it. My initial thought is that changing the block size is potentially more disruptive than just changing the capacity. I mean, block size changes could necessitate cache invalidation, right? Let's refresh our memory of the loop device code. Ah yes, line 1474 and 1475 in `loop_set_block_size` show that it does indeed call `sync_blockdev` and `invalidate_bdev`.
Now, looking at the NBD side, `nbd_set_size` is also changing the `blksize`. That raises a flag. If it's modifying the block size, it probably needs that "claim" mechanism to prevent concurrent modification issues.
The question then becomes about the specific call `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`. I see a potential issue: what if `nbd->disk->part0` is null if `nbd->disk` is null? But wait, I recall there's a check for `nbd->pid` in `nbd_set_size`. Let's confirm... Ah, there it is: `if (!nbd->pid) return 0;`. However, that check is about connection status, not whether the disk is setup. I should go back and re-read the code to make sure I understand the setup.
Right, `nbd_set_size` checks if the device is connected using `nbd->pid`. If it's not connected, it just sets `nbd->config->bytesize`. In this case, the `nbd->disk` may not even be fully initialized. But wait... `nbd_dev_add` sets up the `nbd->disk` before it's used.
Okay, so if `nbd->disk` is non-NULL, then `nbd->disk->part0` is *always* there. In recent kernels, `part0` is a field in the `struct gendisk` itself. We should go back and double-check the `struct gendisk` definition to be sure.
|
| 230/6 |
2026/05/10 03:25 |
tool |
codesearch-struct-layout |
0m
Args:
Results: map[Fields:[map[Name:major OffsetBits:0 SizeBits:32] map[Name:first_minor OffsetBits:32 SizeBits:32] map[Name:minors OffsetBits:64 SizeBits:32] map[Name:disk_name OffsetBits:96 SizeBits:256] map[Name:events OffsetBits:352 SizeBits:16] map[Name:event_flags OffsetBits:368 SizeBits:16] map[Name:part_tbl OffsetBits:384 SizeBits:640] map[Name:part0 OffsetBits:1024 SizeBits:64] map[Name:fops OffsetBits:1088 SizeBits:64] map[Name:queue OffsetBits:1152 SizeBits:64] map[Name:private_data OffsetBits:1216 SizeBits:64] map[Name:bio_split OffsetBits:1280 SizeBits:4608] map[Name:flags OffsetBits:5888 SizeBits:32] map[Name:state OffsetBits:5952 SizeBits:64] map[Name:open_mutex OffsetBits:6016 SizeBits:1088] map[Name:open_partitions OffsetBits:7104 SizeBits:32] map[Name:bdi OffsetBits:7168 SizeBits:64] map[Name:queue_kobj OffsetBits:7232 SizeBits:512] map[Name:slave_dir OffsetBits:7744 SizeBits:64] map[Name:slave_bdevs OffsetBits:7808 SizeBits:128] map[Name:random OffsetBits:7936 SizeBits:64] map[Name:ev OffsetBits:8000 SizeBits:64] map[Name:nr_zones OffsetBits:8064 SizeBits:32] map[Name:zone_capacity OffsetBits:8096 SizeBits:32] map[Name:last_zone_capacity OffsetBits:8128 SizeBits:32] map[Name:zones_cond OffsetBits:8192 SizeBits:64] map[Name:zone_wplugs_hash_bits OffsetBits:8256 SizeBits:32] map[Name:nr_zone_wplugs OffsetBits:8288 SizeBits:32] map[Name:zone_wplugs_hash_lock OffsetBits:8320 SizeBits:512] map[Name:zone_wplugs_pool OffsetBits:8832 SizeBits:64] map[Name:zone_wplugs_hash OffsetBits:8896 SizeBits:64] map[Name:zone_wplugs_wq OffsetBits:8960 SizeBits:64] map[Name:zone_wplugs_list_lock OffsetBits:9024 SizeBits:512] map[Name:zone_wplugs_list OffsetBits:9536 SizeBits:128] map[Name:zone_wplugs_worker OffsetBits:9664 SizeBits:64] map[Name:zone_wplugs_worker_bio_done OffsetBits:9728 SizeBits:704] map[Name:cdi OffsetBits:10432 SizeBits:64] map[Name:node_id OffsetBits:10496 SizeBits:32] map[Name:bb OffsetBits:10560 SizeBits:64] map[Name:lockdep_map OffsetBits:10624 SizeBits:320] map[Name:diskseq OffsetBits:10944 SizeBits:64] map[Name:open_mode OffsetBits:11008 SizeBits:32] map[Name:ia_ranges OffsetBits:11072 SizeBits:64] map[Name:rqos_state_mutex OffsetBits:11136 SizeBits:1088]]]
|
| 231/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 20775
output: 23
thoughts: 28
Thoughts: Here's my thought process, summarized as you requested:
**Deconstructing a Data Structure Pointer**
Okay, so I'm looking at this code and I see `part0`. Hmm, it's assigned something that looks like it *should* be a pointer. But to what? Let's verify. Based on context, my intuition says it might be a `struct block_device *`. *Definitely* need to make sure though. Gotta check the definition or declaration of `part0` to confirm that it's indeed a `block_device` pointer.
|
| 232/6 |
2026/05/10 03:25 |
tool |
read-file |
0m
Error:
Args: map[File:include/linux/genhd.h]
Results:
|
| 233/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 20964
output: 23
thoughts: 11
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Diving into the Block Device Header**
Right, so I need to dig into the kernel's block device structure, and my first instinct is to go straight to the source. Let's see... `include/linux/blkdev.h`. That's the logical starting point. It's the central header file that defines the core data structures and likely the fundamental functions related to block device operations. Everything from the `gendisk` structure to queue management and request handling probably starts there. It will be the place to get a foundational understanding. No need to waste time searching – that's where I'll find the building blocks. Let's get to it.
|
| 234/6 |
2026/05/10 03:25 |
tool |
read-file |
0m
Args: map[File:include/linux/blkdev.h]
Results: map[Contents:/* SPDX-License-Identifier: GPL-2.0 */
/*
* Portions Copyright (C) 1992 Drew Eckhardt
*/
#ifndef _LINUX_BLKDEV_H
#define _LINUX_BLKDEV_H
#include <linux/types.h>
#include <linux/blk_types.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/llist.h>
#include <linux/minmax.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <linux/completion.h>
#include <linux/wait.h>
#include <linux/bio.h>
#include <linux/gfp.h>
#include <linux/kdev_t.h>
#include <linux/rcupdate.h>
#include <linux/percpu-refcount.h>
#include <linux/blkzoned.h>
#include <linux/sched.h>
#include <linux/sbitmap.h>
#include <linux/uuid.h>
#include <linux/xarray.h>
#include <linux/file.h>
#include <linux/lockdep.h>
struct module;
struct request_queue;
struct elevator_queue;
struct blk_trace;
struct request;
struct sg_io_hdr;
struct blkcg_gq;
struct blk_flush_queue;
struct kiocb;
struct pr_ops;
struct rq_qos;
struct hd_geometry;
struct blk_report_zones_args;
struct blk_queue_stats;
struct blk_stat_callback;
struct blk_crypto_profile;
extern const struct device_type disk_type;
extern const struct device_type part_type;
extern const struct class block_class;
/*
* Maximum number of blkcg policies allowed to be registered concurrently.
* Defined here to simplify include dependency.
*/
#define BLKCG_MAX_POLS 6
#define DISK_MAX_PARTS 256
#define DISK_NAME_LEN 32
#define PARTITION_META_INFO_VOLNAMELTH 64
/*
* Enough for the string representation of any kind of UUID plus NULL.
* EFI UUID is 36 characters. MSDOS UUID is 11 characters.
*/
#define PARTITION_META_INFO_UUIDLTH (UUID_STRING_LEN + 1)
struct partition_meta_info {
char uuid[PARTITION_META_INFO_UUIDLTH];
u8 volname[PARTITION_META_INFO_VOLNAMELTH];
};
/**
* DOC: genhd capability flags
*
* ``GENHD_FL_REMOVABLE``: indicates that the block device gives access to
* removable media. When set, the device remains present even when media is not
* inserted. Shall not be set for devices which are removed entirely when the
* media is removed.
*
* ``GENHD_FL_HIDDEN``: the block device is hidden; it doesn't produce events,
* doesn't appear in sysfs, and can't be opened from userspace or using
* blkdev_get*. Used for the underlying components of multipath devices.
*
* ``GENHD_FL_NO_PART``: partition support is disabled. The kernel will not
* scan for partitions from add_disk, and users can't add partitions manually.
*
*/
enum {
GENHD_FL_REMOVABLE = 1 << 0,
GENHD_FL_HIDDEN = 1 << 1,
GENHD_FL_NO_PART = 1 << 2,
};
enum {
DISK_EVENT_MEDIA_CHANGE = 1 << 0, /* media changed */
DISK_EVENT_EJECT_REQUEST = 1 << 1, /* eject requested */
};
enum {
/* Poll even if events_poll_msecs is unset */
DISK_EVENT_FLAG_POLL = 1 << 0,
/* Forward events to udev */
DISK_EVENT_FLAG_UEVENT = 1 << 1,
/* Block event polling when open for exclusive write */
DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE = 1 << 2,
};
struct disk_events;
struct badblocks;
enum blk_integrity_checksum {
BLK_INTEGRITY_CSUM_NONE = 0,
BLK_INTEGRITY_CSUM_IP = 1,
BLK_INTEGRITY_CSUM_CRC = 2,
BLK_INTEGRITY_CSUM_CRC64 = 3,
} __packed ;
struct blk_integrity {
unsigned char flags;
enum blk_integrity_checksum csum_type;
unsigned char metadata_size;
unsigned char pi_offset;
unsigned char interval_exp;
unsigned char tag_size;
unsigned char pi_tuple_size;
};
typedef unsigned int __bitwise blk_mode_t;
/* open for reading */
#define BLK_OPEN_READ ((__force blk_mode_t)(1 << 0))
/* open for writing */
#define BLK_OPEN_WRITE ((__force blk_mode_t)(1 << 1))
/* open exclusively (vs other exclusive openers */
#define BLK_OPEN_EXCL ((__force blk_mode_t)(1 << 2))
/* opened with O_NDELAY */
#define BLK_OPEN_NDELAY ((__force blk_mode_t)(1 << 3))
/* open for "writes" only for ioctls (specialy hack for floppy.c) */
#define BLK_OPEN_WRITE_IOCTL ((__force blk_mode_t)(1 << 4))
/* open is exclusive wrt all other BLK_OPEN_WRITE opens to the device */
#define BLK_OPEN_RESTRICT_WRITES ((__force blk_mode_t)(1 << 5))
/* return partition scanning errors */
#define BLK_OPEN_STRICT_SCAN ((__force blk_mode_t)(1 << 6))
struct gendisk {
/*
* major/first_minor/minors should not be set by any new driver, the
* block core will take care of allocating them automatically.
*/
int major;
int first_minor;
int minors;
char disk_name[DISK_NAME_LEN]; /* name of major driver */
unsigned short events; /* supported events */
unsigned short event_flags; /* flags related to event processing */
struct xarray part_tbl;
struct block_device *part0;
const struct block_device_operations *fops;
struct request_queue *queue;
void *private_data;
struct bio_set bio_split;
int flags;
unsigned long state;
#define GD_NEED_PART_SCAN 0
#define GD_READ_ONLY 1
#define GD_DEAD 2
#define GD_NATIVE_CAPACITY 3
#define GD_ADDED 4
#define GD_SUPPRESS_PART_SCAN 5
#define GD_OWNS_QUEUE 6
#define GD_ZONE_APPEND_USED 7
struct mutex open_mutex; /* open/close mutex */
unsigned open_partitions; /* number of open partitions */
struct backing_dev_info *bdi;
struct kobject queue_kobj; /* the queue/ directory */
struct kobject *slave_dir;
#ifdef CONFIG_BLOCK_HOLDER_DEPRECATED
struct list_head slave_bdevs;
#endif
struct timer_rand_state *random;
struct disk_events *ev;
#ifdef CONFIG_BLK_DEV_ZONED
/*
* Zoned block device information. Reads of this information must be
* protected with blk_queue_enter() / blk_queue_exit(). Modifying this
* information is only allowed while no requests are being processed.
* See also blk_mq_freeze_queue() and blk_mq_unfreeze_queue().
*/
unsigned int nr_zones;
unsigned int zone_capacity;
unsigned int last_zone_capacity;
u8 __rcu *zones_cond;
unsigned int zone_wplugs_hash_bits;
atomic_t nr_zone_wplugs;
spinlock_t zone_wplugs_hash_lock;
struct mempool *zone_wplugs_pool;
struct hlist_head *zone_wplugs_hash;
struct workqueue_struct *zone_wplugs_wq;
spinlock_t zone_wplugs_list_lock;
struct list_head zone_wplugs_list;
struct task_struct *zone_wplugs_worker;
struct completion zone_wplugs_worker_bio_done;
#endif /* CONFIG_BLK_DEV_ZONED */
#if IS_ENABLED(CONFIG_CDROM)
struct cdrom_device_info *cdi;
#endif
int node_id;
struct badblocks *bb;
struct lockdep_map lockdep_map;
u64 diskseq;
blk_mode_t open_mode;
/*
* Independent sector access ranges. This is always NULL for
* devices that do not have multiple independent access ranges.
*/
struct blk_independent_access_ranges *ia_ranges;
struct mutex rqos_state_mutex; /* rqos state change mutex */
};
/**
* disk_openers - returns how many openers are there for a disk
* @disk: disk to check
*
* This returns the number of openers for a disk. Note that this value is only
* stable if disk->open_mutex is held.
*
* Note: Due to a quirk in the block layer open code, each open partition is
* only counted once even if there are multiple openers.
*/
static inline unsigned int disk_openers(struct gendisk *disk)
{
return atomic_read(&disk->part0->bd_openers);
}
/**
* disk_has_partscan - return %true if partition scanning is enabled on a disk
* @disk: disk to check
*
* Returns %true if partitions scanning is enabled for @disk, or %false if
* partition scanning is disabled either permanently or temporarily.
*/
static inline bool disk_has_partscan(struct gendisk *disk)
{
return !(disk->flags & (GENHD_FL_NO_PART | GENHD_FL_HIDDEN)) &&
!test_bit(GD_SUPPRESS_PART_SCAN, &disk->state);
}
/*
* The gendisk is refcounted by the part0 block_device, and the bd_device
* therein is also used for device model presentation in sysfs.
*/
#define dev_to_disk(device) \
(dev_to_bdev(device)->bd_disk)
#define disk_to_dev(disk) \
(&((disk)->part0->bd_device))
#if IS_REACHABLE(CONFIG_CDROM)
#define disk_to_cdi(disk) ((disk)->cdi)
#else
#define disk_to_cdi(disk) NULL
#endif
static inline dev_t disk_devt(struct gendisk *disk)
{
return MKDEV(disk->major, disk->first_minor);
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
/*
* We should strive for 1 << (PAGE_SHIFT + MAX_PAGECACHE_ORDER)
* however we constrain this to what we can validate and test.
*/
#define BLK_MAX_BLOCK_SIZE SZ_64K
#else
#define BLK_MAX_BLOCK_SIZE PAGE_SIZE
#endif
/* blk_validate_limits() validates bsize, so drivers don't usually need to */
static inline int blk_validate_block_size(unsigned long bsize)
{
if (bsize < 512 || bsize > BLK_MAX_BLOCK_SIZE || !is_power_of_2(bsize))
return -EINVAL;
return 0;
}
static inline bool blk_op_is_passthrough(blk_opf_t op)
{
op &= REQ_OP_MASK;
return op == REQ_OP_DRV_IN || op == REQ_OP_DRV_OUT;
}
/* flags set by the driver in queue_limits.features */
typedef unsigned int __bitwise blk_features_t;
/* supports a volatile write cache */
#define BLK_FEAT_WRITE_CACHE ((__force blk_features_t)(1u << 0))
/* supports passing on the FUA bit */
#define BLK_FEAT_FUA ((__force blk_features_t)(1u << 1))
/* rotational device (hard drive or floppy) */
#define BLK_FEAT_ROTATIONAL ((__force blk_features_t)(1u << 2))
/* contributes to the random number pool */
#define BLK_FEAT_ADD_RANDOM ((__force blk_features_t)(1u << 3))
/* do disk/partitions IO accounting */
#define BLK_FEAT_IO_STAT ((__force blk_features_t)(1u << 4))
/* don't modify data until writeback is done */
#define BLK_FEAT_STABLE_WRITES ((__force blk_features_t)(1u << 5))
/* always completes in submit context */
#define BLK_FEAT_SYNCHRONOUS ((__force blk_features_t)(1u << 6))
/* supports REQ_NOWAIT */
#define BLK_FEAT_NOWAIT ((__force blk_features_t)(1u << 7))
/* supports DAX */
#define BLK_FEAT_DAX ((__force blk_features_t)(1u << 8))
/* supports I/O polling */
#define BLK_FEAT_POLL ((__force blk_features_t)(1u << 9))
/* is a zoned device */
#define BLK_FEAT_ZONED ((__force blk_features_t)(1u << 10))
/* supports PCI(e) p2p requests */
#define BLK_FEAT_PCI_P2PDMA ((__force blk_features_t)(1u << 12))
/* skip this queue in blk_mq_(un)quiesce_tagset */
#define BLK_FEAT_SKIP_TAGSET_QUIESCE ((__force blk_features_t)(1u << 13))
/* atomic writes enabled */
#define BLK_FEAT_ATOMIC_WRITES ((__force blk_features_t)(1u << 14))
/* undocumented magic for bcache */
#define BLK_FEAT_RAID_PARTIAL_STRIPES_EXPENSIVE \
((__force blk_features_t)(1u << 15))
/*
* Flags automatically inherited when stacking limits.
*/
#define BLK_FEAT_INHERIT_MASK \
(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA | BLK_FEAT_ROTATIONAL | \
BLK_FEAT_STABLE_WRITES | BLK_FEAT_ZONED | \
BLK_FEAT_RAID_PARTIAL_STRIPES_EXPENSIVE)
/* internal flags in queue_limits.flags */
typedef unsigned int __bitwise blk_flags_t;
/* do not send FLUSH/FUA commands despite advertising a write cache */
#define BLK_FLAG_WRITE_CACHE_DISABLED ((__force blk_flags_t)(1u << 0))
/* I/O topology is misaligned */
#define BLK_FLAG_MISALIGNED ((__force blk_flags_t)(1u << 1))
/* passthrough command IO accounting */
#define BLK_FLAG_IOSTATS_PASSTHROUGH ((__force blk_flags_t)(1u << 2))
struct queue_limits {
blk_features_t features;
blk_flags_t flags;
unsigned long seg_boundary_mask;
unsigned long virt_boundary_mask;
unsigned int max_hw_sectors;
unsigned int max_dev_sectors;
unsigned int chunk_sectors;
unsigned int max_sectors;
unsigned int max_user_sectors;
unsigned int max_segment_size;
unsigned int max_fast_segment_size;
unsigned int physical_block_size;
unsigned int logical_block_size;
unsigned int alignment_offset;
unsigned int io_min;
unsigned int io_opt;
unsigned int max_discard_sectors;
unsigned int max_hw_discard_sectors;
unsigned int max_user_discard_sectors;
unsigned int max_secure_erase_sectors;
unsigned int max_write_zeroes_sectors;
unsigned int max_wzeroes_unmap_sectors;
unsigned int max_hw_wzeroes_unmap_sectors;
unsigned int max_user_wzeroes_unmap_sectors;
unsigned int max_hw_zone_append_sectors;
unsigned int max_zone_append_sectors;
unsigned int discard_granularity;
unsigned int discard_alignment;
unsigned int zone_write_granularity;
/* atomic write limits */
unsigned int atomic_write_hw_max;
unsigned int atomic_write_max_sectors;
unsigned int atomic_write_hw_boundary;
unsigned int atomic_write_boundary_sectors;
unsigned int atomic_write_hw_unit_min;
unsigned int atomic_write_unit_min;
unsigned int atomic_write_hw_unit_max;
unsigned int atomic_write_unit_max;
unsigned short max_segments;
unsigned short max_integrity_segments;
unsigned short max_discard_segments;
unsigned short max_write_streams;
unsigned int write_stream_granularity;
unsigned int max_open_zones;
unsigned int max_active_zones;
/*
* Drivers that set dma_alignment to less than 511 must be prepared to
* handle individual bvec's that are not a multiple of a SECTOR_SIZE
* due to possible offsets.
*/
unsigned int dma_alignment;
unsigned int dma_pad_mask;
struct blk_integrity integrity;
};
typedef int (*report_zones_cb)(struct blk_zone *zone, unsigned int idx,
void *data);
int disk_report_zone(struct gendisk *disk, struct blk_zone *zone,
unsigned int idx, struct blk_report_zones_args *args);
int blkdev_get_zone_info(struct block_device *bdev, sector_t sector,
struct blk_zone *zone);
#define BLK_ALL_ZONES ((unsigned int)-1)
int blkdev_report_zones(struct block_device *bdev, sector_t sector,
unsigned int nr_zones, report_zones_cb cb, void *data);
int blkdev_report_zones_cached(struct block_device *bdev, sector_t sector,
unsigned int nr_zones, report_zones_cb cb, void *data);
int blkdev_zone_mgmt(struct block_device *bdev, enum req_op op,
sector_t sectors, sector_t nr_sectors);
int blk_revalidate_disk_zones(struct gendisk *disk);
/*
* Independent access ranges: struct blk_independent_access_range describes
* a range of contiguous sectors that can be accessed using device command
* execution resources that are independent from the resources used for
* other access ranges. This is typically found with single-LUN multi-actuator
* HDDs where each access range is served by a different set of heads.
* The set of independent ranges supported by the device is defined using
* struct blk_independent_access_ranges. The independent ranges must not overlap
* and must include all sectors within the disk capacity (no sector holes
* allowed).
* For a device with multiple ranges, requests targeting sectors in different
* ranges can be executed in parallel. A request can straddle an access range
* boundary.
*/
struct blk_independent_access_range {
struct kobject kobj;
sector_t sector;
sector_t nr_sectors;
};
struct blk_independent_access_ranges {
struct kobject kobj;
bool sysfs_registered;
unsigned int nr_ia_ranges;
struct blk_independent_access_range ia_range[];
};
struct request_queue {
/*
* The queue owner gets to use this for whatever they like.
* ll_rw_blk doesn't touch it.
*/
void *queuedata;
struct elevator_queue *elevator;
const struct blk_mq_ops *mq_ops;
/* sw queues */
struct blk_mq_ctx __percpu *queue_ctx;
/*
* various queue flags, see QUEUE_* below
*/
unsigned long queue_flags;
unsigned int __data_racy rq_timeout;
unsigned int queue_depth;
refcount_t refs;
/* hw dispatch queues */
unsigned int nr_hw_queues;
struct blk_mq_hw_ctx * __rcu *queue_hw_ctx __counted_by_ptr(nr_hw_queues);
struct percpu_ref q_usage_counter;
struct lock_class_key io_lock_cls_key;
struct lockdep_map io_lockdep_map;
struct lock_class_key q_lock_cls_key;
struct lockdep_map q_lockdep_map;
struct request *last_merge;
spinlock_t queue_lock;
int quiesce_depth;
struct gendisk *disk;
/*
* mq queue kobject
*/
struct kobject *mq_kobj;
struct queue_limits limits;
#ifdef CONFIG_PM
struct device *dev;
enum rpm_status rpm_status;
#endif
/*
* Number of contexts that have called blk_set_pm_only(). If this
* counter is above zero then only RQF_PM requests are processed.
*/
atomic_t pm_only;
struct blk_queue_stats *stats;
struct rq_qos *rq_qos;
struct mutex rq_qos_mutex;
/*
* ida allocated id for this queue. Used to index queues from
* ioctx.
*/
int id;
/*
* queue settings
*/
unsigned int nr_requests; /* Max # of requests */
unsigned int async_depth; /* Max # of async requests */
#ifdef CONFIG_BLK_INLINE_ENCRYPTION
struct blk_crypto_profile *crypto_profile;
struct kobject *crypto_kobject;
#endif
struct timer_list timeout;
struct work_struct timeout_work;
atomic_t nr_active_requests_shared_tags;
struct blk_mq_tags *sched_shared_tags;
struct list_head icq_list;
#ifdef CONFIG_BLK_CGROUP
DECLARE_BITMAP (blkcg_pols, BLKCG_MAX_POLS);
struct blkcg_gq *root_blkg;
struct list_head blkg_list;
struct mutex blkcg_mutex;
#endif
int node;
spinlock_t requeue_lock;
struct list_head requeue_list;
struct delayed_work requeue_work;
#ifdef CONFIG_BLK_DEV_IO_TRACE
struct blk_trace __rcu *blk_trace;
#endif
/*
* for flush operations
*/
struct blk_flush_queue *fq;
struct list_head flush_list;
/*
* Protects against I/O scheduler switching, particularly when updating
* q->elevator. Since the elevator update code path may also modify q->
* nr_requests and wbt latency, this lock also protects the sysfs attrs
* nr_requests and wbt_lat_usec. Additionally the nr_hw_queues update
* may modify hctx tags, reserved-tags and cpumask, so this lock also
* helps protect the hctx sysfs/debugfs attrs. To ensure proper locking
* order during an elevator or nr_hw_queue update, first freeze the
* queue, then acquire ->elevator_lock.
*/
struct mutex elevator_lock;
struct mutex sysfs_lock;
/*
* Protects queue limits and also sysfs attribute read_ahead_kb.
*/
struct mutex limits_lock;
/*
* for reusing dead hctx instance in case of updating
* nr_hw_queues
*/
struct list_head unused_hctx_list;
spinlock_t unused_hctx_lock;
int mq_freeze_depth;
#ifdef CONFIG_BLK_DEV_THROTTLING
/* Throttle data */
struct throtl_data *td;
#endif
struct rcu_head rcu_head;
#ifdef CONFIG_LOCKDEP
struct task_struct *mq_freeze_owner;
int mq_freeze_owner_depth;
/*
* Records disk & queue state in current context, used in unfreeze
* queue
*/
bool mq_freeze_disk_dead;
bool mq_freeze_queue_dying;
#endif
wait_queue_head_t mq_freeze_wq;
/*
* Protect concurrent access to q_usage_counter by
* percpu_ref_kill() and percpu_ref_reinit().
*/
struct mutex mq_freeze_lock;
struct blk_mq_tag_set *tag_set;
struct list_head tag_set_list;
struct dentry *debugfs_dir;
struct dentry *sched_debugfs_dir;
struct dentry *rqos_debugfs_dir;
/*
* Serializes all debugfs metadata operations using the above dentries.
*/
struct mutex debugfs_mutex;
};
/* Keep blk_queue_flag_name[] in sync with the definitions below */
enum {
QUEUE_FLAG_DYING, /* queue being torn down */
QUEUE_FLAG_NOMERGES, /* disable merge attempts */
QUEUE_FLAG_SAME_COMP, /* complete on same CPU-group */
QUEUE_FLAG_FAIL_IO, /* fake timeout */
QUEUE_FLAG_NOXMERGES, /* No extended merges */
QUEUE_FLAG_SAME_FORCE, /* force complete on same CPU */
QUEUE_FLAG_INIT_DONE, /* queue is initialized */
QUEUE_FLAG_STATS, /* track IO start and completion times */
QUEUE_FLAG_REGISTERED, /* queue has been registered to a disk */
QUEUE_FLAG_QUIESCED, /* queue has been quiesced */
QUEUE_FLAG_RQ_ALLOC_TIME, /* record rq->alloc_time_ns */
QUEUE_FLAG_HCTX_ACTIVE, /* at least one blk-mq hctx is active */
QUEUE_FLAG_SQ_SCHED, /* single queue style io dispatch */
QUEUE_FLAG_DISABLE_WBT_DEF, /* for sched to disable/enable wbt */
QUEUE_FLAG_NO_ELV_SWITCH, /* can't switch elevator any more */
QUEUE_FLAG_QOS_ENABLED, /* qos is enabled */
QUEUE_FLAG_BIO_ISSUE_TIME, /* record bio->issue_time_ns */
QUEUE_FLAG_ZONED_QD1_WRITES, /* Limit zoned devices writes to QD=1 */
QUEUE_FLAG_MAX
};
#define QUEUE_FLAG_MQ_DEFAULT (1UL << QUEUE_FLAG_SAME_COMP)
void blk_queue_flag_set(unsigned int flag, struct request_queue *q);
void blk_queue_flag_clear(unsigned int flag, struct request_queue *q);
#define blk_queue_dying(q) test_bit(QUEUE_FLAG_DYING, &(q)->queue_flags)
#define blk_queue_init_done(q) test_bit(QUEUE_FLAG_INIT_DONE, &(q)->queue_flags)
#define blk_queue_nomerges(q) test_bit(QUEUE_FLAG_NOMERGES, &(q)->queue_flags)
#define blk_queue_noxmerges(q) \
test_bit(QUEUE_FLAG_NOXMERGES, &(q)->queue_flags)
#define blk_queue_rot(q) ((q)->limits.features & BLK_FEAT_ROTATIONAL)
#define blk_queue_io_stat(q) ((q)->limits.features & BLK_FEAT_IO_STAT)
#define blk_queue_passthrough_stat(q) \
((q)->limits.flags & BLK_FLAG_IOSTATS_PASSTHROUGH)
#define blk_queue_dax(q) ((q)->limits.features & BLK_FEAT_DAX)
#define blk_queue_pci_p2pdma(q) ((q)->limits.features & BLK_FEAT_PCI_P2PDMA)
#ifdef CONFIG_BLK_RQ_ALLOC_TIME
#define blk_queue_rq_alloc_time(q) \
test_bit(QUEUE_FLAG_RQ_ALLOC_TIME, &(q)->queue_flags)
#else
#define blk_queue_rq_alloc_time(q) false
#endif
#define blk_noretry_request(rq) \
((rq)->cmd_flags & (REQ_FAILFAST_DEV|REQ_FAILFAST_TRANSPORT| \
REQ_FAILFAST_DRIVER))
#define blk_queue_quiesced(q) test_bit(QUEUE_FLAG_QUIESCED, &(q)->queue_flags)
#define blk_queue_pm_only(q) atomic_read(&(q)->pm_only)
#define blk_queue_registered(q) test_bit(QUEUE_FLAG_REGISTERED, &(q)->queue_flags)
#define blk_queue_sq_sched(q) test_bit(QUEUE_FLAG_SQ_SCHED, &(q)->queue_flags)
#define blk_queue_skip_tagset_quiesce(q) \
((q)->limits.features & BLK_FEAT_SKIP_TAGSET_QUIESCE)
#define blk_queue_disable_wbt(q) \
test_bit(QUEUE_FLAG_DISABLE_WBT_DEF, &(q)->queue_flags)
#define blk_queue_no_elv_switch(q) \
test_bit(QUEUE_FLAG_NO_ELV_SWITCH, &(q)->queue_flags)
#define blk_queue_zoned_qd1_writes(q) \
test_bit(QUEUE_FLAG_ZONED_QD1_WRITES, &(q)->queue_flags)
extern void blk_set_pm_only(struct request_queue *q);
extern void blk_clear_pm_only(struct request_queue *q);
#define list_entry_rq(ptr) list_entry((ptr), struct request, queuelist)
#define dma_map_bvec(dev, bv, dir, attrs) \
dma_map_page_attrs(dev, (bv)->bv_page, (bv)->bv_offset, (bv)->bv_len, \
(dir), (attrs))
static inline bool queue_is_mq(struct request_queue *q)
{
return q->mq_ops;
}
#ifdef CONFIG_PM
static inline enum rpm_status queue_rpm_status(struct request_queue *q)
{
return q->rpm_status;
}
#else
static inline enum rpm_status queue_rpm_status(struct request_queue *q)
{
return RPM_ACTIVE;
}
#endif
static inline bool blk_queue_is_zoned(struct request_queue *q)
{
return IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
(q->limits.features & BLK_FEAT_ZONED);
}
static inline unsigned int disk_zone_no(struct gendisk *disk, sector_t sector)
{
if (!blk_queue_is_zoned(disk->queue))
return 0;
return sector >> ilog2(disk->queue->limits.chunk_sectors);
}
static inline unsigned int bdev_max_open_zones(struct block_device *bdev)
{
return bdev->bd_disk->queue->limits.max_open_zones;
}
static inline unsigned int bdev_max_active_zones(struct block_device *bdev)
{
return bdev->bd_disk->queue->limits.max_active_zones;
}
static inline unsigned int blk_queue_depth(struct request_queue *q)
{
if (q->queue_depth)
return q->queue_depth;
return q->nr_requests;
}
/*
* default timeout for SG_IO if none specified
*/
#define BLK_DEFAULT_SG_TIMEOUT (60 * HZ)
#define BLK_MIN_SG_TIMEOUT (7 * HZ)
/* This should not be used directly - use rq_for_each_segment */
#define for_each_bio(_bio) \
for (; _bio; _bio = _bio->bi_next)
int __must_check add_disk_fwnode(struct device *parent, struct gendisk *disk,
const struct attribute_group **groups,
struct fwnode_handle *fwnode);
int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
const struct attribute_group **groups);
static inline int __must_check add_disk(struct gendisk *disk)
{
return device_add_disk(NULL, disk, NULL);
}
void del_gendisk(struct gendisk *gp);
void invalidate_disk(struct gendisk *disk);
void set_disk_ro(struct gendisk *disk, bool read_only);
void disk_uevent(struct gendisk *disk, enum kobject_action action);
static inline u8 bdev_partno(const struct block_device *bdev)
{
return atomic_read(&bdev->__bd_flags) & BD_PARTNO;
}
static inline bool bdev_test_flag(const struct block_device *bdev, unsigned flag)
{
return atomic_read(&bdev->__bd_flags) & flag;
}
static inline void bdev_set_flag(struct block_device *bdev, unsigned flag)
{
atomic_or(flag, &bdev->__bd_flags);
}
static inline void bdev_clear_flag(struct block_device *bdev, unsigned flag)
{
atomic_andnot(flag, &bdev->__bd_flags);
}
static inline bool get_disk_ro(struct gendisk *disk)
{
return bdev_test_flag(disk->part0, BD_READ_ONLY) ||
test_bit(GD_READ_ONLY, &disk->state);
}
static inline bool bdev_read_only(struct block_device *bdev)
{
return bdev_test_flag(bdev, BD_READ_ONLY) || get_disk_ro(bdev->bd_disk);
}
bool set_capacity_and_notify(struct gendisk *disk, sector_t size);
void disk_force_media_change(struct gendisk *disk);
void bdev_mark_dead(struct block_device *bdev, bool surprise);
void add_disk_randomness(struct gendisk *disk) __latent_entropy;
void rand_initialize_disk(struct gendisk *disk);
static inline sector_t get_start_sect(struct block_device *bdev)
{
return bdev->bd_start_sect;
}
static inline sector_t bdev_nr_sectors(struct block_device *bdev)
{
return bdev->bd_nr_sectors;
}
static inline loff_t bdev_nr_bytes(struct block_device *bdev)
{
return (loff_t)bdev_nr_sectors(bdev) << SECTOR_SHIFT;
}
static inline sector_t get_capacity(struct gendisk *disk)
{
return bdev_nr_sectors(disk->part0);
}
static inline u64 sb_bdev_nr_blocks(struct super_block *sb)
{
return bdev_nr_sectors(sb->s_bdev) >>
(sb->s_blocksize_bits - SECTOR_SHIFT);
}
#ifdef CONFIG_BLK_DEV_ZONED
static inline unsigned int disk_nr_zones(struct gendisk *disk)
{
return disk->nr_zones;
}
/**
* bio_needs_zone_write_plugging - Check if a BIO needs to be handled with zone
* write plugging
* @bio: The BIO being submitted
*
* Return true whenever @bio execution needs to be handled through zone
* write plugging (using blk_zone_plug_bio()). Return false otherwise.
*/
static inline bool bio_needs_zone_write_plugging(struct bio *bio)
{
enum req_op op = bio_op(bio);
/*
* Only zoned block devices have a zone write plug hash table. But not
* all of them have one (e.g. DM devices may not need one).
*/
if (!bio->bi_bdev->bd_disk->zone_wplugs_hash)
return false;
/* Only write operations need zone write plugging. */
if (!op_is_write(op))
return false;
/* Ignore empty flush */
if (op_is_flush(bio->bi_opf) && !bio_sectors(bio))
return false;
/* Ignore BIOs that already have been handled by zone write plugging. */
if (bio_flagged(bio, BIO_ZONE_WRITE_PLUGGING))
return false;
/*
* All zone write operations must be handled through zone write plugging
* using blk_zone_plug_bio().
*/
switch (op) {
case REQ_OP_ZONE_APPEND:
case REQ_OP_WRITE:
case REQ_OP_WRITE_ZEROES:
case REQ_OP_ZONE_FINISH:
case REQ_OP_ZONE_RESET:
case REQ_OP_ZONE_RESET_ALL:
return true;
default:
return false;
}
}
bool blk_zone_plug_bio(struct bio *bio, unsigned int nr_segs);
/**
* disk_zone_capacity - returns the zone capacity of zone containing @sector
* @disk: disk to work with
* @sector: sector number within the querying zone
*
* Returns the zone capacity of a zone containing @sector. @sector can be any
* sector in the zone.
*/
static inline unsigned int disk_zone_capacity(struct gendisk *disk,
sector_t sector)
{
sector_t zone_sectors = disk->queue->limits.chunk_sectors;
if (sector + zone_sectors >= get_capacity(disk))
return disk->last_zone_capacity;
return disk->zone_capacity;
}
static inline unsigned int bdev_zone_capacity(struct block_device *bdev,
sector_t pos)
{
return disk_zone_capacity(bdev->bd_disk, pos);
}
bool bdev_zone_is_seq(struct block_device *bdev, sector_t sector);
#else /* CONFIG_BLK_DEV_ZONED */
static inline unsigned int disk_nr_zones(struct gendisk *disk)
{
return 0;
}
static inline bool bdev_zone_is_seq(struct block_device *bdev, sector_t sector)
{
return false;
}
static inline bool bio_needs_zone_write_plugging(struct bio *bio)
{
return false;
}
static inline bool blk_zone_plug_bio(struct bio *bio, unsigned int nr_segs)
{
return false;
}
#endif /* CONFIG_BLK_DEV_ZONED */
static inline unsigned int bdev_nr_zones(struct block_device *bdev)
{
return disk_nr_zones(bdev->bd_disk);
}
int bdev_disk_changed(struct gendisk *disk, bool invalidate);
void put_disk(struct gendisk *disk);
struct gendisk *__blk_alloc_disk(struct queue_limits *lim, int node,
struct lock_class_key *lkclass);
/**
* blk_alloc_disk - allocate a gendisk structure
* @lim: queue limits to be used for this disk.
* @node_id: numa node to allocate on
*
* Allocate and pre-initialize a gendisk structure for use with BIO based
* drivers.
*
* Returns an ERR_PTR on error, else the allocated disk.
*
* Context: can sleep
*/
#define blk_alloc_disk(lim, node_id) \
({ \
static struct lock_class_key __key; \
\
__blk_alloc_disk(lim, node_id, &__key); \
})
int __register_blkdev(unsigned int major, const char *name,
void (*probe)(dev_t devt));
#define register_blkdev(major, name) \
__register_blkdev(major, name, NULL)
void unregister_blkdev(unsigned int major, const char *name);
bool disk_check_media_change(struct gendisk *disk);
void set_capacity(struct gendisk *disk, sector_t size);
#ifdef CONFIG_BLOCK_HOLDER_DEPRECATED
int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk);
void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk);
#else
static inline int bd_link_disk_holder(struct block_device *bdev,
struct gendisk *disk)
{
return 0;
}
static inline void bd_unlink_disk_holder(struct block_device *bdev,
struct gendisk *disk)
{
}
#endif /* CONFIG_BLOCK_HOLDER_DEPRECATED */
dev_t part_devt(struct gendisk *disk, u8 partno);
void inc_diskseq(struct gendisk *disk);
void blk_request_module(dev_t devt);
extern int blk_register_queue(struct gendisk *disk);
extern void blk_unregister_queue(struct gendisk *disk);
void submit_bio_noacct(struct bio *bio);
struct bio *bio_split_to_limits(struct bio *bio);
struct bio *bio_submit_split_bioset(struct bio *bio, unsigned int split_sectors,
struct bio_set *bs);
extern int blk_lld_busy(struct request_queue *q);
extern int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags);
extern void blk_queue_exit(struct request_queue *q);
extern void blk_sync_queue(struct request_queue *q);
/* Convert a request operation REQ_OP_name into the string "name" */
extern const char *blk_op_str(enum req_op op);
int blk_status_to_errno(blk_status_t status);
blk_status_t errno_to_blk_status(int errno);
const char *blk_status_to_str(blk_status_t status);
/* only poll the hardware once, don't continue until a completion was found */
#define BLK_POLL_ONESHOT (1 << 0)
int bio_poll(struct bio *bio, struct io_comp_batch *iob, unsigned int flags);
int iocb_bio_iopoll(struct kiocb *kiocb, struct io_comp_batch *iob,
unsigned int flags);
static inline struct request_queue *bdev_get_queue(struct block_device *bdev)
{
return bdev->bd_queue; /* this is never NULL */
}
/* Convert a zone condition BLK_ZONE_COND_name into the string "name" */
const char *blk_zone_cond_str(enum blk_zone_cond zone_cond);
static inline unsigned int bio_zone_no(struct bio *bio)
{
return disk_zone_no(bio->bi_bdev->bd_disk, bio->bi_iter.bi_sector);
}
static inline bool bio_straddles_zones(struct bio *bio)
{
return bio_sectors(bio) &&
bio_zone_no(bio) !=
disk_zone_no(bio->bi_bdev->bd_disk, bio_end_sector(bio) - 1);
}
/*
* Return how much within the boundary is left to be used for I/O at a given
* offset.
*/
static inline unsigned int blk_boundary_sectors_left(sector_t offset,
unsigned int boundary_sectors)
{
if (unlikely(!is_power_of_2(boundary_sectors)))
return boundary_sectors - sector_div(offset, boundary_sectors);
return boundary_sectors - (offset & (boundary_sectors - 1));
}
/**
* queue_limits_start_update - start an atomic update of queue limits
* @q: queue to update
*
* This functions starts an atomic update of the queue limits. It takes a lock
* to prevent other updates and returns a snapshot of the current limits that
* the caller can modify. The caller must call queue_limits_commit_update()
* to finish the update.
*
* Context: process context.
*/
static inline struct queue_limits
queue_limits_start_update(struct request_queue *q)
{
mutex_lock(&q->limits_lock);
return q->limits;
}
int queue_limits_commit_update_frozen(struct request_queue *q,
struct queue_limits *lim);
int queue_limits_commit_update(struct request_queue *q,
struct queue_limits *lim);
int queue_limits_set(struct request_queue *q, struct queue_limits *lim);
int blk_validate_limits(struct queue_limits *lim);
/**
* queue_limits_cancel_update - cancel an atomic update of queue limits
* @q: queue to update
*
* This functions cancels an atomic update of the queue limits started by
* queue_limits_start_update() and should be used when an error occurs after
* starting update.
*/
static inline void queue_limits_cancel_update(struct request_queue *q)
{
mutex_unlock(&q->limits_lock);
}
/*
* These helpers are for drivers that have sloppy feature negotiation and might
* have to disable DISCARD, WRITE_ZEROES or SECURE_DISCARD from the I/O
* completion handler when the device returned an indicator that the respective
* feature is not actually supported. They are racy and the driver needs to
* cope with that. Try to avoid this scheme if you can.
*/
static inline void blk_queue_disable_discard(struct request_queue *q)
{
q->limits.max_discard_sectors = 0;
}
static inline void blk_queue_disable_secure_erase(struct request_queue *q)
{
q->limits.max_secure_erase_sectors = 0;
}
static inline void blk_queue_disable_write_zeroes(struct request_queue *q)
{
q->limits.max_write_zeroes_sectors = 0;
q->limits.max_wzeroes_unmap_sectors = 0;
}
/*
* Access functions for manipulating queue properties
*/
extern void blk_set_queue_depth(struct request_queue *q, unsigned int depth);
extern void blk_set_stacking_limits(struct queue_limits *lim);
extern int blk_stack_limits(struct queue_limits *t, struct queue_limits *b,
sector_t offset);
void queue_limits_stack_bdev(struct queue_limits *t, struct block_device *bdev,
sector_t offset, const char *pfx);
extern void blk_queue_rq_timeout(struct request_queue *, unsigned int);
struct blk_independent_access_ranges *
disk_alloc_independent_access_ranges(struct gendisk *disk, int nr_ia_ranges);
void disk_set_independent_access_ranges(struct gendisk *disk,
struct blk_independent_access_ranges *iars);
bool __must_check blk_get_queue(struct request_queue *);
extern void blk_put_queue(struct request_queue *);
void blk_mark_disk_dead(struct gendisk *disk);
struct rq_list {
struct request *head;
struct request *tail;
};
#ifdef CONFIG_BLOCK
/*
* blk_plug permits building a queue of related requests by holding the I/O
* fragments for a short period. This allows merging of sequential requests
* into single larger request. As the requests are moved from a per-task list to
* the device's request_queue in a batch, this results in improved scalability
* as the lock contention for request_queue lock is reduced.
*
* It is ok not to disable preemption when adding the request to the plug list
* or when attempting a merge. For details, please see schedule() where
* blk_flush_plug() is called.
*/
struct blk_plug {
struct rq_list mq_list; /* blk-mq requests */
/* if ios_left is > 1, we can batch tag/rq allocations */
struct rq_list cached_rqs;
u64 cur_ktime;
unsigned short nr_ios;
unsigned short rq_count;
bool multiple_queues;
bool has_elevator;
struct list_head cb_list; /* md requires an unplug callback */
};
struct blk_plug_cb;
typedef void (*blk_plug_cb_fn)(struct blk_plug_cb *, bool);
struct blk_plug_cb {
struct list_head list;
blk_plug_cb_fn callback;
void *data;
};
extern struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug,
void *data, int size);
extern void blk_start_plug(struct blk_plug *);
extern void blk_start_plug_nr_ios(struct blk_plug *, unsigned short);
extern void blk_finish_plug(struct blk_plug *);
void __blk_flush_plug(struct blk_plug *plug, bool from_schedule);
static inline void blk_flush_plug(struct blk_plug *plug, bool async)
{
if (plug)
__blk_flush_plug(plug, async);
}
/*
* tsk == current here
*/
static inline void blk_plug_invalidate_ts(struct task_struct *tsk)
{
struct blk_plug *plug = tsk->plug;
if (plug)
plug->cur_ktime = 0;
current->flags &= ~PF_BLOCK_TS;
}
int blkdev_issue_flush(struct block_device *bdev);
long nr_blockdev_pages(void);
#else /* CONFIG_BLOCK */
struct blk_plug {
};
static inline void blk_start_plug_nr_ios(struct blk_plug *plug,
unsigned short nr_ios)
{
}
static inline void blk_start_plug(struct blk_plug *plug)
{
}
static inline void blk_finish_plug(struct blk_plug *plug)
{
}
static inline void blk_flush_plug(struct blk_plug *plug, bool async)
{
}
static inline void blk_plug_invalidate_ts(struct task_struct *tsk)
{
}
static inline int blkdev_issue_flush(struct block_device *bdev)
{
return 0;
}
static inline long nr_blockdev_pages(void)
{
return 0;
}
#endif /* CONFIG_BLOCK */
extern void blk_io_schedule(void);
int blkdev_issue_discard(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp_mask);
void __blkdev_issue_discard(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp_mask, struct bio **biop);
int blkdev_issue_secure_erase(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp);
#define BLKDEV_ZERO_NOUNMAP (1 << 0) /* do not free blocks */
#define BLKDEV_ZERO_NOFALLBACK (1 << 1) /* don't write explicit zeroes */
#define BLKDEV_ZERO_KILLABLE (1 << 2) /* interruptible by fatal signals */
extern int __blkdev_issue_zeroout(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp_mask, struct bio **biop,
unsigned flags);
extern int blkdev_issue_zeroout(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp_mask, unsigned flags);
static inline int sb_issue_discard(struct super_block *sb, sector_t block,
sector_t nr_blocks, gfp_t gfp_mask, unsigned long flags)
{
return blkdev_issue_discard(sb->s_bdev,
block << (sb->s_blocksize_bits -
SECTOR_SHIFT),
nr_blocks << (sb->s_blocksize_bits -
SECTOR_SHIFT),
gfp_mask);
}
static inline int sb_issue_zeroout(struct super_block *sb, sector_t block,
sector_t nr_blocks, gfp_t gfp_mask)
{
return blkdev_issue_zeroout(sb->s_bdev,
block << (sb->s_blocksize_bits -
SECTOR_SHIFT),
nr_blocks << (sb->s_blocksize_bits -
SECTOR_SHIFT),
gfp_mask, 0);
}
static inline bool bdev_is_partition(struct block_device *bdev)
{
return bdev_partno(bdev) != 0;
}
enum blk_default_limits {
BLK_MAX_SEGMENTS = 128,
BLK_SAFE_MAX_SECTORS = 255,
BLK_MAX_SEGMENT_SIZE = 65536,
BLK_SEG_BOUNDARY_MASK = 0xFFFFFFFFUL,
};
static inline struct queue_limits *bdev_limits(struct block_device *bdev)
{
return &bdev_get_queue(bdev)->limits;
}
static inline unsigned long queue_segment_boundary(const struct request_queue *q)
{
return q->limits.seg_boundary_mask;
}
static inline unsigned long queue_virt_boundary(const struct request_queue *q)
{
return q->limits.virt_boundary_mask;
}
static inline unsigned int queue_max_sectors(const struct request_queue *q)
{
return q->limits.max_sectors;
}
static inline unsigned int queue_max_bytes(struct request_queue *q)
{
return min_t(unsigned int, queue_max_sectors(q), INT_MAX >> 9) << 9;
}
static inline unsigned int queue_max_hw_sectors(const struct request_queue *q)
{
return q->limits.max_hw_sectors;
}
static inline unsigned short queue_max_segments(const struct request_queue *q)
{
return q->limits.max_segments;
}
static inline unsigned short queue_max_discard_segments(const struct request_queue *q)
{
return q->limits.max_discard_segments;
}
static inline unsigned int queue_max_segment_size(const struct request_queue *q)
{
return q->limits.max_segment_size;
}
static inline bool queue_emulates_zone_append(struct request_queue *q)
{
return blk_queue_is_zoned(q) && !q->limits.max_hw_zone_append_sectors;
}
static inline bool bdev_emulates_zone_append(struct block_device *bdev)
{
return queue_emulates_zone_append(bdev_get_queue(bdev));
}
static inline unsigned int
bdev_max_zone_append_sectors(struct block_device *bdev)
{
return bdev_limits(bdev)->max_zone_append_sectors;
}
static inline unsigned int bdev_max_segments(struct block_device *bdev)
{
return queue_max_segments(bdev_get_queue(bdev));
}
static inline unsigned short bdev_max_write_streams(struct block_device *bdev)
{
if (bdev_is_partition(bdev))
return 0;
return bdev_limits(bdev)->max_write_streams;
}
static inline unsigned queue_logical_block_size(const struct request_queue *q)
{
return q->limits.logical_block_size;
}
static inline unsigned int bdev_logical_block_size(struct block_device *bdev)
{
return queue_logical_block_size(bdev_get_queue(bdev));
}
static inline unsigned int queue_physical_block_size(const struct request_queue *q)
{
return q->limits.physical_block_size;
}
static inline unsigned int bdev_physical_block_size(struct block_device *bdev)
{
return queue_physical_block_size(bdev_get_queue(bdev));
}
static inline unsigned int queue_io_min(const struct request_queue *q)
{
return q->limits.io_min;
}
static inline unsigned int bdev_io_min(struct block_device *bdev)
{
return queue_io_min(bdev_get_queue(bdev));
}
static inline unsigned int queue_io_opt(const struct request_queue *q)
{
return q->limits.io_opt;
}
static inline unsigned int bdev_io_opt(struct block_device *bdev)
{
return queue_io_opt(bdev_get_queue(bdev));
}
static inline unsigned int
queue_zone_write_granularity(const struct request_queue *q)
{
return q->limits.zone_write_granularity;
}
static inline unsigned int
bdev_zone_write_granularity(struct block_device *bdev)
{
return queue_zone_write_granularity(bdev_get_queue(bdev));
}
int bdev_alignment_offset(struct block_device *bdev);
unsigned int bdev_discard_alignment(struct block_device *bdev);
static inline unsigned int bdev_max_discard_sectors(struct block_device *bdev)
{
return bdev_limits(bdev)->max_discard_sectors;
}
static inline unsigned int bdev_discard_granularity(struct block_device *bdev)
{
return bdev_limits(bdev)->discard_granularity;
}
static inline unsigned int
bdev_max_secure_erase_sectors(struct block_device *bdev)
{
return bdev_limits(bdev)->max_secure_erase_sectors;
}
static inline unsigned int bdev_write_zeroes_sectors(struct block_device *bdev)
{
return bdev_limits(bdev)->max_write_zeroes_sectors;
}
static inline unsigned int
bdev_write_zeroes_unmap_sectors(struct block_device *bdev)
{
return bdev_limits(bdev)->max_wzeroes_unmap_sectors;
}
static inline bool bdev_rot(struct block_device *bdev)
{
return blk_queue_rot(bdev_get_queue(bdev));
}
static inline bool bdev_synchronous(struct block_device *bdev)
{
return bdev->bd_disk->queue->limits.features & BLK_FEAT_SYNCHRONOUS;
}
static inline bool bdev_has_integrity_csum(struct block_device *bdev)
{
struct queue_limits *lim = bdev_limits(bdev);
return IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
lim->integrity.csum_type != BLK_INTEGRITY_CSUM_NONE;
}
static inline bool bdev_stable_writes(struct block_device *bdev)
{
return bdev_has_integrity_csum(bdev) ||
(bdev_limits(bdev)->features & BLK_FEAT_STABLE_WRITES);
}
static inline bool blk_queue_write_cache(struct request_queue *q)
{
return (q->limits.features & BLK_FEAT_WRITE_CACHE) &&
!(q->limits.flags & BLK_FLAG_WRITE_CACHE_DISABLED);
}
static inline bool bdev_write_cache(struct block_device *bdev)
{
return blk_queue_write_cache(bdev_get_queue(bdev));
}
static inline bool bdev_fua(struct block_device *bdev)
{
return bdev_limits(bdev)->features & BLK_FEAT_FUA;
}
static inline bool bdev_nowait(struct block_device *bdev)
{
return bdev->bd_disk->queue->limits.features & BLK_FEAT_NOWAIT;
}
static inline bool bdev_is_zoned(struct block_device *bdev)
{
return blk_queue_is_zoned(bdev_get_queue(bdev));
}
static inline unsigned int bdev_zone_no(struct block_device *bdev, sector_t sec)
{
return disk_zone_no(bdev->bd_disk, sec);
}
static inline sector_t bdev_zone_sectors(struct block_device *bdev)
{
struct request_queue *q = bdev_get_queue(bdev);
if (!blk_queue_is_zoned(q))
return 0;
return q->limits.chunk_sectors;
}
static inline sector_t bdev_zone_start(struct block_device *bdev,
sector_t sector)
{
return sector & ~(bdev_zone_sectors(bdev) - 1);
}
static inline sector_t bdev_offset_from_zone_start(struct block_device *bdev,
sector_t sector)
{
return sector & (bdev_zone_sectors(bdev) - 1);
}
static inline sector_t bio_offset_from_zone_start(struct bio *bio)
{
return bdev_offset_from_zone_start(bio->bi_bdev,
bio->bi_iter.bi_sector);
}
static inline bool bdev_is_zone_start(struct block_device *bdev,
sector_t sector)
{
return bdev_offset_from_zone_start(bdev, sector) == 0;
}
/* Check whether @sector is a multiple of the zone size. */
static inline bool bdev_is_zone_aligned(struct block_device *bdev,
sector_t sector)
{
return bdev_is_zone_start(bdev, sector);
}
int blk_zone_issue_zeroout(struct block_device *bdev, sector_t sector,
sector_t nr_sects, gfp_t gfp_mask);
static inline unsigned int queue_dma_alignment(const struct request_queue *q)
{
return q->limits.dma_alignment;
}
static inline unsigned int
queue_atomic_write_unit_max_bytes(const struct request_queue *q)
{
return q->limits.atomic_write_unit_max;
}
static inline unsigned int
queue_atomic_write_unit_min_bytes(const struct request_queue *q)
{
return q->limits.atomic_write_unit_min;
}
static inline unsigned int
queue_atomic_write_boundary_bytes(const struct request_queue *q)
{
return q->limits.atomic_write_boundary_sectors << SECTOR_SHIFT;
}
static inline unsigned int
queue_atomic_write_max_bytes(const struct request_queue *q)
{
return q->limits.atomic_write_max_sectors << SECTOR_SHIFT;
}
static inline unsigned int bdev_dma_alignment(struct block_device *bdev)
{
return queue_dma_alignment(bdev_get_queue(bdev));
}
static inline unsigned int
blk_lim_dma_alignment_and_pad(struct queue_limits *lim)
{
return lim->dma_alignment | lim->dma_pad_mask;
}
static inline bool blk_rq_aligned(struct request_queue *q, unsigned long addr,
unsigned int len)
{
unsigned int alignment = blk_lim_dma_alignment_and_pad(&q->limits);
return !(addr & alignment) && !(len & alignment);
}
/* assumes size > 256 */
static inline unsigned int blksize_bits(unsigned int size)
{
return order_base_2(size >> SECTOR_SHIFT) + SECTOR_SHIFT;
}
int kblockd_schedule_work(struct work_struct *work);
int kblockd_mod_delayed_work_on(int cpu, struct delayed_work *dwork, unsigned long delay);
#define MODULE_ALIAS_BLOCKDEV(major,minor) \
MODULE_ALIAS("block-major-" __stringify(major) "-" __stringify(minor))
#define MODULE_ALIAS_BLOCKDEV_MAJOR(major) \
MODULE_ALIAS("block-major-" __stringify(major) "-*")
#ifdef CONFIG_BLK_INLINE_ENCRYPTION
bool blk_crypto_register(struct blk_crypto_profile *profile,
struct request_queue *q);
#else /* CONFIG_BLK_INLINE_ENCRYPTION */
static inline bool blk_crypto_register(struct blk_crypto_profile *profile,
struct request_queue *q)
{
return true;
}
#endif /* CONFIG_BLK_INLINE_ENCRYPTION */
enum blk_unique_id {
/* these match the Designator Types specified in SPC */
BLK_UID_T10 = 1,
BLK_UID_EUI64 = 2,
BLK_UID_NAA = 3,
};
struct block_device_operations {
void (*submit_bio)(struct bio *bio);
int (*poll_bio)(struct bio *bio, struct io_comp_batch *iob,
unsigned int flags);
int (*open)(struct gendisk *disk, blk_mode_t mode);
void (*release)(struct gendisk *disk);
int (*ioctl)(struct block_device *bdev, blk_mode_t mode,
unsigned cmd, unsigned long arg);
int (*compat_ioctl)(struct block_device *bdev, blk_mode_t mode,
unsigned cmd, unsigned long arg);
unsigned int (*check_events) (struct gendisk *disk,
unsigned int clearing);
void (*unlock_native_capacity) (struct gendisk *);
int (*getgeo)(struct gendisk *, struct hd_geometry *);
int (*set_read_only)(struct block_device *bdev, bool ro);
void (*free_disk)(struct gendisk *disk);
/* this callback is with swap_lock and sometimes page table lock held */
void (*swap_slot_free_notify) (struct block_device *, unsigned long);
int (*report_zones)(struct gendisk *, sector_t sector,
unsigned int nr_zones,
struct blk_report_zones_args *args);
char *(*devnode)(struct gendisk *disk, umode_t *mode);
/* returns the length of the identifier or a negative errno: */
int (*get_unique_id)(struct gendisk *disk, u8 id[16],
enum blk_unique_id id_type);
struct module *owner;
const struct pr_ops *pr_ops;
/*
* Special callback for probing GPT entry at a given sector.
* Needed by Android devices, used by GPT scanner and MMC blk
* driver.
*/
int (*alternative_gpt_sector)(struct gendisk *disk, sector_t *sector);
};
#ifdef CONFIG_COMPAT
extern int blkdev_compat_ptr_ioctl(struct block_device *, blk_mode_t,
unsigned int, unsigned long);
#else
#define blkdev_compat_ptr_ioctl NULL
#endif
static inline void blk_wake_io_task(struct task_struct *waiter)
{
/*
* If we're polling, the task itself is doing the completions. For
* that case, we don't need to signal a wakeup, it's enough to just
* mark us as RUNNING.
*/
if (waiter == current)
__set_current_state(TASK_RUNNING);
else
wake_up_process(waiter);
}
unsigned long bdev_start_io_acct(struct block_device *bdev, enum req_op op,
unsigned long start_time);
void bdev_end_io_acct(struct block_device *bdev, enum req_op op,
unsigned int sectors, unsigned long start_time);
unsigned long bio_start_io_acct(struct bio *bio);
void bio_end_io_acct_remapped(struct bio *bio, unsigned long start_time,
struct block_device *orig_bdev);
/**
* bio_end_io_acct - end I/O accounting for bio based drivers
* @bio: bio to end account for
* @start_time: start time returned by bio_start_io_acct()
*/
static inline void bio_end_io_acct(struct bio *bio, unsigned long start_time)
{
return bio_end_io_acct_remapped(bio, start_time, bio->bi_bdev);
}
int bdev_validate_blocksize(struct block_device *bdev, int block_size);
int set_blocksize(struct file *file, int size);
int lookup_bdev(const char *pathname, dev_t *dev);
void blkdev_show(struct seq_file *seqf, off_t offset);
#define BDEVNAME_SIZE 32 /* Largest string for a blockdev identifier */
#define BDEVT_SIZE 10 /* Largest string for MAJ:MIN for blkdev */
#ifdef CONFIG_BLOCK
#define BLKDEV_MAJOR_MAX 512
#else
#define BLKDEV_MAJOR_MAX 0
#endif
struct blk_holder_ops {
void (*mark_dead)(struct block_device *bdev, bool surprise);
/*
* Sync the file system mounted on the block device.
*/
void (*sync)(struct block_device *bdev);
/*
* Freeze the file system mounted on the block device.
*/
int (*freeze)(struct block_device *bdev);
/*
* Thaw the file system mounted on the block device.
*/
int (*thaw)(struct block_device *bdev);
};
/*
* For filesystems using @fs_holder_ops, the @holder argument passed to
* helpers used to open and claim block devices via
* bd_prepare_to_claim() must point to a superblock.
*/
extern const struct blk_holder_ops fs_holder_ops;
/*
* Return the correct open flags for blkdev_get_by_* for super block flags
* as stored in sb->s_flags.
*/
#define sb_open_mode(flags) \
(BLK_OPEN_READ | BLK_OPEN_RESTRICT_WRITES | \
(((flags) & SB_RDONLY) ? 0 : BLK_OPEN_WRITE))
struct file *bdev_file_open_by_dev(dev_t dev, blk_mode_t mode, void *holder,
const struct blk_holder_ops *hops);
struct file *bdev_file_open_by_path(const char *path, blk_mode_t mode,
void *holder, const struct blk_holder_ops *hops);
int bd_prepare_to_claim(struct block_device *bdev, void *holder,
const struct blk_holder_ops *hops);
void bd_abort_claiming(struct block_device *bdev, void *holder);
struct block_device *I_BDEV(struct inode *inode);
struct block_device *file_bdev(struct file *bdev_file);
bool disk_live(struct gendisk *disk);
unsigned int block_size(struct block_device *bdev);
#ifdef CONFIG_BLOCK
void invalidate_bdev(struct block_device *bdev);
int sync_blockdev(struct block_device *bdev);
int sync_blockdev_range(struct block_device *bdev, loff_t lstart, loff_t lend);
int sync_blockdev_nowait(struct block_device *bdev);
void sync_bdevs(bool wait);
void bdev_statx(const struct path *path, struct kstat *stat, u32 request_mask);
void printk_all_partitions(void);
int __init early_lookup_bdev(const char *pathname, dev_t *dev);
#else
static inline void invalidate_bdev(struct block_device *bdev)
{
}
static inline int sync_blockdev(struct block_device *bdev)
{
return 0;
}
static inline int sync_blockdev_nowait(struct block_device *bdev)
{
return 0;
}
static inline void sync_bdevs(bool wait)
{
}
static inline void bdev_statx(const struct path *path, struct kstat *stat,
u32 request_mask)
{
}
static inline void printk_all_partitions(void)
{
}
static inline int early_lookup_bdev(const char *pathname, dev_t *dev)
{
return -EINVAL;
}
#endif /* CONFIG_BLOCK */
int bdev_freeze(struct block_device *bdev);
int bdev_thaw(struct block_device *bdev);
void bdev_fput(struct file *bdev_file);
struct io_comp_batch {
struct rq_list req_list;
bool need_ts;
void (*complete)(struct io_comp_batch *);
void *poll_ctx;
};
static inline bool blk_atomic_write_start_sect_aligned(sector_t sector,
struct queue_limits *limits)
{
unsigned int alignment = max(limits->atomic_write_hw_unit_min,
limits->atomic_write_hw_boundary);
return IS_ALIGNED(sector, alignment >> SECTOR_SHIFT);
}
static inline bool bdev_can_atomic_write(struct block_device *bdev)
{
struct request_queue *bd_queue = bdev->bd_queue;
struct queue_limits *limits = &bd_queue->limits;
if (!limits->atomic_write_unit_min)
return false;
if (bdev_is_partition(bdev))
return blk_atomic_write_start_sect_aligned(bdev->bd_start_sect,
limits);
return true;
}
static inline unsigned int
bdev_atomic_write_unit_min_bytes(struct block_device *bdev)
{
if (!bdev_can_atomic_write(bdev))
return 0;
return queue_atomic_write_unit_min_bytes(bdev_get_queue(bdev));
}
static inline unsigned int
bdev_atomic_write_unit_max_bytes(struct block_device *bdev)
{
if (!bdev_can_atomic_write(bdev))
return 0;
return queue_atomic_write_unit_max_bytes(bdev_get_queue(bdev));
}
static inline int bio_split_rw_at(struct bio *bio,
const struct queue_limits *lim,
unsigned *segs, unsigned max_bytes)
{
return bio_split_io_at(bio, lim, segs, max_bytes, lim->dma_alignment);
}
/*
* Maximum contiguous integrity buffer allocation.
*/
#define BLK_INTEGRITY_MAX_SIZE SZ_2M
/*
* Maximum size of I/O that needs a block layer integrity buffer. Limited
* by the number of intervals for which we can fit the integrity buffer into
* the buffer size. Because the buffer is a single segment it is also limited
* by the maximum segment size.
*/
static inline unsigned int max_integrity_io_size(struct queue_limits *lim)
{
return min_t(unsigned int, lim->max_segment_size,
(BLK_INTEGRITY_MAX_SIZE / lim->integrity.metadata_size) <<
lim->integrity.interval_exp);
}
#define DEFINE_IO_COMP_BATCH(name) struct io_comp_batch name = { }
#endif /* _LINUX_BLKDEV_H */
]
|
| 235/6 |
2026/05/10 03:25 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 40250
output: 43
thoughts: 504
Thoughts: **Analyzing Potential Race Conditions in NBD Device Initialization**
Okay, so I'm looking at this `struct gendisk` and specifically the `part0` member, which is a `struct block_device *`. Right, that's straightforward.
Now, my focus is on the `nbd_set_size` function, and how it interacts with claiming the block device. It's becoming clear that we're using `bd_prepare_to_claim` with the whole disk, using `nbd->disk->part0`.
The key issue is that `nbd_set_size` is called from `nbd_start_device`, which itself is invoked by either `nbd_ioctl` (specifically `NBD_DO_IT`) or `nbd_genl_connect`.
If the call comes via `nbd_ioctl`, the device is, by definition, already open. If the user opened the device with the `O_EXCL` flag, which means exclusive access, then `bd_prepare_to_claim` is very likely to fail. This is because they *intended* to be the sole owner. Trying to then claim it again, with a different context via `nbd_set_size`, goes against that intention.
I see how the `loop.c` driver deals with this. They check the open `mode` using `BLK_OPEN_EXCL`. If the exclusive open flag is set they skip the `bd_prepare_to_claim` call. Smart.
The problem here is that `nbd_set_size` doesn't know anything about the `mode` used to open the device. Further, when `nbd_set_size` is called through `nbd_genl_connect`, there is no `mode` to consult.
Another crucial point: `bd_prepare_to_claim` *must* be paired with either `bd_abort_claiming` or `bd_finish_claiming`. That means if we put this `bd_prepare_to_claim` in `nbd_set_size`, we *must* ensure that we release the claim, regardless of what happens. This is critical.
Wait a second, `nbd_set_size` is called from `nbd_start_device`. But `nbd_start_device` is called *after* the device is supposedly ready to go. So, what's going on in `nbd_start_device` now? Let's take a look.
|
| 236/6 |
2026/05/10 03:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device]
Results: map[SourceCode:1471: static int nbd_start_device(struct nbd_device *nbd)
1472: {
1473: struct nbd_config *config = nbd->config;
1474: int num_connections = config->num_connections;
1475: int error = 0, i;
1476:
1477: if (nbd->pid)
1478: return -EBUSY;
1479: if (!config->socks)
1480: return -EINVAL;
1481: if (num_connections > 1 &&
1482: !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1483: dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1484: return -EINVAL;
1485: }
1486:
1487: retry:
1488: mutex_unlock(&nbd->config_lock);
1489: blk_mq_update_nr_hw_queues(&nbd->tag_set, num_connections);
1490: mutex_lock(&nbd->config_lock);
1491:
1492: /* if another code path updated nr_hw_queues, retry until succeed */
1493: if (num_connections != config->num_connections) {
1494: num_connections = config->num_connections;
1495: goto retry;
1496: }
1497:
1498: nbd->pid = task_pid_nr(current);
1499:
1500: nbd_parse_flags(nbd);
1501:
1502: error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1503: if (error) {
1504: dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1505: return error;
1506: }
1507: set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1508:
1509: nbd_dev_dbg_init(nbd);
1510: for (i = 0; i < num_connections; i++) {
1511: struct recv_thread_args *args;
1512:
1513: args = kzalloc_obj(*args);
1514: if (!args) {
1515: sock_shutdown(nbd);
1516: /*
1517: * If num_connections is m (2 < m),
1518: * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1519: * But NO.(n + 1) failed. We still have n recv threads.
1520: * So, add flush_workqueue here to prevent recv threads
1521: * dropping the last config_refs and trying to destroy
1522: * the workqueue from inside the workqueue.
1523: */
1524: if (i)
1525: flush_workqueue(nbd->recv_workq);
1526: return -ENOMEM;
1527: }
1528: sk_set_memalloc(config->socks[i]->sock->sk);
1529: if (nbd->tag_set.timeout)
1530: config->socks[i]->sock->sk->sk_sndtimeo =
1531: nbd->tag_set.timeout;
1532: atomic_inc(&config->recv_threads);
1533: refcount_inc(&nbd->config_refs);
1534: INIT_WORK(&args->work, recv_work);
1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
SourceFile:drivers/block/nbd.c]
|
| 237/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 42518
output: 41
thoughts: 451
Thoughts: **Analyzing Potential Deadlock in NBD Driver**
Okay, so I'm looking at this question about using `bd_prepare_to_claim` within `nbd_set_size` in the NBD driver, specifically in `drivers/block/nbd.c`. The user is hinting at a potential issue, and I need to figure out if there's a real deadlock scenario here.
First off, I'm noting that `nbd_start_device` calls are made while holding `nbd->config_lock`. And, of course, `nbd_set_size` is usually called with that same lock held. The concern arises because `bd_prepare_to_claim` is called *inside* `nbd_set_size`, and that function takes `bdev_lock`.
The crux of the matter is this: `nbd_set_size` then calls `set_capacity_and_notify`, which in turn calls `kobject_uevent_env`. The question is, can we create a situation where we're holding `bdev_lock` and then try to take `nbd->config_lock`?
I immediately considered this might be a deadlock, because `bd_prepare_to_claim` *does* take `bdev_lock`. So, my first question is, does anything else in `nbd.c` also take `bdev_lock`? If we have a dependency cycle it is a concern.
Then I recalled that `bd_prepare_to_claim` can actually sleep. Specifically, it can sleep if the block device is already being claimed: it checks the `whole->bd_claiming` flag, and if set, it will sleep in the wait queue. It drops `bdev_lock` to allow the sleep, using `mutex_unlock(&bdev_lock)` just before the `schedule()` call.
The relevant bit is here:
```c
606: if (whole->bd_claiming) {
607: wait_queue_head_t *wq = __var_waitqueue(&whole->bd_claiming);
608: DEFINE_WAIT(wait);
609:
610: prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
611: mutex_unlock(&bdev_lock);
612: schedule();
```
If `nbd_set_size` is called from `nbd_ioctl`, we are already holding `nbd->config_lock`, so it is not a direct path to the deadlock.
So, to summarize, the critical check is: is there any code path that, on one hand, takes `bdev_lock` and, on the other hand, calls some function that tries to take `nbd->config_lock`? `nbd_open` takes `nbd->config_lock`, I should examine that function to be certain. That is where I will start.
|
| 238/6 |
2026/05/10 03:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_open]
Results: map[SourceCode:1705: static int nbd_open(struct gendisk *disk, blk_mode_t mode)
1706: {
1707: struct nbd_device *nbd;
1708: struct nbd_config *config;
1709: int ret = 0;
1710:
1711: mutex_lock(&nbd_index_mutex);
1712: nbd = disk->private_data;
1713: if (!nbd) {
1714: ret = -ENXIO;
1715: goto out;
1716: }
1717: if (!refcount_inc_not_zero(&nbd->refs)) {
1718: ret = -ENXIO;
1719: goto out;
1720: }
1721:
1722: config = nbd_get_config_unlocked(nbd);
1723: if (!config) {
1724: mutex_lock(&nbd->config_lock);
1725: if (refcount_inc_not_zero(&nbd->config_refs)) {
1726: mutex_unlock(&nbd->config_lock);
1727: goto out;
1728: }
1729: ret = nbd_alloc_and_init_config(nbd);
1730: if (ret) {
1731: mutex_unlock(&nbd->config_lock);
1732: goto out;
1733: }
1734:
1735: refcount_inc(&nbd->refs);
1736: mutex_unlock(&nbd->config_lock);
1737: if (max_part)
1738: set_bit(GD_NEED_PART_SCAN, &disk->state);
1739: } else if (nbd_disconnected(config)) {
1740: if (max_part)
1741: set_bit(GD_NEED_PART_SCAN, &disk->state);
1742: }
1743: out:
1744: mutex_unlock(&nbd_index_mutex);
1745: return ret;
1746: }
SourceFile:drivers/block/nbd.c]
|
| 239/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 44299
output: 40
thoughts: 965
Thoughts: **Analyzing Potential Regression in NBD Device Resizing**
Okay, so I'm digging into how NBD device resizing works, and I've hit something that smells like a potential regression. I'm seeing that `nbd_open` grabs the `nbd_index_mutex` and `nbd->config_lock`, which is expected. The interesting part is that `nbd_open` gets called from the block layer, and, importantly, it *doesn't* hold `bdev_lock` when it's invoked. Now, `bdev_lock` is a global lock in `block/bdev.c`, so I need to understand what it protects.
It looks like `bdev_lock` guards `bd_claiming` and `bd_holder`. The problem arises when I look at `bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL)`. I'm essentially using `nbd_set_size` as the holder here. Now, if `nbd_set_size` is called via `nbd_ioctl`, the block layer has already opened the device, right? And if it was opened with `O_EXCL`, then `bdev->bd_holder` is *already* set.
This leads to a key point: `bd_prepare_to_claim` calls `bd_may_claim`. `bd_may_claim` checks if `bdev->bd_holder` is set, and if it's not `nbd_set_size`, it returns `false`. This, in turn, causes `bd_prepare_to_claim` to return `-EBUSY`.
Essentially, this means that if `/dev/nbd0` is opened with `O_EXCL`, I can't resize it via ioctl. But that *can't* be right. Resizing an NBD device is a common operation, often done while the device is in use, so this seems like a step backwards or, at the very least, a shift in behavior.
Wait, hold on. If I open `/dev/nbd0` with `O_EXCL`, *then* call `ioctl(NBD_SET_SIZE)`, it *should* work because *I* have exclusive access. The issue is that the function pointer, `nbd_set_size`, is not the same as the entity that opened the device and "holds" the exclusive lock.
Looking at `loop.c`, I see some interesting code. There's a check: `if (!(mode & BLK_OPEN_EXCL))`. If the exclusive open flag isn't set, then `bd_prepare_to_claim` is called. That's good. In the case where `mode & BLK_OPEN_EXCL` *is* true, `bd_prepare_to_claim` is skipped. The logic here is sound: if the caller already has exclusive access, we don't need to try claiming it.
Now I need to determine how to apply this to `nbd_set_size`. The difficulty is, `nbd_set_size` is called from various places, some of which don't have a `mode` parameter. `nbd_genl_size_set` (using Netlink), for example, doesn't have a `mode` value. If someone has `/dev/nbd0` open exclusively, should Netlink be *allowed* to resize it? Using `bd_prepare_to_claim` will result in a `-EBUSY` error.
Is this the *correct* behavior? For `loop`, `loop_set_block_size` is an ioctl. But `loop` resizing via `loop_set_capacity` doesn't use `bd_prepare_to_claim`. Why the difference? Perhaps modifying the block size is more dangerous than changing the device capacity. `nbd_set_size` allows both the block size and capacity to be changed:
```c
372: lim.logical_block_size = blksize;
373: lim.physical_block_size = blksize;
```
Changing the block size, when the device is in use, could be highly problematic.
Ah, there's another point. `nbd->disk->part0` might be NULL if `nbd->disk` is NULL, but `nbd_set_size` is called on an *existing* `nbd_device`. The disk gets created in `nbd_dev_add`.
I think I've found something! I remember seeing something about `bd_prepare_to_claim` in recent commits. Let's start searching recent commits for `bd
|
| 240/6 |
2026/05/10 03:26 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:1 Name:bd_prepare_to_claim SourceTreePrefix:block/]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:bdev_open SourceFile:block/bdev.c SourceLine:943 SourceSnippet: 942: mode |= BLK_OPEN_EXCL;
943: ret = bd_prepare_to_claim(bdev, holder, hops);
944: if (ret)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:disk_scan_partitions SourceFile:block/genhd.c SourceLine:380 SourceSnippet: 379: if (!(mode & BLK_OPEN_EXCL)) {
380: ret = bd_prepare_to_claim(disk->part0, disk_scan_partitions,
381: NULL);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:truncate_bdev_range SourceFile:block/bdev.c SourceLine:120 SourceSnippet: 119: if (!(mode & BLK_OPEN_EXCL)) {
120: int err = bd_prepare_to_claim(bdev, truncate_bdev_range, NULL);
121: if (err)
]] TruncatedOutput:false]
|
| 241/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 46682
output: 45
thoughts: 243
Thoughts: **Analyzing the NBD Device Size Change**
Okay, first things first, I need to verify something. I should check the history of `nbd.c` to see if `bd_prepare_to_claim` was ever used. That might be relevant. But before I do that, let me re-examine the current implementation of `nbd_set_size`.
Ah, right, it calls `queue_limits_commit_update_frozen`. Now, wait a minute... `queue_limits_commit_update_frozen` – that's a relatively new API, isn't it? That could be important to understanding the bigger picture.
Let me go back and look at the `nbd_set_size` function again. Okay, here it is:
```c
334: static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
335: {
...
354: lim = queue_limits_start_update(nbd->disk->queue);
...
374: error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
```
Okay, so `queue_limits_start_update` takes `q->limits_lock`. Now, the crucial question is whether `queue_limits_commit_update_frozen` releases that lock. I need to be sure about that. Let me double-check the implementation of `queue_limits_commit_update_frozen`.
|
| 242/6 |
2026/05/10 03:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-settings.c IncludeLines:true Name:queue_limits_commit_update_frozen]
Results: map[SourceCode: 573: /**
574: * queue_limits_commit_update_frozen - commit an atomic update of queue limits
575: * @q: queue to update
576: * @lim: limits to apply
577: *
578: * Apply the limits in @lim that were obtained from queue_limits_start_update()
579: * and updated with the new values by the caller to @q. Freezes the queue
580: * before the update and unfreezes it after.
581: *
582: * Returns 0 if successful, else a negative error code.
583: */
584: int queue_limits_commit_update_frozen(struct request_queue *q,
585: struct queue_limits *lim)
586: {
587: unsigned int memflags;
588: int ret;
589:
590: memflags = blk_mq_freeze_queue(q);
591: ret = queue_limits_commit_update(q, lim);
592: blk_mq_unfreeze_queue(q, memflags);
593:
594: return ret;
595: }
SourceFile:block/blk-settings.c]
|
| 243/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 47681
output: 43
thoughts: 10
Thoughts: Okay, here's my summary, taking on the persona you requested:
**Analyzing `queue_limits_commit_update`**
Alright, let's break this down. From a high-level perspective, I'm thinking about how we're handling limits related to queues, specifically when updates are being committed. This function, `queue_limits_commit_update`, sounds crucial. I need to understand what triggered this event, what specific queue data is in play, and what state it was in. What were the previous limits, what modifications are intended, and are they valid? I'm immediately running through the potential concurrency issues. Is this function atomic? What locking mechanisms are in place, if any, to prevent race conditions when multiple processes or threads are trying to update queue limits concurrently? I need to know the potential for deadlocks or priority inversion.
Next, I'm digging into data consistency. How is this update persisted? Is it a single write, or a multi-step process? If it's multi-step, what happens if there's a failure in the middle of it? Are there transactional guarantees in place, or some other mechanism for handling partial updates? We're talking about limits, so data integrity is paramount. If a limit is partially applied, what's the consequence? Can we even recover if this update fails, or does it leave us in an inconsistent state?
Then there's the question of notifications or propagation. Once the update is committed, does the system need to notify any other components or processes that rely on these queue limits? Other services? Other internal modules? Is there a broadcast mechanism, or is it a polling strategy? What are the performance implications of the chosen notification method?
Finally, let's consider error handling. What exceptions could this function potentially throw? What are the recovery strategies? And finally, what are the logging capabilities, especially for debugging and auditing? What information is logged when an update is successful, and what information is logged if it fails?
|
| 244/6 |
2026/05/10 03:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/blk-settings.c IncludeLines:true Name:queue_limits_commit_update]
Results: map[SourceCode: 534: /**
535: * queue_limits_commit_update - commit an atomic update of queue limits
536: * @q: queue to update
537: * @lim: limits to apply
538: *
539: * Apply the limits in @lim that were obtained from queue_limits_start_update()
540: * and updated by the caller to @q. The caller must have frozen the queue or
541: * ensure that there are no outstanding I/Os by other means.
542: *
543: * Returns 0 if successful, else a negative error code.
544: */
545: int queue_limits_commit_update(struct request_queue *q,
546: struct queue_limits *lim)
547: {
548: int error;
549:
550: lockdep_assert_held(&q->limits_lock);
551:
552: error = blk_validate_limits(lim);
553: if (error)
554: goto out_unlock;
555:
556: #ifdef CONFIG_BLK_INLINE_ENCRYPTION
557: if (q->crypto_profile && lim->integrity.tag_size) {
558: pr_warn("blk-integrity: Integrity and hardware inline encryption are not supported together.\n");
559: error = -EINVAL;
560: goto out_unlock;
561: }
562: #endif
563:
564: q->limits = *lim;
565: if (q->disk)
566: blk_apply_bdi_limits(q->disk->bdi, lim);
567: out_unlock:
568: mutex_unlock(&q->limits_lock);
569: return error;
570: }
SourceFile:block/blk-settings.c]
|
| 245/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 48713
output: 41
thoughts: 613
Thoughts: **Analyzing the Implications of Adding `bd_prepare_to_claim` to `nbd_set_size`**
Okay, so I've confirmed that releasing `q->limits_lock` is handled correctly. Now, I need to figure out the best way to integrate `bd_prepare_to_claim`.
The proposed approach is to include `bd_prepare_to_claim` within the `nbd_set_size` function, similar to how it's done in `loop.c`. The initial thought was:
```c
if (!(mode & BLK_OPEN_EXCL)) {
error = bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL);
if (error)
return error;
}
...
if (!(mode & BLK_OPEN_EXCL))
bd_abort_claiming(nbd->disk->part0, nbd_set_size);
```
However, I immediately see a problem: `nbd_set_size` doesn't have access to the `mode` parameter.
If I just unconditionally call `bd_prepare_to_claim`, it's going to fail when the device is opened with `O_EXCL`. This is a significant issue because `nbd_ioctl` *calls* `nbd_set_size`. So, consider this scenario:
```c
fd = open("/dev/nbd0", O_RDWR | O_EXCL);
ioctl(fd, NBD_SET_SIZE, ...);
```
The `open` with `O_EXCL` will claim the device. Then, the `ioctl` will call `nbd_set_size`, which, if it calls `bd_prepare_to_claim` unconditionally, would fail because the device is already claimed by the `open`. Definitely wrong.
But, do we need `bd_prepare_to_claim` at all? In `loop.c`, it seems to be used to "avoid changing the device under exclusive owner". But, if the *caller* is the exclusive owner, they *should* be allowed to change it. That's why `loop.c` checks `mode & BLK_OPEN_EXCL`.
So, if `nbd` wants similar protection, it must *also* check the `mode`. However, `nbd` has another layer of protection with `nbd->config_lock`. The `config_lock`, though, only protects the internal `nbd` state, not the block device's "claimed" status.
Now, I need to consider all angles. Is there any other potential issue? For instance, what if `nbd->disk->part0` is NULL? I recall that `nbd->disk` is allocated in `nbd_dev_add` using `blk_mq_alloc_disk`. And `blk_mq_alloc_disk` (which calls `alloc_disk_node`) initializes `part0`. I should verify that initialization flow. Let me double-check `alloc_disk_node`...
|
| 246/6 |
2026/05/10 03:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c IncludeLines:true Name:__blk_alloc_disk]
Results: map[SourceCode:1508: struct gendisk *__blk_alloc_disk(struct queue_limits *lim, int node,
1509: struct lock_class_key *lkclass)
1510: {
1511: struct queue_limits default_lim = { };
1512: struct request_queue *q;
1513: struct gendisk *disk;
1514:
1515: q = blk_alloc_queue(lim ? lim : &default_lim, node);
1516: if (IS_ERR(q))
1517: return ERR_CAST(q);
1518:
1519: disk = __alloc_disk_node(q, node, lkclass);
1520: if (!disk) {
1521: blk_put_queue(q);
1522: return ERR_PTR(-ENOMEM);
1523: }
1524: set_bit(GD_OWNS_QUEUE, &disk->state);
1525: return disk;
1526: }
SourceFile:block/genhd.c]
|
| 247/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 50351
output: 41
thoughts: 9
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Internal Monologue on `__alloc_disk_node`**
Alright, let's break down this `__alloc_disk_node` function. I'm immediately thinking about its role in the block layer, specifically within the context of disk device representation. It's the critical entry point for creating a new `disk_dev` structure, which I know is the core data structure that represents a logical disk to the kernel.
My first thought is around resource allocation. What kind of memory allocator is it using internally? Is it `kmalloc`? Does it interact with a custom slab cache tailored for `disk_dev` objects for increased performance? I'd expect some optimization here, given the likely frequent creation and destruction of these structures, particularly during hotplug events or LVM operations. Memory fragmentation is something I need to keep in mind, and the allocator strategy greatly influences that.
Next, I'm analyzing the initial field initialization. What data is it setting? Obviously, it's populating the basic fields like the device number, the disk name, and importantly, the major and minor numbers for the character device. This is crucial for device identification and access. I'm wondering if it's hooking the disk into the block device list, and how it handles potential race conditions there. Any locking involved is something I'd want to audit carefully. I'd need to consider how this function interacts with `blk_register_queue` and other block layer functions.
Finally, I'm considering the failure cases. What happens if memory allocation fails? How does it handle potential errors in the device number allocation or block layer registration? Does it return an error code, and is that error propagated correctly up the call chain? Proper error handling is paramount, especially when dealing with potentially catastrophic failures in storage systems. I'm also curious about its interaction with any device discovery or enumeration mechanisms. It would be important for it to work correctly in all situations.
|
| 248/6 |
2026/05/10 03:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/genhd.c IncludeLines:true Name:__alloc_disk_node]
Results: map[SourceCode:1446: struct gendisk *__alloc_disk_node(struct request_queue *q, int node_id,
1447: struct lock_class_key *lkclass)
1448: {
1449: struct gendisk *disk;
1450:
1451: disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1452: if (!disk)
1453: return NULL;
1454:
1455: if (bioset_init(&disk->bio_split, BIO_POOL_SIZE, 0, 0))
1456: goto out_free_disk;
1457:
1458: disk->bdi = bdi_alloc(node_id);
1459: if (!disk->bdi)
1460: goto out_free_bioset;
1461:
1462: /* bdev_alloc() might need the queue, set before the first call */
1463: disk->queue = q;
1464:
1465: disk->part0 = bdev_alloc(disk, 0);
1466: if (!disk->part0)
1467: goto out_free_bdi;
1468:
1469: disk->node_id = node_id;
1470: mutex_init(&disk->open_mutex);
1471: xa_init(&disk->part_tbl);
1472: if (xa_insert(&disk->part_tbl, 0, disk->part0, GFP_KERNEL))
1473: goto out_destroy_part_tbl;
1474:
1475: if (blkcg_init_disk(disk))
1476: goto out_erase_part0;
1477:
1478: disk_init_zone_resources(disk);
1479: rand_initialize_disk(disk);
1480: disk_to_dev(disk)->class = &block_class;
1481: disk_to_dev(disk)->type = &disk_type;
1482: device_initialize(disk_to_dev(disk));
1483: inc_diskseq(disk);
1484: q->disk = disk;
1485: lockdep_init_map(&disk->lockdep_map, "(bio completion)", lkclass, 0);
1486: #ifdef CONFIG_BLOCK_HOLDER_DEPRECATED
1487: INIT_LIST_HEAD(&disk->slave_bdevs);
1488: #endif
1489: mutex_init(&disk->rqos_state_mutex);
1490: kobject_init(&disk->queue_kobj, &blk_queue_ktype);
1491: return disk;
1492:
1493: out_erase_part0:
1494: xa_erase(&disk->part_tbl, 0);
1495: out_destroy_part_tbl:
1496: xa_destroy(&disk->part_tbl);
1497: disk->part0->bd_disk = NULL;
1498: bdev_drop(disk->part0);
1499: out_free_bdi:
1500: bdi_put(disk->bdi);
1501: out_free_bioset:
1502: bioset_exit(&disk->bio_split);
1503: out_free_disk:
1504: kfree(disk);
1505: return NULL;
1506: }
SourceFile:block/genhd.c]
|
| 249/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 51823
output: 46
thoughts: 1643
Thoughts: **Analyzing NBD Device Resizing and Exclusive Access**
Okay, so I'm digging into how the NBD driver handles size changes, and some interesting interactions with device claiming are popping up. First, I noticed that `disk->part0` is initialized during allocation, as expected.
Then, there's this bit of code in `nbd_set_size`. It returns early if `nbd->pid` is zero. `nbd->pid` gets set in `nbd_start_device`. Essentially, if `nbd_set_size` is called *before* the device is actually started (like through an `NBD_SET_SIZE` ioctl before `NBD_DO_IT`), it just updates the size in the config but doesn't touch the capacity or queue limits. It waits to actually set the size until start, which calls `nbd_set_size` again.
Here's the interesting part: if `nbd_set_size` *is* called from within `nbd_start_device` (after the device has been started), and we use `bd_prepare_to_claim`, what happens? `nbd_start_device` is called from `nbd_ioctl(NBD_DO_IT)` which is how the device is "run".
If the user opens the device normally with `open("/dev/nbd0", O_RDWR)`, the device isn't opened exclusively, so `bd_prepare_to_claim` will succeed. This isn't a problem.
But if they open with `O_RDWR | O_EXCL`, `bd_prepare_to_claim` would fail with `-EBUSY`, and `nbd_start_device` would fail. This means you can't start an NBD device if it's already exclusively opened. Is this by design? Probably, but what if a tool attempts to start the device and exclusively open the device. It seems like the common case is that you do *not* exclusively open a device when starting it, but this is a potentially serious issue.
However, a more significant concern is online resizing. `nbd_set_size` is also called from `nbd_genl_reconfigure`. Now, if the device is running (e.g., mounted), and we want to resize it, using `bd_prepare_to_claim` could fail because the device is in use, thus breaking online resizing, which is a supported feature. This is a big problem.
So, using `bd_prepare_to_claim` in `nbd_set_size` would break online resizing of mounted NBD devices. I need to know if this is a mistake, or an intended design.
I'm thinking, let's look at `loop` to see how it handles online resizing. I see `loop_set_capacity` doesn't use `bd_prepare_to_claim`, but `loop_set_block_size` *does*. This suggests capacity changes are fine while claimed, but block size changes might need more care. In `nbd_set_size`, we might be changing both! But we need to allow resizing even when it's claimed, which means not using `bd_prepare_to_claim`.
However, consider that `nbd_set_size` is *often* called with the same block size just to change the capacity. Is there a way to optimize this?
Looking back at `nbd_set_size`, I see queue limits are updated using `queue_limits_commit_update_frozen`, which freezes the queue. I think this should be enough to safely change the block size, right?
But why does `loop` use `bd_prepare_to_claim` at all? Maybe it's a matter of expectations. If a filesystem has the device, it likely expects the block size to remain constant. If `nbd` wants to follow this, it should only call `bd_prepare_to_claim` *if* the block size is actually changing.
Now, there's another crucial problem with adding a call to `bd_prepare_to_claim`: if it succeeds, it sets `nbd->disk->part0->bd_claiming` and *must* be cleared later. If we just add the `bd_prepare_to_claim` call without a matching `bd_abort_claiming` or `bd_finish_claiming`, the device will remain in a "claiming" state indefinitely, blocking subsequent `O_EXCL` opens or other claims. This is a very serious bug.
Also, I have to check if `nbd->disk` can be NULL. In `nbd_dev_add`, `nbd->disk` is set before `add_disk`. The
|
| 250/6 |
2026/05/10 03:26 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:1 Name:bd_prepare_to_claim SourceTreePrefix:drivers/block/nbd.c]
Results: map[References:<nil> TruncatedOutput:false]
|
| 251/6 |
2026/05/10 03:26 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 54554
output: 39
thoughts: 1204
Thoughts: **Analyzing a Potential Deadlock in the NBD Driver**
Okay, still nothing immediately jumping out from the source code. Let's revisit `nbd_set_size`. I'm racking my brain, trying to find anything else, any issue I missed. What if `nbd->disk` is unexpectedly NULL? That should be handled in the connect sequence, though.
Right, back to basics. Looking at `nbd_genl_connect`, specifically how the `nbd` device is retrieved from the IDR. If `nbd` is found, `nbd->disk` *must* be valid because it's added by `nbd_dev_add`. Good.
Aha! Wait, I'm just glancing over the possible problems related to `nbd->disk->part0`. In *some* kernel versions, `part0` might not be directly part of the `gendisk` structure or might be handled differently, but in this version it *is* there based on the `struct-layout` I've just checked.
Hang on. Is `bd_prepare_to_claim` the correct function for this? If we're changing the size, perhaps we should use something like `blkdev_get_by_dev` with `BLK_OPEN_EXCL`? No, that's not right. `bd_prepare_to_claim` is definitely used when we *have* the `block_device` pointer and we want to claim it, it's the right function.
Actually, something just surfaced from the back of my memory, I *think* I recall a commit about `nbd` and `bd_prepare_to_claim`. I really wish I could search the git logs for "nbd" and "claim" but no joy. Maybe I could search the history of the `nbd.c` file itself... if I had the tool!
Okay, I *can* use `codesearch-find-references` with a wider context to find any comments about claiming. Let's see...
Alright, let's circle back to `nbd_set_size` again. If `set_capacity_and_notify` returns `false`, it means the uevent was not sent. Wait, I remember that `set_capacity_and_notify` sends a `RESIZE=1` uevent, so if it returns false, it's because it couldn't be sent, and `nbd` sends a generic `KOBJ_CHANGE` uevent. That makes sense.
Now, that brings me back to `bd_prepare_to_claim`. If I use it, I *am* claiming the device, right? If I'm already holding `config_lock`... and `bd_prepare_to_claim` waits for someone else to release the claim... Could that create a deadlock? Who else would be claiming the device? `bdev_open` with `O_EXCL` claims the device, I remember that. `bdev_open` *calls* the `disk->fops->open`. And `nbd_open` takes `nbd_index_mutex` and `nbd->config_lock`.
Here's the scenario:
1. **Thread A:** Runs `bdev_open(O_EXCL)` on, say, `/dev/nbd0`.
* Takes the `bdev_lock`.
* Sets `whole->bd_claiming = holder` (where `holder` is `Thread A`).
* Calls `disk->fops->open` which is `nbd_open`.
* `nbd_open` tries to acquire `nbd->config_lock`.
2. **Thread B:** Executes `nbd_ioctl(NBD_SET_SIZE)`.
* Takes `nbd->config_lock`.
* Calls `nbd_set_size`.
* `nbd_set_size` calls `bd_prepare_to_claim`.
* `bd_prepare_to_claim` takes the `bdev_lock`.
* `bd_prepare_to_claim` sees that `whole->bd_claiming` is already set (by Thread A).
* `bd_prepare_to_claim` is designed to wait on `whole->bd_claiming` waitqueue (while holding `nbd->config_lock`)?
Wait, I know `bd_prepare_to_claim` *releases* the `bdev_lock` before `schedule()`:
```c
mutex_unlock(&bdev_lock);
schedule();
```
But it still holds
|
| 252/6 |
2026/05/10 03:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:bdev_open]
Results: map[SourceCode: 917: /**
918: * bdev_open - open a block device
919: * @bdev: block device to open
920: * @mode: open mode (BLK_OPEN_*)
921: * @holder: exclusive holder identifier
922: * @hops: holder operations
923: * @bdev_file: file for the block device
924: *
925: * Open the block device. If @holder is not %NULL, the block device is opened
926: * with exclusive access. Exclusive opens may nest for the same @holder.
927: *
928: * CONTEXT:
929: * Might sleep.
930: *
931: * RETURNS:
932: * zero on success, -errno on failure.
933: */
934: int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
935: const struct blk_holder_ops *hops, struct file *bdev_file)
936: {
937: bool unblock_events = true;
938: struct gendisk *disk = bdev->bd_disk;
939: int ret;
940:
941: if (holder) {
942: mode |= BLK_OPEN_EXCL;
943: ret = bd_prepare_to_claim(bdev, holder, hops);
944: if (ret)
945: return ret;
946: } else {
947: if (WARN_ON_ONCE(mode & BLK_OPEN_EXCL))
948: return -EIO;
949: }
950:
951: disk_block_events(disk);
952:
953: mutex_lock(&disk->open_mutex);
954: ret = -ENXIO;
955: if (!disk_live(disk))
956: goto abort_claiming;
957: if (!try_module_get(disk->fops->owner))
958: goto abort_claiming;
959: ret = -EBUSY;
960: if (!bdev_may_open(bdev, mode))
961: goto put_module;
962: if (bdev_is_partition(bdev))
963: ret = blkdev_get_part(bdev, mode);
964: else
965: ret = blkdev_get_whole(bdev, mode);
966: if (ret)
967: goto put_module;
968: bdev_claim_write_access(bdev, mode);
969: if (holder) {
970: bd_finish_claiming(bdev, holder, hops);
971:
972: /*
973: * Block event polling for write claims if requested. Any write
974: * holder makes the write_holder state stick until all are
975: * released. This is good enough and tracking individual
976: * writeable reference is too fragile given the way @mode is
977: * used in blkdev_get/put().
978: */
979: if ((mode & BLK_OPEN_WRITE) &&
980: !bdev_test_flag(bdev, BD_WRITE_HOLDER) &&
981: (disk->event_flags & DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE)) {
982: bdev_set_flag(bdev, BD_WRITE_HOLDER);
983: unblock_events = false;
984: }
985: }
986: mutex_unlock(&disk->open_mutex);
987:
988: if (unblock_events)
989: disk_unblock_events(disk);
990:
991: bdev_file->f_flags |= O_LARGEFILE;
992: bdev_file->f_mode |= FMODE_CAN_ODIRECT;
993: if (bdev_nowait(bdev))
994: bdev_file->f_mode |= FMODE_NOWAIT;
995: if (mode & BLK_OPEN_RESTRICT_WRITES)
996: bdev_file->f_mode |= FMODE_WRITE_RESTRICTED;
997: bdev_file->f_mapping = bdev->bd_mapping;
998: bdev_file->f_wb_err = filemap_sample_wb_err(bdev_file->f_mapping);
999: bdev_file->private_data = holder;
1000:
1001: return 0;
1002: put_module:
1003: module_put(disk->fops->owner);
1004: abort_claiming:
1005: if (holder)
1006: bd_abort_claiming(bdev, holder);
1007: mutex_unlock(&disk->open_mutex);
1008: disk_unblock_events(disk);
1009: return ret;
1010: }
SourceFile:block/bdev.c]
|
| 253/6 |
2026/05/10 03:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 58311
output: 41
thoughts: 94
Thoughts: **My Analysis of the Block Device Opening Process**
Okay, so I'm diving into this `bdev_open` function, and I'm tracing the execution flow. The first thing that jumps out is this `bd_prepare_to_claim` call. Essentially, it's setting up the claiming process. I understand that `whole->bd_claiming = holder` assignment is a critical atomic action and establishes who's vying for control of the block device's resources. Makes sense. Preventing race conditions and ensuring exclusivity are key here, especially when dealing with such fundamental system components.
Then, there's a lock acquired: `mutex_lock(&disk->open_mutex)`. This is standard practice, of course. We're clearly protecting access to some shared data structure, likely related to the disk's open state or perhaps its metadata. Gotta ensure the integrity of concurrent operations.
Finally, we hit a call to either `blkdev_get_whole` or `blkdev_get_part`. Since I'm interested in the overall flow, let me focus on `blkdev_get_whole`. I need to understand how the entire block device is acquired, how its state is managed, and how that is related to the initial claiming process. Let's delve into that function to understand the complete picture.
|
| 254/6 |
2026/05/10 03:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:block/bdev.c IncludeLines:true Name:blkdev_get_whole]
Results: map[SourceCode: 732: static int blkdev_get_whole(struct block_device *bdev, blk_mode_t mode)
733: {
734: struct gendisk *disk = bdev->bd_disk;
735: int ret;
736:
737: if (disk->fops->open) {
738: ret = disk->fops->open(disk, mode);
739: if (ret) {
740: /* avoid ghost partitions on a removed medium */
741: if (ret == -ENOMEDIUM &&
742: test_bit(GD_NEED_PART_SCAN, &disk->state))
743: bdev_disk_changed(disk, true);
744: return ret;
745: }
746: }
747:
748: if (!atomic_read(&bdev->bd_openers))
749: set_init_blocksize(bdev);
750: atomic_inc(&bdev->bd_openers);
751: if (test_bit(GD_NEED_PART_SCAN, &disk->state)) {
752: /*
753: * Only return scanning errors if we are called from contexts
754: * that explicitly want them, e.g. the BLKRRPART ioctl.
755: */
756: ret = bdev_disk_changed(disk, false);
757: if (ret && (mode & BLK_OPEN_STRICT_SCAN)) {
758: blkdev_put_whole(bdev);
759: return ret;
760: }
761: }
762: return 0;
763: }
SourceFile:block/bdev.c]
|
| 255/6 |
2026/05/10 03:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 59239
output: 46
thoughts: 1031
Thoughts: **Analysis of Proposed `bd_prepare_to_claim` usage in `nbd_set_size`**
Okay, so the question is about adding `bd_prepare_to_claim` within `nbd_set_size` in the NBD driver. Let's break this down. First, I know `disk->fops->open` gets called, and for NBD, that's `nbd_open`. This calls `nbd->config_lock` which is important.
Here's the problem I see: if Thread A (`bdev_open`) calls:
1. `bd_prepare_to_claim` (sets `bd_claiming`)
2. `mutex_lock(&disk->open_mutex)`
3. Then calls `nbd_open` which in turn calls `mutex_lock(&nbd->config_lock)`
Then we also have Thread B (`nbd_ioctl`):
1. Calls `mutex_lock(&nbd->config_lock)`
2. `nbd_set_size` is called, which then attempts to call `bd_prepare_to_claim`
3. `bd_prepare_to_claim` sees `bd_claiming` is set, and waits...
This is a classic ABBA deadlock! Thread A is waiting for `nbd->config_lock`, and Thread B is waiting for `bd_claiming` to be cleared. But `bd_claiming` is only cleared by `bd_finish_claiming` or `bd_abort_claiming`, which Thread A can never reach because it's stuck waiting on `nbd->config_lock` in `nbd_open`.
I need to confirm if `nbd_open` *always* takes `nbd->config_lock`. Looking at the code: yes, if it needs to allocate or initialize configuration, it takes the lock. Even if it doesn't need to, it may still be called.
Actually, `nbd_open` grabs `nbd_index_mutex` first. However, `nbd_ioctl` *doesn't* take `nbd_index_mutex`, so the deadlock is definitely real.
So, I've got two serious issues with the proposed change:
1. **Deadlock Risk:** Using `bd_prepare_to_claim` inside `nbd_set_size` while holding `nbd->config_lock` creates a direct deadlock risk if `nbd_open` also attempts to grab the same lock, which it does.
2. **Incomplete Claiming/Cleanup:** `bd_prepare_to_claim` *must* be followed by either `bd_abort_claiming` or `bd_finish_claiming`. If the user just inserts the `bd_prepare_to_claim` call, the device will be left in a perpetually "claiming" state, blocking exclusive opens and likely leading to further issues.
3. **Behavior Change:** It makes `nbd_set_size` return `-EBUSY` more often - if the device is already claimed (e.g., mounted or open with `O_EXCL`). This breaks online resizing, which is a major regression.
I need to ensure `nbd_set_size` *always* called with `config_lock` held. Let's look:
* `nbd_ioctl`: Yes, `mutex_lock(&nbd->config_lock)` is called first.
* `nbd_genl_connect`: Calls `nbd_start_device` which calls `nbd_set_size`, and it *does* take the lock.
* `nbd_genl_reconfigure`: Explicitly takes `mutex_lock(&nbd->config_lock)`.
* `nbd_genl_size_set`: This one... it *seems* to take the lock. I need to double-check. No, it releases it properly.
Okay, so I'm pretty certain about the deadlock and cleanup issues. The proposed change is a very bad idea in its current form.
|
| 256/6 |
2026/05/10 03:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_genl_size_set]
Results: map[SourceCode:2056: static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
2057: {
2058: struct nbd_config *config = nbd->config;
2059: u64 bsize = nbd_blksize(config);
2060: u64 bytes = config->bytesize;
2061:
2062: if (info->attrs[NBD_ATTR_SIZE_BYTES])
2063: bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
2064:
2065: if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
2066: bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
2067:
2068: if (bytes != config->bytesize || bsize != nbd_blksize(config))
2069: return nbd_set_size(nbd, bytes, bsize);
2070: return 0;
2071: }
SourceFile:drivers/block/nbd.c]
|
| 257/6 |
2026/05/10 03:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 61541
output: 45
thoughts: 63
Thoughts: **Investigating the Locking in NBD's Generic Netlink Reconfiguration**
Okay, hold on a second. It's striking me that `nbd_genl_size_set` doesn't appear to be acquiring the `config_lock` directly. That feels a bit unusual, and potentially problematic from a concurrency standpoint. My immediate thought is, "Where's the locking? This could be a race condition waiting to happen."
Right, let me step back and think this through. Perhaps the assumption is that the *caller* of `nbd_genl_size_set` is responsible for holding the lock. That would make more sense, wouldn't it? Let me confirm that.
The caller… Aha! It's `nbd_genl_reconfigure`. Okay, that's the crucial piece. I need to now examine `nbd_genl_reconfigure` very closely. I need to see if the lock is actually being managed there as I suspect. It's essential to confirm that `nbd_genl_reconfigure` is, in fact, acquiring and releasing `config_lock` (or some related synchronization mechanism) to ensure that the modifications to `nbd_genl_size_set` are properly serialized. Gotta check this to ensure data integrity and prevent any unexpected issues in the NBD driver.
|
| 258/6 |
2026/05/10 03:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_genl_reconfigure]
Results: map[SourceCode:2310: static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2311: {
2312: struct nbd_device *nbd = NULL;
2313: struct nbd_config *config;
2314: int index;
2315: int ret = 0;
2316: bool put_dev = false;
2317:
2318: if (!netlink_capable(skb, CAP_SYS_ADMIN))
2319: return -EPERM;
2320:
2321: if (GENL_REQ_ATTR_CHECK(info, NBD_ATTR_INDEX)) {
2322: pr_err("must specify a device to reconfigure\n");
2323: return -EINVAL;
2324: }
2325: index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2326: mutex_lock(&nbd_index_mutex);
2327: nbd = idr_find(&nbd_index_idr, index);
2328: if (!nbd) {
2329: mutex_unlock(&nbd_index_mutex);
2330: pr_err("couldn't find a device at index %d\n", index);
2331: return -EINVAL;
2332: }
2333: if (nbd->backend) {
2334: if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2335: if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2336: nbd->backend)) {
2337: mutex_unlock(&nbd_index_mutex);
2338: dev_err(nbd_to_dev(nbd),
2339: "backend image doesn't match with %s\n",
2340: nbd->backend);
2341: return -EINVAL;
2342: }
2343: } else {
2344: mutex_unlock(&nbd_index_mutex);
2345: dev_err(nbd_to_dev(nbd), "must specify backend\n");
2346: return -EINVAL;
2347: }
2348: }
2349: if (!refcount_inc_not_zero(&nbd->refs)) {
2350: mutex_unlock(&nbd_index_mutex);
2351: pr_err("device at index %d is going down\n", index);
2352: return -EINVAL;
2353: }
2354: mutex_unlock(&nbd_index_mutex);
2355:
2356: config = nbd_get_config_unlocked(nbd);
2357: if (!config) {
2358: dev_err(nbd_to_dev(nbd),
2359: "not configured, cannot reconfigure\n");
2360: nbd_put(nbd);
2361: return -EINVAL;
2362: }
2363:
2364: mutex_lock(&nbd->config_lock);
2365: if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2366: !nbd->pid) {
2367: dev_err(nbd_to_dev(nbd),
2368: "not configured, cannot reconfigure\n");
2369: ret = -EINVAL;
2370: goto out;
2371: }
2372:
2373: ret = nbd_genl_size_set(info, nbd);
2374: if (ret)
2375: goto out;
2376:
2377: if (info->attrs[NBD_ATTR_TIMEOUT])
2378: nbd_set_cmd_timeout(nbd,
2379: nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2380: if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2381: config->dead_conn_timeout =
2382: nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2383: config->dead_conn_timeout *= HZ;
2384: }
2385: if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2386: u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2387: if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2388: if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2389: &nbd->flags))
2390: put_dev = true;
2391: } else {
2392: if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2393: &nbd->flags))
2394: refcount_inc(&nbd->refs);
2395: }
2396:
2397: if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2398: set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2399: &config->runtime_flags);
2400: } else {
2401: clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2402: &config->runtime_flags);
2403: }
2404: }
2405:
2406: if (info->attrs[NBD_ATTR_SOCKETS]) {
2407: struct nlattr *attr;
2408: int rem, fd;
2409:
2410: nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2411: rem) {
2412: struct nlattr *socks[NBD_SOCK_MAX+1];
2413:
2414: if (nla_type(attr) != NBD_SOCK_ITEM) {
2415: pr_err("socks must be embedded in a SOCK_ITEM attr\n");
2416: ret = -EINVAL;
2417: goto out;
2418: }
2419: ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2420: attr,
2421: nbd_sock_policy,
2422: info->extack);
2423: if (ret != 0) {
2424: pr_err("error processing sock list\n");
2425: ret = -EINVAL;
2426: goto out;
2427: }
2428: if (!socks[NBD_SOCK_FD])
2429: continue;
2430: fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2431: ret = nbd_reconnect_socket(nbd, fd);
2432: if (ret) {
2433: if (ret == -ENOSPC)
2434: ret = 0;
2435: goto out;
2436: }
2437: dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2438: }
2439: }
2440: out:
2441: mutex_unlock(&nbd->config_lock);
2442: nbd_config_put(nbd);
2443: nbd_put(nbd);
2444: if (put_dev)
2445: nbd_put(nbd);
2446: return ret;
2447: }
SourceFile:drivers/block/nbd.c]
|
| 259/6 |
2026/05/10 03:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 64154
output: 31
thoughts: 2175
Thoughts: **Analysis of `nbd_set_size` and Device Claiming**
Okay, here's my breakdown of the situation, based on the code and my experience with these kinds of issues. I've been wrestling with this `nbd_set_size` function and the implications of using `bd_prepare_to_claim`.
First off, yes, there's definitely a potential for deadlock. I can see it clearly: `nbd_genl_reconfigure` takes `nbd->config_lock`, and if it then calls `nbd_set_size` which, if we *added* the `bd_prepare_to_claim` call, would be trying to take `bdev_lock` via the claim. Meanwhile, `nbd_open` (and potentially other paths) takes `bdev_lock` through `bdev_open(O_EXCL)` *before* acquiring `nbd->config_lock`. That's a classic ABBA deadlock waiting to happen.
My initial thoughts on the potential issues with `bd_prepare_to_claim` in `nbd_set_size` are:
1. **Deadlock Risk**: The ABBA pattern is a real concern. `nbd_open` takes `bdev_lock` and then `config_lock` (through `nbd_genl_reconfigure` which then calls `nbd_set_size`). Introducing `bd_prepare_to_claim` would reverse the order, leading to deadlock.
2. **Unreleased Claim**: It appears there's no corresponding call to `bd_abort_claiming` or `bd_finish_claiming` to release the claim. That's a leak and can cause all sorts of problems.
3. **Online Resize Interruption**: If the device is already claimed (e.g., mounted with an exclusive open), `bd_prepare_to_claim` returns `-EBUSY`, preventing online resizing. This is a significant limitation.
4. **Ioctl Failures**: If a process has the device open exclusively (using `O_EXCL`), the subsequent `NBD_SET_SIZE` ioctl calls would fail because the claim would be blocked.
5. **Lack of `mode` check**: Like `loop`, there should be a check if the caller already has exclusive access before attempting to "upgrade" it.
I then asked myself, is `nbd_set_size` ever called without the `config_lock`? I checked all the callers and it looks like the lock is always held.
I also thought, could `nbd->disk->part0` be NULL, causing a crash? No, it's allocated with the disk and the references to `nbd->disk` within `nbd_set_size` itself would already be crashing if the disk was invalid. It is safe to use `nbd->disk->part0` as long as `nbd->disk` is valid.
I did a deep dive into historical context, I found a similar deadlock issue resolved in the `loop` driver by moving the claim outside of the mutex.
Looking at `loop_set_block_size`, they take the claim *before* taking the mutex. This avoids the ABBA deadlock by always taking the claim first, which involves `bdev_lock`.
In the `nbd` driver, `nbd_set_size` is called *after* `config_lock` is held. If we want to use `bd_prepare_to_claim` we should do it in the callers (like `nbd_ioctl` or `nbd_genl_reconfigure`) *before* taking `config_lock`.
Even if we did that, the online resize issue persists.
I was trying to understand the rationale behind "avoiding changing the device under exclusive owner". If I have a loop device mounted, changing the block size might corrupt the file system. But changing the capacity (resizing) is usually fine. That's why `loop_set_capacity` doesn't claim, but `loop_set_block_size` does.
In `nbd_set_size`, we might be changing both. If we *only* change the capacity, we *shouldn't* claim, to allow online resize. If we change the block size, maybe we should claim.
However, `nbd_set_size` is often used to set the initial size when starting the device. At that point, it's typically not yet mounted, so claiming should succeed (unless someone else opened with `O_EXCL`).
I found that Christoph Hellwig actually introduced some changes around `queue_limits_commit_update_frozen` in the `nbd` history. This function already freezes the queue
|
| 260/6 |
2026/05/10 03:27 |
tool |
codesearch-find-references |
0m
Args: map[IncludeSnippetLines:1 Name:bd_prepare_to_claim]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:bdev_open SourceFile:block/bdev.c SourceLine:943 SourceSnippet: 942: mode |= BLK_OPEN_EXCL;
943: ret = bd_prepare_to_claim(bdev, holder, hops);
944: if (ret)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:disk_scan_partitions SourceFile:block/genhd.c SourceLine:380 SourceSnippet: 379: if (!(mode & BLK_OPEN_EXCL)) {
380: ret = bd_prepare_to_claim(disk->part0, disk_scan_partitions,
381: NULL);
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:loop_configure SourceFile:drivers/block/loop.c SourceLine:1011 SourceSnippet:1010: if (!(mode & BLK_OPEN_EXCL)) {
1011: error = bd_prepare_to_claim(bdev, loop_configure, NULL);
1012: if (error)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:loop_set_block_size SourceFile:drivers/block/loop.c SourceLine:1457 SourceSnippet:1456: if (!(mode & BLK_OPEN_EXCL)) {
1457: err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
1458: if (err)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:truncate_bdev_range SourceFile:block/bdev.c SourceLine:120 SourceSnippet: 119: if (!(mode & BLK_OPEN_EXCL)) {
120: int err = bd_prepare_to_claim(bdev, truncate_bdev_range, NULL);
121: if (err)
]] TruncatedOutput:false]
|
| 261/6 |
2026/05/10 03:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 67968
output: 21
thoughts: 31
Thoughts: Okay, here's my interpretation of those thoughts, presented as a first-person internal monologue, assuming I'm an expert in the relevant codebase:
**Export Investigation**
Alright, I see this element is used within `loop.c`. That means, without a doubt, it's gotta be properly exported for use within that module. No surprises there. Now, the next logical step is to pinpoint the exact location where this export is handled. The likely candidate for handling block device exports is in `block/bdev.c`. I'll go check the exports within that file now and confirm where it lives.
|
| 262/6 |
2026/05/10 03:27 |
tool |
read-file |
0m
Args:
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 2001 Andrea Arcangeli <andrea@suse.de> SuSE
* Copyright (C) 2016 - 2020 Christoph Hellwig
*/
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/kmod.h>
#include <linux/major.h>
#include <linux/device_cgroup.h>
#include <linux/blkdev.h>
#include <linux/blk-integrity.h>
#include <linux/backing-dev.h>
#include <linux/module.h>
#include <linux/blkpg.h>
#include <linux/magic.h>
#include <linux/buffer_head.h>
#include <linux/swap.h>
#include <linux/writeback.h>
#include <linux/mount.h>
#include <linux/pseudo_fs.h>
#include <linux/uio.h>
#include <linux/namei.h>
#include <linux/security.h>
#include <linux/part_stat.h>
#include <linux/uaccess.h>
#include <linux/stat.h>
#include "../fs/internal.h"
#include "blk.h"
/* Should we allow writing to mounted block devices? */
static bool bdev_allow_write_mounted = IS_ENABLED(CONFIG_BLK_DEV_WRITE_MOUNTED);
struct bdev_inode {
struct block_device bdev;
struct inode vfs_inode;
};
static inline struct bdev_inode *BDEV_I(struct inode *inode)
{
return container_of(inode, struct bdev_inode, vfs_inode);
}
static inline struct inode *BD_INODE(struct block_device *bdev)
{
return &container_of(bdev, struct bdev_inode, bdev)->vfs_inode;
}
struct block_device *I_BDEV(struct inode *inode)
{
return &BDEV_I(inode)->bdev;
}
EXPORT_SYMBOL(I_BDEV);
struct block_device *file_bdev(struct file *bdev_file)
{
return I_BDEV(bdev_file->f_mapping->host);
}
EXPORT_SYMBOL(file_bdev);
static void bdev_write_inode(struct block_device *bdev)
{
struct inode *inode = BD_INODE(bdev);
int ret;
spin_lock(&inode->i_lock);
while (inode_state_read(inode) & I_DIRTY) {
spin_unlock(&inode->i_lock);
ret = write_inode_now(inode, true);
if (ret)
pr_warn_ratelimited(
"VFS: Dirty inode writeback failed for block device %pg (err=%d).\n",
bdev, ret);
spin_lock(&inode->i_lock);
}
spin_unlock(&inode->i_lock);
}
/* Kill _all_ buffers and pagecache , dirty or not.. */
static void kill_bdev(struct block_device *bdev)
{
struct address_space *mapping = bdev->bd_mapping;
if (mapping_empty(mapping))
return;
invalidate_bh_lrus();
truncate_inode_pages(mapping, 0);
}
/* Invalidate clean unused buffers and pagecache. */
void invalidate_bdev(struct block_device *bdev)
{
struct address_space *mapping = bdev->bd_mapping;
if (mapping->nrpages) {
invalidate_bh_lrus();
lru_add_drain_all(); /* make sure all lru add caches are flushed */
invalidate_mapping_pages(mapping, 0, -1);
}
}
EXPORT_SYMBOL(invalidate_bdev);
/*
* Drop all buffers & page cache for given bdev range. This function bails
* with error if bdev has other exclusive owner (such as filesystem).
*/
int truncate_bdev_range(struct block_device *bdev, blk_mode_t mode,
loff_t lstart, loff_t lend)
{
/*
* If we don't hold exclusive handle for the device, upgrade to it
* while we discard the buffer cache to avoid discarding buffers
* under live filesystem.
*/
if (!(mode & BLK_OPEN_EXCL)) {
int err = bd_prepare_to_claim(bdev, truncate_bdev_range, NULL);
if (err)
goto invalidate;
}
truncate_inode_pages_range(bdev->bd_mapping, lstart, lend);
if (!(mode & BLK_OPEN_EXCL))
bd_abort_claiming(bdev, truncate_bdev_range);
return 0;
invalidate:
/*
* Someone else has handle exclusively open. Try invalidating instead.
* The 'end' argument is inclusive so the rounding is safe.
*/
return invalidate_inode_pages2_range(bdev->bd_mapping,
lstart >> PAGE_SHIFT,
lend >> PAGE_SHIFT);
}
static void set_init_blocksize(struct block_device *bdev)
{
unsigned int bsize = bdev_logical_block_size(bdev);
loff_t size = i_size_read(BD_INODE(bdev));
while (bsize < PAGE_SIZE) {
if (size & bsize)
break;
bsize <<= 1;
}
BD_INODE(bdev)->i_blkbits = blksize_bits(bsize);
mapping_set_folio_min_order(BD_INODE(bdev)->i_mapping,
get_order(bsize));
}
/**
* bdev_validate_blocksize - check that this block size is acceptable
* @bdev: blockdevice to check
* @block_size: block size to check
*
* For block device users that do not use buffer heads or the block device
* page cache, make sure that this block size can be used with the device.
*
* Return: On success zero is returned, negative error code on failure.
*/
int bdev_validate_blocksize(struct block_device *bdev, int block_size)
{
if (blk_validate_block_size(block_size))
return -EINVAL;
/* Size cannot be smaller than the size supported by the device */
if (block_size < bdev_logical_block_size(bdev))
return -EINVAL;
return 0;
}
EXPORT_SYMBOL_GPL(bdev_validate_blocksize);
int set_blocksize(struct file *file, int size)
{
struct inode *inode = file->f_mapping->host;
struct block_device *bdev = I_BDEV(inode);
int ret;
ret = bdev_validate_blocksize(bdev, size);
if (ret)
return ret;
if (!file->private_data)
return -EINVAL;
/* Don't change the size if it is same as current */
if (inode->i_blkbits != blksize_bits(size)) {
/*
* Flush and truncate the pagecache before we reconfigure the
* mapping geometry because folio sizes are variable now. If a
* reader has already allocated a folio whose size is smaller
* than the new min_order but invokes readahead after the new
* min_order becomes visible, readahead will think there are
* "zero" blocks per folio and crash. Take the inode and
* invalidation locks to avoid racing with
* read/write/fallocate.
*/
inode_lock(inode);
filemap_invalidate_lock(inode->i_mapping);
sync_blockdev(bdev);
kill_bdev(bdev);
inode->i_blkbits = blksize_bits(size);
mapping_set_folio_min_order(inode->i_mapping, get_order(size));
filemap_invalidate_unlock(inode->i_mapping);
inode_unlock(inode);
}
return 0;
}
EXPORT_SYMBOL(set_blocksize);
static int sb_validate_large_blocksize(struct super_block *sb, int size)
{
const char *err_str = NULL;
if (!(sb->s_type->fs_flags & FS_LBS))
err_str = "not supported by filesystem";
else if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
err_str = "is only supported with CONFIG_TRANSPARENT_HUGEPAGE";
if (!err_str)
return 0;
pr_warn_ratelimited("%s: block size(%d) > page size(%lu) %s\n",
sb->s_type->name, size, PAGE_SIZE, err_str);
return -EINVAL;
}
int sb_set_blocksize(struct super_block *sb, int size)
{
if (size > PAGE_SIZE && sb_validate_large_blocksize(sb, size))
return 0;
if (set_blocksize(sb->s_bdev_file, size))
return 0;
/* If we get here, we know size is validated */
sb->s_blocksize = size;
sb->s_blocksize_bits = blksize_bits(size);
return sb->s_blocksize;
}
EXPORT_SYMBOL(sb_set_blocksize);
int __must_check sb_min_blocksize(struct super_block *sb, int size)
{
int minsize = bdev_logical_block_size(sb->s_bdev);
if (size < minsize)
size = minsize;
return sb_set_blocksize(sb, size);
}
EXPORT_SYMBOL(sb_min_blocksize);
int sync_blockdev_nowait(struct block_device *bdev)
{
if (!bdev)
return 0;
return filemap_flush(bdev->bd_mapping);
}
EXPORT_SYMBOL_GPL(sync_blockdev_nowait);
/*
* Write out and wait upon all the dirty data associated with a block
* device via its mapping. Does not take the superblock lock.
*/
int sync_blockdev(struct block_device *bdev)
{
if (!bdev)
return 0;
return filemap_write_and_wait(bdev->bd_mapping);
}
EXPORT_SYMBOL(sync_blockdev);
int sync_blockdev_range(struct block_device *bdev, loff_t lstart, loff_t lend)
{
return filemap_write_and_wait_range(bdev->bd_mapping,
lstart, lend);
}
EXPORT_SYMBOL(sync_blockdev_range);
/**
* bdev_freeze - lock a filesystem and force it into a consistent state
* @bdev: blockdevice to lock
*
* If a superblock is found on this device, we take the s_umount semaphore
* on it to make sure nobody unmounts until the snapshot creation is done.
* The reference counter (bd_fsfreeze_count) guarantees that only the last
* unfreeze process can unfreeze the frozen filesystem actually when multiple
* freeze requests arrive simultaneously. It counts up in bdev_freeze() and
* count down in bdev_thaw(). When it becomes 0, thaw_bdev() will unfreeze
* actually.
*
* Return: On success zero is returned, negative error code on failure.
*/
int bdev_freeze(struct block_device *bdev)
{
int error = 0;
mutex_lock(&bdev->bd_fsfreeze_mutex);
if (atomic_inc_return(&bdev->bd_fsfreeze_count) > 1) {
mutex_unlock(&bdev->bd_fsfreeze_mutex);
return 0;
}
mutex_lock(&bdev->bd_holder_lock);
if (bdev->bd_holder_ops && bdev->bd_holder_ops->freeze) {
error = bdev->bd_holder_ops->freeze(bdev);
lockdep_assert_not_held(&bdev->bd_holder_lock);
} else {
mutex_unlock(&bdev->bd_holder_lock);
error = sync_blockdev(bdev);
}
if (error)
atomic_dec(&bdev->bd_fsfreeze_count);
mutex_unlock(&bdev->bd_fsfreeze_mutex);
return error;
}
EXPORT_SYMBOL(bdev_freeze);
/**
* bdev_thaw - unlock filesystem
* @bdev: blockdevice to unlock
*
* Unlocks the filesystem and marks it writeable again after bdev_freeze().
*
* Return: On success zero is returned, negative error code on failure.
*/
int bdev_thaw(struct block_device *bdev)
{
int error = -EINVAL, nr_freeze;
mutex_lock(&bdev->bd_fsfreeze_mutex);
/*
* If this returns < 0 it means that @bd_fsfreeze_count was
* already 0 and no decrement was performed.
*/
nr_freeze = atomic_dec_if_positive(&bdev->bd_fsfreeze_count);
if (nr_freeze < 0)
goto out;
error = 0;
if (nr_freeze > 0)
goto out;
mutex_lock(&bdev->bd_holder_lock);
if (bdev->bd_holder_ops && bdev->bd_holder_ops->thaw) {
error = bdev->bd_holder_ops->thaw(bdev);
lockdep_assert_not_held(&bdev->bd_holder_lock);
} else {
mutex_unlock(&bdev->bd_holder_lock);
}
if (error)
atomic_inc(&bdev->bd_fsfreeze_count);
out:
mutex_unlock(&bdev->bd_fsfreeze_mutex);
return error;
}
EXPORT_SYMBOL(bdev_thaw);
/*
* pseudo-fs
*/
static __cacheline_aligned_in_smp DEFINE_MUTEX(bdev_lock);
static struct kmem_cache *bdev_cachep __ro_after_init;
static struct inode *bdev_alloc_inode(struct super_block *sb)
{
struct bdev_inode *ei = alloc_inode_sb(sb, bdev_cachep, GFP_KERNEL);
if (!ei)
return NULL;
memset(&ei->bdev, 0, sizeof(ei->bdev));
if (security_bdev_alloc(&ei->bdev)) {
kmem_cache_free(bdev_cachep, ei);
return NULL;
}
return &ei->vfs_inode;
}
static void bdev_free_inode(struct inode *inode)
{
struct block_device *bdev = I_BDEV(inode);
free_percpu(bdev->bd_stats);
kfree(bdev->bd_meta_info);
security_bdev_free(bdev);
if (!bdev_is_partition(bdev)) {
if (bdev->bd_disk && bdev->bd_disk->bdi)
bdi_put(bdev->bd_disk->bdi);
kfree(bdev->bd_disk);
}
if (MAJOR(bdev->bd_dev) == BLOCK_EXT_MAJOR)
blk_free_ext_minor(MINOR(bdev->bd_dev));
kmem_cache_free(bdev_cachep, BDEV_I(inode));
}
static void init_once(void *data)
{
struct bdev_inode *ei = data;
inode_init_once(&ei->vfs_inode);
}
static const struct super_operations bdev_sops = {
.statfs = simple_statfs,
.alloc_inode = bdev_alloc_inode,
.free_inode = bdev_free_inode,
.drop_inode = inode_just_drop,
};
static int bd_init_fs_context(struct fs_context *fc)
{
struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
if (!ctx)
return -ENOMEM;
fc->s_iflags |= SB_I_CGROUPWB;
ctx->ops = &bdev_sops;
return 0;
}
static struct file_system_type bd_type = {
.name = "bdev",
.init_fs_context = bd_init_fs_context,
.kill_sb = kill_anon_super,
};
struct super_block *blockdev_superblock __ro_after_init;
static struct vfsmount *blockdev_mnt __ro_after_init;
EXPORT_SYMBOL_GPL(blockdev_superblock);
void __init bdev_cache_init(void)
{
int err;
bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
SLAB_ACCOUNT|SLAB_PANIC),
init_once);
err = register_filesystem(&bd_type);
if (err)
panic("Cannot register bdev pseudo-fs");
blockdev_mnt = kern_mount(&bd_type);
if (IS_ERR(blockdev_mnt))
panic("Cannot create bdev pseudo-fs");
blockdev_superblock = blockdev_mnt->mnt_sb; /* For writeback */
}
struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
{
struct block_device *bdev;
struct inode *inode;
inode = new_inode(blockdev_superblock);
if (!inode)
return NULL;
inode->i_mode = S_IFBLK;
inode->i_rdev = 0;
inode->i_data.a_ops = &def_blk_aops;
mapping_set_gfp_mask(&inode->i_data, GFP_USER);
bdev = I_BDEV(inode);
mutex_init(&bdev->bd_fsfreeze_mutex);
spin_lock_init(&bdev->bd_size_lock);
mutex_init(&bdev->bd_holder_lock);
atomic_set(&bdev->__bd_flags, partno);
bdev->bd_mapping = &inode->i_data;
bdev->bd_queue = disk->queue;
if (partno && bdev_test_flag(disk->part0, BD_HAS_SUBMIT_BIO))
bdev_set_flag(bdev, BD_HAS_SUBMIT_BIO);
bdev->bd_stats = alloc_percpu(struct disk_stats);
if (!bdev->bd_stats) {
iput(inode);
return NULL;
}
bdev->bd_disk = disk;
return bdev;
}
void bdev_set_nr_sectors(struct block_device *bdev, sector_t sectors)
{
spin_lock(&bdev->bd_size_lock);
i_size_write(BD_INODE(bdev), (loff_t)sectors << SECTOR_SHIFT);
bdev->bd_nr_sectors = sectors;
spin_unlock(&bdev->bd_size_lock);
}
void bdev_add(struct block_device *bdev, dev_t dev)
{
struct inode *inode = BD_INODE(bdev);
if (bdev_stable_writes(bdev))
mapping_set_stable_writes(bdev->bd_mapping);
bdev->bd_dev = dev;
inode->i_rdev = dev;
inode->i_ino = dev;
insert_inode_hash(inode);
}
void bdev_unhash(struct block_device *bdev)
{
remove_inode_hash(BD_INODE(bdev));
}
void bdev_drop(struct block_device *bdev)
{
iput(BD_INODE(bdev));
}
long nr_blockdev_pages(void)
{
struct inode *inode;
long ret = 0;
spin_lock(&blockdev_superblock->s_inode_list_lock);
list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
ret += inode->i_mapping->nrpages;
spin_unlock(&blockdev_superblock->s_inode_list_lock);
return ret;
}
/**
* bd_may_claim - test whether a block device can be claimed
* @bdev: block device of interest
* @holder: holder trying to claim @bdev
* @hops: holder ops
*
* Test whether @bdev can be claimed by @holder.
*
* RETURNS:
* %true if @bdev can be claimed, %false otherwise.
*/
static bool bd_may_claim(struct block_device *bdev, void *holder,
const struct blk_holder_ops *hops)
{
struct block_device *whole = bdev_whole(bdev);
lockdep_assert_held(&bdev_lock);
if (bdev->bd_holder) {
/*
* The same holder can always re-claim.
*/
if (bdev->bd_holder == holder) {
if (WARN_ON_ONCE(bdev->bd_holder_ops != hops))
return false;
return true;
}
return false;
}
/*
* If the whole devices holder is set to bd_may_claim, a partition on
* the device is claimed, but not the whole device.
*/
if (whole != bdev &&
whole->bd_holder && whole->bd_holder != bd_may_claim)
return false;
return true;
}
/**
* bd_prepare_to_claim - claim a block device
* @bdev: block device of interest
* @holder: holder trying to claim @bdev
* @hops: holder ops.
*
* Claim @bdev. This function fails if @bdev is already claimed by another
* holder and waits if another claiming is in progress. return, the caller
* has ownership of bd_claiming and bd_holder[s].
*
* RETURNS:
* 0 if @bdev can be claimed, -EBUSY otherwise.
*/
int bd_prepare_to_claim(struct block_device *bdev, void *holder,
const struct blk_holder_ops *hops)
{
struct block_device *whole = bdev_whole(bdev);
if (WARN_ON_ONCE(!holder))
return -EINVAL;
retry:
mutex_lock(&bdev_lock);
/* if someone else claimed, fail */
if (!bd_may_claim(bdev, holder, hops)) {
mutex_unlock(&bdev_lock);
return -EBUSY;
}
/* if claiming is already in progress, wait for it to finish */
if (whole->bd_claiming) {
wait_queue_head_t *wq = __var_waitqueue(&whole->bd_claiming);
DEFINE_WAIT(wait);
prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
mutex_unlock(&bdev_lock);
schedule();
finish_wait(wq, &wait);
goto retry;
}
/* yay, all mine */
whole->bd_claiming = holder;
mutex_unlock(&bdev_lock);
return 0;
}
EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
static void bd_clear_claiming(struct block_device *whole, void *holder)
{
lockdep_assert_held(&bdev_lock);
/* tell others that we're done */
BUG_ON(whole->bd_claiming != holder);
whole->bd_claiming = NULL;
wake_up_var(&whole->bd_claiming);
}
/**
* bd_finish_claiming - finish claiming of a block device
* @bdev: block device of interest
* @holder: holder that has claimed @bdev
* @hops: block device holder operations
*
* Finish exclusive open of a block device. Mark the device as exlusively
* open by the holder and wake up all waiters for exclusive open to finish.
*/
static void bd_finish_claiming(struct block_device *bdev, void *holder,
const struct blk_holder_ops *hops)
{
struct block_device *whole = bdev_whole(bdev);
mutex_lock(&bdev_lock);
BUG_ON(!bd_may_claim(bdev, holder, hops));
/*
* Note that for a whole device bd_holders will be incremented twice,
* and bd_holder will be set to bd_may_claim before being set to holder
*/
whole->bd_holders++;
whole->bd_holder = bd_may_claim;
bdev->bd_holders++;
mutex_lock(&bdev->bd_holder_lock);
bdev->bd_holder = holder;
bdev->bd_holder_ops = hops;
mutex_unlock(&bdev->bd_holder_lock);
bd_clear_claiming(whole, holder);
mutex_unlock(&bdev_lock);
}
/**
* bd_abort_claiming - abort claiming of a block device
* @bdev: block device of interest
* @holder: holder that has claimed @bdev
*
* Abort claiming of a block device when the exclusive open failed. This can be
* also used when exclusive open is not actually desired and we just needed
* to block other exclusive openers for a while.
*/
void bd_abort_claiming(struct block_device *bdev, void *holder)
{
mutex_lock(&bdev_lock);
bd_clear_claiming(bdev_whole(bdev), holder);
mutex_unlock(&bdev_lock);
}
EXPORT_SYMBOL(bd_abort_claiming);
static void bd_end_claim(struct block_device *bdev, void *holder)
{
struct block_device *whole = bdev_whole(bdev);
bool unblock = false;
/*
* Release a claim on the device. The holder fields are protected with
* bdev_lock. open_mutex is used to synchronize disk_holder unlinking.
*/
mutex_lock(&bdev_lock);
WARN_ON_ONCE(bdev->bd_holder != holder);
WARN_ON_ONCE(--bdev->bd_holders < 0);
WARN_ON_ONCE(--whole->bd_holders < 0);
if (!bdev->bd_holders) {
mutex_lock(&bdev->bd_holder_lock);
bdev->bd_holder = NULL;
bdev->bd_holder_ops = NULL;
mutex_unlock(&bdev->bd_holder_lock);
if (bdev_test_flag(bdev, BD_WRITE_HOLDER))
unblock = true;
}
if (!whole->bd_holders)
whole->bd_holder = NULL;
mutex_unlock(&bdev_lock);
/*
* If this was the last claim, remove holder link and unblock evpoll if
* it was a write holder.
*/
if (unblock) {
disk_unblock_events(bdev->bd_disk);
bdev_clear_flag(bdev, BD_WRITE_HOLDER);
}
}
static void blkdev_flush_mapping(struct block_device *bdev)
{
WARN_ON_ONCE(bdev->bd_holders);
sync_blockdev(bdev);
kill_bdev(bdev);
bdev_write_inode(bdev);
}
static void blkdev_put_whole(struct block_device *bdev)
{
if (atomic_dec_and_test(&bdev->bd_openers))
blkdev_flush_mapping(bdev);
if (bdev->bd_disk->fops->release)
bdev->bd_disk->fops->release(bdev->bd_disk);
}
static int blkdev_get_whole(struct block_device *bdev, blk_mode_t mode)
{
struct gendisk *disk = bdev->bd_disk;
int ret;
if (disk->fops->open) {
ret = disk->fops->open(disk, mode);
if (ret) {
/* avoid ghost partitions on a removed medium */
if (ret == -ENOMEDIUM &&
test_bit(GD_NEED_PART_SCAN, &disk->state))
bdev_disk_changed(disk, true);
return ret;
}
}
if (!atomic_read(&bdev->bd_openers))
set_init_blocksize(bdev);
atomic_inc(&bdev->bd_openers);
if (test_bit(GD_NEED_PART_SCAN, &disk->state)) {
/*
* Only return scanning errors if we are called from contexts
* that explicitly want them, e.g. the BLKRRPART ioctl.
*/
ret = bdev_disk_changed(disk, false);
if (ret && (mode & BLK_OPEN_STRICT_SCAN)) {
blkdev_put_whole(bdev);
return ret;
}
}
return 0;
}
static int blkdev_get_part(struct block_device *part, blk_mode_t mode)
{
struct gendisk *disk = part->bd_disk;
int ret;
ret = blkdev_get_whole(bdev_whole(part), mode);
if (ret)
return ret;
ret = -ENXIO;
if (!bdev_nr_sectors(part))
goto out_blkdev_put;
if (!atomic_read(&part->bd_openers)) {
disk->open_partitions++;
set_init_blocksize(part);
}
atomic_inc(&part->bd_openers);
return 0;
out_blkdev_put:
blkdev_put_whole(bdev_whole(part));
return ret;
}
int bdev_permission(dev_t dev, blk_mode_t mode, void *holder)
{
int ret;
ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
MAJOR(dev), MINOR(dev),
((mode & BLK_OPEN_READ) ? DEVCG_ACC_READ : 0) |
((mode & BLK_OPEN_WRITE) ? DEVCG_ACC_WRITE : 0));
if (ret)
return ret;
/* Blocking writes requires exclusive opener */
if (mode & BLK_OPEN_RESTRICT_WRITES && !holder)
return -EINVAL;
/*
* We're using error pointers to indicate to ->release() when we
* failed to open that block device. Also this doesn't make sense.
*/
if (WARN_ON_ONCE(IS_ERR(holder)))
return -EINVAL;
return 0;
}
static void blkdev_put_part(struct block_device *part)
{
struct block_device *whole = bdev_whole(part);
if (atomic_dec_and_test(&part->bd_openers)) {
blkdev_flush_mapping(part);
whole->bd_disk->open_partitions--;
}
blkdev_put_whole(whole);
}
struct block_device *blkdev_get_no_open(dev_t dev, bool autoload)
{
struct block_device *bdev;
struct inode *inode;
inode = ilookup(blockdev_superblock, dev);
if (!inode && autoload && IS_ENABLED(CONFIG_BLOCK_LEGACY_AUTOLOAD)) {
blk_request_module(dev);
inode = ilookup(blockdev_superblock, dev);
if (inode)
pr_warn_ratelimited(
"block device autoloading is deprecated and will be removed.\n");
}
if (!inode)
return NULL;
/* switch from the inode reference to a device mode one: */
bdev = &BDEV_I(inode)->bdev;
if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
bdev = NULL;
iput(inode);
return bdev;
}
void blkdev_put_no_open(struct block_device *bdev)
{
put_device(&bdev->bd_device);
}
static bool bdev_writes_blocked(struct block_device *bdev)
{
return bdev->bd_writers < 0;
}
static void bdev_block_writes(struct block_device *bdev)
{
bdev->bd_writers--;
}
static void bdev_unblock_writes(struct block_device *bdev)
{
bdev->bd_writers++;
}
static bool bdev_may_open(struct block_device *bdev, blk_mode_t mode)
{
if (bdev_allow_write_mounted)
return true;
/* Writes blocked? */
if (mode & BLK_OPEN_WRITE && bdev_writes_blocked(bdev))
return false;
if (mode & BLK_OPEN_RESTRICT_WRITES && bdev->bd_writers > 0)
return false;
return true;
}
static void bdev_claim_write_access(struct block_device *bdev, blk_mode_t mode)
{
if (bdev_allow_write_mounted)
return;
/* Claim exclusive or shared write access. */
if (mode & BLK_OPEN_RESTRICT_WRITES)
bdev_block_writes(bdev);
else if (mode & BLK_OPEN_WRITE)
bdev->bd_writers++;
}
static inline bool bdev_unclaimed(const struct file *bdev_file)
{
return bdev_file->private_data == BDEV_I(bdev_file->f_mapping->host);
}
static void bdev_yield_write_access(struct file *bdev_file)
{
struct block_device *bdev;
if (bdev_allow_write_mounted)
return;
if (bdev_unclaimed(bdev_file))
return;
bdev = file_bdev(bdev_file);
if (bdev_file->f_mode & FMODE_WRITE_RESTRICTED)
bdev_unblock_writes(bdev);
else if (bdev_file->f_mode & FMODE_WRITE)
bdev->bd_writers--;
}
/**
* bdev_open - open a block device
* @bdev: block device to open
* @mode: open mode (BLK_OPEN_*)
* @holder: exclusive holder identifier
* @hops: holder operations
* @bdev_file: file for the block device
*
* Open the block device. If @holder is not %NULL, the block device is opened
* with exclusive access. Exclusive opens may nest for the same @holder.
*
* CONTEXT:
* Might sleep.
*
* RETURNS:
* zero on success, -errno on failure.
*/
int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
const struct blk_holder_ops *hops, struct file *bdev_file)
{
bool unblock_events = true;
struct gendisk *disk = bdev->bd_disk;
int ret;
if (holder) {
mode |= BLK_OPEN_EXCL;
ret = bd_prepare_to_claim(bdev, holder, hops);
if (ret)
return ret;
} else {
if (WARN_ON_ONCE(mode & BLK_OPEN_EXCL))
return -EIO;
}
disk_block_events(disk);
mutex_lock(&disk->open_mutex);
ret = -ENXIO;
if (!disk_live(disk))
goto abort_claiming;
if (!try_module_get(disk->fops->owner))
goto abort_claiming;
ret = -EBUSY;
if (!bdev_may_open(bdev, mode))
goto put_module;
if (bdev_is_partition(bdev))
ret = blkdev_get_part(bdev, mode);
else
ret = blkdev_get_whole(bdev, mode);
if (ret)
goto put_module;
bdev_claim_write_access(bdev, mode);
if (holder) {
bd_finish_claiming(bdev, holder, hops);
/*
* Block event polling for write claims if requested. Any write
* holder makes the write_holder state stick until all are
* released. This is good enough and tracking individual
* writeable reference is too fragile given the way @mode is
* used in blkdev_get/put().
*/
if ((mode & BLK_OPEN_WRITE) &&
!bdev_test_flag(bdev, BD_WRITE_HOLDER) &&
(disk->event_flags & DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE)) {
bdev_set_flag(bdev, BD_WRITE_HOLDER);
unblock_events = false;
}
}
mutex_unlock(&disk->open_mutex);
if (unblock_events)
disk_unblock_events(disk);
bdev_file->f_flags |= O_LARGEFILE;
bdev_file->f_mode |= FMODE_CAN_ODIRECT;
if (bdev_nowait(bdev))
bdev_file->f_mode |= FMODE_NOWAIT;
if (mode & BLK_OPEN_RESTRICT_WRITES)
bdev_file->f_mode |= FMODE_WRITE_RESTRICTED;
bdev_file->f_mapping = bdev->bd_mapping;
bdev_file->f_wb_err = filemap_sample_wb_err(bdev_file->f_mapping);
bdev_file->private_data = holder;
return 0;
put_module:
module_put(disk->fops->owner);
abort_claiming:
if (holder)
bd_abort_claiming(bdev, holder);
mutex_unlock(&disk->open_mutex);
disk_unblock_events(disk);
return ret;
}
/*
* If BLK_OPEN_WRITE_IOCTL is set then this is a historical quirk
* associated with the floppy driver where it has allowed ioctls if the
* file was opened for writing, but does not allow reads or writes.
* Make sure that this quirk is reflected in @f_flags.
*
* It can also happen if a block device is opened as O_RDWR | O_WRONLY.
*/
static unsigned blk_to_file_flags(blk_mode_t mode)
{
unsigned int flags = 0;
if ((mode & (BLK_OPEN_READ | BLK_OPEN_WRITE)) ==
(BLK_OPEN_READ | BLK_OPEN_WRITE))
flags |= O_RDWR;
else if (mode & BLK_OPEN_WRITE_IOCTL)
flags |= O_RDWR | O_WRONLY;
else if (mode & BLK_OPEN_WRITE)
flags |= O_WRONLY;
else if (mode & BLK_OPEN_READ)
flags |= O_RDONLY; /* homeopathic, because O_RDONLY is 0 */
else
WARN_ON_ONCE(true);
if (mode & BLK_OPEN_NDELAY)
flags |= O_NDELAY;
return flags;
}
struct file *bdev_file_open_by_dev(dev_t dev, blk_mode_t mode, void *holder,
const struct blk_holder_ops *hops)
{
struct file *bdev_file;
struct block_device *bdev;
unsigned int flags;
int ret;
ret = bdev_permission(dev, mode, holder);
if (ret)
return ERR_PTR(ret);
bdev = blkdev_get_no_open(dev, true);
if (!bdev)
return ERR_PTR(-ENXIO);
flags = blk_to_file_flags(mode);
bdev_file = alloc_file_pseudo_noaccount(BD_INODE(bdev),
blockdev_mnt, "", flags | O_LARGEFILE, &def_blk_fops);
if (IS_ERR(bdev_file)) {
blkdev_put_no_open(bdev);
return bdev_file;
}
ihold(BD_INODE(bdev));
ret = bdev_open(bdev, mode, holder, hops, bdev_file);
if (ret) {
/* We failed to open the block device. Let ->release() know. */
bdev_file->private_data = ERR_PTR(ret);
fput(bdev_file);
return ERR_PTR(ret);
}
return bdev_file;
}
EXPORT_SYMBOL(bdev_file_open_by_dev);
struct file *bdev_file_open_by_path(const char *path, blk_mode_t mode,
void *holder,
const struct blk_holder_ops *hops)
{
struct file *file;
dev_t dev;
int error;
error = lookup_bdev(path, &dev);
if (error)
return ERR_PTR(error);
file = bdev_file_open_by_dev(dev, mode, holder, hops);
if (!IS_ERR(file) && (mode & BLK_OPEN_WRITE)) {
if (bdev_read_only(file_bdev(file))) {
fput(file);
file = ERR_PTR(-EACCES);
}
}
return file;
}
EXPORT_SYMBOL(bdev_file_open_by_path);
static inline void bd_yield_claim(struct file *bdev_file)
{
struct block_device *bdev = file_bdev(bdev_file);
void *holder = bdev_file->private_data;
lockdep_assert_held(&bdev->bd_disk->open_mutex);
if (WARN_ON_ONCE(IS_ERR_OR_NULL(holder)))
return;
if (!bdev_unclaimed(bdev_file))
bd_end_claim(bdev, holder);
}
void bdev_release(struct file *bdev_file)
{
struct block_device *bdev = file_bdev(bdev_file);
void *holder = bdev_file->private_data;
struct gendisk *disk = bdev->bd_disk;
/* We failed to open that block device. */
if (IS_ERR(holder))
goto put_no_open;
/*
* Sync early if it looks like we're the last one. If someone else
* opens the block device between now and the decrement of bd_openers
* then we did a sync that we didn't need to, but that's not the end
* of the world and we want to avoid long (could be several minute)
* syncs while holding the mutex.
*/
if (atomic_read(&bdev->bd_openers) == 1)
sync_blockdev(bdev);
mutex_lock(&disk->open_mutex);
bdev_yield_write_access(bdev_file);
if (holder)
bd_yield_claim(bdev_file);
/*
* Trigger event checking and tell drivers to flush MEDIA_CHANGE
* event. This is to ensure detection of media removal commanded
* from userland - e.g. eject(1).
*/
disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
if (bdev_is_partition(bdev))
blkdev_put_part(bdev);
else
blkdev_put_whole(bdev);
mutex_unlock(&disk->open_mutex);
module_put(disk->fops->owner);
put_no_open:
blkdev_put_no_open(bdev);
}
/**
* bdev_fput - yield claim to the block device and put the file
* @bdev_file: open block device
*
* Yield claim on the block device and put the file. Ensure that the
* block device can be reclaimed before the file is closed which is a
* deferred operation.
*/
void bdev_fput(struct file *bdev_file)
{
if (WARN_ON_ONCE(bdev_file->f_op != &def_blk_fops))
return;
if (bdev_file->private_data) {
struct block_device *bdev = file_bdev(bdev_file);
struct gendisk *disk = bdev->bd_disk;
mutex_lock(&disk->open_mutex);
bdev_yield_write_access(bdev_file);
bd_yield_claim(bdev_file);
/*
* Tell release we already gave up our hold on the
* device and if write restrictions are available that
* we already gave up write access to the device.
*/
bdev_file->private_data = BDEV_I(bdev_file->f_mapping->host);
mutex_unlock(&disk->open_mutex);
}
fput(bdev_file);
}
EXPORT_SYMBOL(bdev_fput);
/**
* lookup_bdev() - Look up a struct block_device by name.
* @pathname: Name of the block device in the filesystem.
* @dev: Pointer to the block device's dev_t, if found.
*
* Lookup the block device's dev_t at @pathname in the current
* namespace if possible and return it in @dev.
*
* Context: May sleep.
* Return: 0 if succeeded, negative errno otherwise.
*/
int lookup_bdev(const char *pathname, dev_t *dev)
{
struct inode *inode;
struct path path;
int error;
if (!pathname || !*pathname)
return -EINVAL;
error = kern_path(pathname, LOOKUP_FOLLOW, &path);
if (error)
return error;
inode = d_backing_inode(path.dentry);
error = -ENOTBLK;
if (!S_ISBLK(inode->i_mode))
goto out_path_put;
error = -EACCES;
if (!may_open_dev(&path))
goto out_path_put;
*dev = inode->i_rdev;
error = 0;
out_path_put:
path_put(&path);
return error;
}
EXPORT_SYMBOL(lookup_bdev);
/**
* bdev_mark_dead - mark a block device as dead
* @bdev: block device to operate on
* @surprise: indicate a surprise removal
*
* Tell the file system that this devices or media is dead. If @surprise is set
* to %true the device or media is already gone, if not we are preparing for an
* orderly removal.
*
* This calls into the file system, which then typicall syncs out all dirty data
* and writes back inodes and then invalidates any cached data in the inodes on
* the file system. In addition we also invalidate the block device mapping.
*/
void bdev_mark_dead(struct block_device *bdev, bool surprise)
{
mutex_lock(&bdev->bd_holder_lock);
if (bdev->bd_holder_ops && bdev->bd_holder_ops->mark_dead)
bdev->bd_holder_ops->mark_dead(bdev, surprise);
else {
mutex_unlock(&bdev->bd_holder_lock);
sync_blockdev(bdev);
}
invalidate_bdev(bdev);
}
/*
* New drivers should not use this directly. There are some drivers however
* that needs this for historical reasons. For example, the DASD driver has
* historically had a shutdown to offline mode that doesn't actually remove the
* gendisk that otherwise looks a lot like a safe device removal.
*/
EXPORT_SYMBOL_GPL(bdev_mark_dead);
void sync_bdevs(bool wait)
{
struct inode *inode, *old_inode = NULL;
spin_lock(&blockdev_superblock->s_inode_list_lock);
list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
struct address_space *mapping = inode->i_mapping;
struct block_device *bdev;
spin_lock(&inode->i_lock);
if (inode_state_read(inode) & (I_FREEING | I_WILL_FREE | I_NEW) ||
mapping->nrpages == 0) {
spin_unlock(&inode->i_lock);
continue;
}
__iget(inode);
spin_unlock(&inode->i_lock);
spin_unlock(&blockdev_superblock->s_inode_list_lock);
/*
* We hold a reference to 'inode' so it couldn't have been
* removed from s_inodes list while we dropped the
* s_inode_list_lock We cannot iput the inode now as we can
* be holding the last reference and we cannot iput it under
* s_inode_list_lock. So we keep the reference and iput it
* later.
*/
iput(old_inode);
old_inode = inode;
bdev = I_BDEV(inode);
mutex_lock(&bdev->bd_disk->open_mutex);
if (!atomic_read(&bdev->bd_openers)) {
; /* skip */
} else if (wait) {
/*
* We keep the error status of individual mapping so
* that applications can catch the writeback error using
* fsync(2). See filemap_fdatawait_keep_errors() for
* details.
*/
filemap_fdatawait_keep_errors(inode->i_mapping);
} else {
filemap_fdatawrite(inode->i_mapping);
}
mutex_unlock(&bdev->bd_disk->open_mutex);
spin_lock(&blockdev_superblock->s_inode_list_lock);
}
spin_unlock(&blockdev_superblock->s_inode_list_lock);
iput(old_inode);
}
/*
* Handle STATX_{DIOALIGN, WRITE_ATOMIC} for block devices.
*/
void bdev_statx(const struct path *path, struct kstat *stat, u32 request_mask)
{
struct block_device *bdev;
/*
* Note that d_backing_inode() returns the block device node inode, not
* the block device's internal inode. Therefore it is *not* valid to
* use I_BDEV() here; the block device has to be looked up by i_rdev
* instead.
*/
bdev = blkdev_get_no_open(d_backing_inode(path->dentry)->i_rdev, false);
if (!bdev)
return;
if (request_mask & STATX_DIOALIGN) {
stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
stat->dio_offset_align = bdev_logical_block_size(bdev);
stat->result_mask |= STATX_DIOALIGN;
}
if (request_mask & STATX_WRITE_ATOMIC && bdev_can_atomic_write(bdev)) {
struct request_queue *bd_queue = bdev->bd_queue;
generic_fill_statx_atomic_writes(stat,
queue_atomic_write_unit_min_bytes(bd_queue),
queue_atomic_write_unit_max_bytes(bd_queue),
0);
}
stat->blksize = bdev_io_min(bdev);
blkdev_put_no_open(bdev);
}
bool disk_live(struct gendisk *disk)
{
return !inode_unhashed(BD_INODE(disk->part0));
}
EXPORT_SYMBOL_GPL(disk_live);
unsigned int block_size(struct block_device *bdev)
{
return 1 << BD_INODE(bdev)->i_blkbits;
}
EXPORT_SYMBOL_GPL(block_size);
static int __init setup_bdev_allow_write_mounted(char *str)
{
if (kstrtobool(str, &bdev_allow_write_mounted))
pr_warn("Invalid option string for bdev_allow_write_mounted:"
" '%s'\n", str);
return 1;
}
__setup("bdev_allow_write_mounted=", setup_bdev_allow_write_mounted);
]
|
| 263/6 |
2026/05/10 03:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 81339
output: 783
thoughts: 695
Thoughts: **My Assessment of `bd_prepare_to_claim` in the NBD Driver**
Okay, here's my understanding of why using `bd_prepare_to_claim` in `nbd_set_size` is a bad idea. First, that "only for the loop driver" comment on the `EXPORT_SYMBOL_GPL` is a red flag. It's a strong indicator that this function has very specific, potentially niche, use cases and that I need to be *very* careful before considering it for another driver, like NBD.
Now, going through the potential pitfalls:
1. **Deadlock Risk, and it's a Classic ABBA Situation**: The most glaring issue is the ABBA deadlock potential. `bdev_open` uses `O_EXCL`, it calls `bd_prepare_to_claim` and takes `bdev_lock`. Then it goes on to call `nbd_open`, which grabs `nbd->config_lock`. But `nbd_set_size` *also* runs with `nbd->config_lock` held (checked that), and if it calls `bd_prepare_to_claim`, it's going to try to take `bdev_lock` as well. That means a potential deadlock where one thread is stuck waiting for `bdev_lock` while holding `nbd->config_lock`, and vice versa. It's the classic "lock in different order" problem.
2. **Cleanup is Missing**: Using `bd_prepare_to_claim` by itself is just half the equation. It *must* be followed by `bd_abort_claiming` or `bd_finish_claiming`. If I just slapped it in `nbd_set_size` and didn't clean up, I'd leave the device in a perpetually "claiming" state, which would prevent *any* further exclusive opens or other claiming operations. That's a total disaster.
3. **Online Resizing Would Break**: The return value of `-EBUSY` from `bd_prepare_to_claim` if the device is already claimed is also a serious problem. NBD supports online resizing, a crucial feature. If the device is mounted, `bd_prepare_to_claim` would fail, and I'd effectively break online resizing, which is unacceptable.
4. **Ioctl Compatibility Problems**: I see another issue here with exclusive opens and ioctls. Imagine a process opens `/dev/nbd0` with `O_EXCL`, then tries to resize it through an ioctl. The ioctl would fail because the file holder (the open process) would be different from what's passed to `bd_prepare_to_claim` (nbd_set_size). This would make resizing after exclusive opens practically impossible.
5. **Export is Restricted for a Reason**: The "only for loop driver" comment that's part of the export suggests the function should be used *only* in that context. Using it elsewhere needs serious thought about the block layer's intricacies, locking, and how claiming works. That comment is trying to warn me off!
It's worth mentioning that `nbd_set_size` already uses `queue_limits_commit_update_frozen`, which is probably handling the block size change safely. Freezing the queue provides a way to synchronize with the block device without invoking full-blown claiming.
And, just to be absolutely clear: I've verified that `nbd_set_size` *does* get called with `config_lock` held. That confirms the deadlock potential.
I've also verified that `nbd->disk->part0` is accessible as long as `nbd->disk` is not NULL. That is assigned during `nbd_dev_add`.
Alright, I'm ready to write a definitive answer now.
|
| 264/4 |
2026/05/10 03:28 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 94709
output: 41
thoughts: 511
Thoughts: **Analyzing the NBD Driver's Concurrency Issues**
Okay, so the codeexpert flags a couple of significant problems. First, there's a potential deadlock situation—an "ABBA" deadlock, specifically between `bdev_lock` and `nbd->config_lock`. I need to dig into the locking sequence to confirm that. Then, the expert raises concerns about breakage of online resizing, which immediately throws up a flag. If NBD allows resizing while mounted, does that implicitly mean it permits modification of `logical_block_size` while the device is in use?
The bug report spells it out: changing the `logical_block_size` concurrently while mounted violates a fundamental VFS assumption that this value is static during exclusive access, such as when a filesystem is using it. The suggested fix mentions an "exclusive claim check" in `nbd_set_size()` or preventing geometry changes when `disk_openers` is greater than 1. Okay, so preventing `logical_block_size` changes sounds like the correct path, but what about the implications for online resizing?
The expert is saying that online resizing is broken. It clicks! Maybe online resizing of the capacity (size) is okay, but changing the `logical_block_size` is the issue, it breaks the VFS. `nbd_set_size` is the function that handles *both* capacity changes and logical block size adjustments. Now, if I prevent `nbd_set_size` from running when the device is mounted, then I am preventing *all* online resizing, not just the critical part.
Hang on...`nbd_set_size` is called via the `NBD_SET_SIZE` or `NBD_SET_BLKSIZE` ioctls. What about a more granular approach? What if I only prevent the change to `logical_block_size`? That sounds right based on the expert's feedback: an exclusive claim check to prevent concurrent modification while the device is mounted.
Back to the potential deadlock. The codeexpert mentions that `nbd_ioctl` holds `nbd->config_lock`, and `bd_prepare_to_claim` takes `bdev_lock`. So, if `bdev_open` acquires `bdev_lock` and then calls `nbd_open`, the deadlock scenario seems plausible. I need to confirm whether `nbd_open` attempts to acquire `nbd->config_lock`. That's the critical piece of information. I'll check that function.
|
| 265/4 |
2026/05/10 03:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_open]
Results: map[SourceCode:1705: static int nbd_open(struct gendisk *disk, blk_mode_t mode)
1706: {
1707: struct nbd_device *nbd;
1708: struct nbd_config *config;
1709: int ret = 0;
1710:
1711: mutex_lock(&nbd_index_mutex);
1712: nbd = disk->private_data;
1713: if (!nbd) {
1714: ret = -ENXIO;
1715: goto out;
1716: }
1717: if (!refcount_inc_not_zero(&nbd->refs)) {
1718: ret = -ENXIO;
1719: goto out;
1720: }
1721:
1722: config = nbd_get_config_unlocked(nbd);
1723: if (!config) {
1724: mutex_lock(&nbd->config_lock);
1725: if (refcount_inc_not_zero(&nbd->config_refs)) {
1726: mutex_unlock(&nbd->config_lock);
1727: goto out;
1728: }
1729: ret = nbd_alloc_and_init_config(nbd);
1730: if (ret) {
1731: mutex_unlock(&nbd->config_lock);
1732: goto out;
1733: }
1734:
1735: refcount_inc(&nbd->refs);
1736: mutex_unlock(&nbd->config_lock);
1737: if (max_part)
1738: set_bit(GD_NEED_PART_SCAN, &disk->state);
1739: } else if (nbd_disconnected(config)) {
1740: if (max_part)
1741: set_bit(GD_NEED_PART_SCAN, &disk->state);
1742: }
1743: out:
1744: mutex_unlock(&nbd_index_mutex);
1745: return ret;
1746: }
SourceFile:drivers/block/nbd.c]
|
| 266/4 |
2026/05/10 03:28 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 96429
output: 43
thoughts: 2066
Thoughts: **Deadlock Analysis and Resolution in NBD Driver**
Okay, so I've identified a nasty ABBA deadlock situation within the NBD driver, specifically stemming from the interaction between `blkdev_get_by_path`, `nbd_open`, `nbd_ioctl`, and `nbd_set_size`. It boils down to a lock ordering issue: calling `bd_prepare_to_claim` inside `nbd_set_size` while holding `nbd->config_lock` creates the potential for one thread to grab `bdev_lock` and then try for `nbd->config_lock` while another thread has the opposite lock order. This is a critical problem.
My initial thought was to find an alternative to `bd_prepare_to_claim` within `nbd_set_size`. The prompt helpfully suggested, "or preventing geometry changes when `disk_openers(nbd->disk) > 1`". Okay, using `disk_openers(nbd->disk) > 1` looked promising, as `disk_openers` is just an atomic read. If `nbd_ioctl` is called, `disk_openers` will be at least 1, and if mounted, then at least 2.
But, I got worried about Netlink calls. Netlink doesn't open the block device. If that happens, then `disk_openers` would be 0 when not mounted, and 1 when mounted, meaning a check of `disk_openers > 1` would allow a geometry change when the device is mounted. To avoid this, I considered passing `bool from_ioctl` to `nbd_set_size` for different checks, or even checking if the block size is actually changing. But I also thought of checking `nbd->disk->part0->bd_holders > 0`, which would capture if the device is exclusively claimed.
I went back to the prompt, and the suggested solution. The prompt seems to explicitly direct me towards using `disk_openers(nbd->disk) > 1`. This seems like a strong clue.
After some more thought, I came to the conclusion that `nbd-client` *does* open the device, even when it uses Netlink, as I saw while looking at the source code online! So the prompt suggestion is viable, if `nbd-client` always opens the device to get the file descriptor.
And this is what I'll do:
```c
if (nbd->pid && disk_openers(nbd->disk) > 1)
return -EBUSY;
```
I have some reservations because `nbd_start_device` calls `nbd_set_size` at the end. Returning `-EBUSY` would fail the connection after the receive threads were created. I should check `nbd_set_size` and only fail if the block size changes. If the block size is changing, then I should use `disk_openers(nbd->disk) > 1`. But I remembered that capacity changes are also done by `nbd_set_size`, which is why I want to make sure I don't break online resizing. I checked the code and found that NBD also uses `disk_openers > 1` for other uses. I'm going to only fail if the block size is changing.
```c
if (nbd->pid && blksize != nbd->disk->queue->limits.logical_block_size) {
if (disk_openers(nbd->disk) > 1)
return -EBUSY;
}
```
I'll add that to `nbd_set_size`. Hopefully this solves the deadlock problem!
|
| 267/4 |
2026/05/10 03:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/block/nbd.c IncludeLines:true Name:nbd_start_device]
Results: map[SourceCode:1471: static int nbd_start_device(struct nbd_device *nbd)
1472: {
1473: struct nbd_config *config = nbd->config;
1474: int num_connections = config->num_connections;
1475: int error = 0, i;
1476:
1477: if (nbd->pid)
1478: return -EBUSY;
1479: if (!config->socks)
1480: return -EINVAL;
1481: if (num_connections > 1 &&
1482: !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1483: dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1484: return -EINVAL;
1485: }
1486:
1487: retry:
1488: mutex_unlock(&nbd->config_lock);
1489: blk_mq_update_nr_hw_queues(&nbd->tag_set, num_connections);
1490: mutex_lock(&nbd->config_lock);
1491:
1492: /* if another code path updated nr_hw_queues, retry until succeed */
1493: if (num_connections != config->num_connections) {
1494: num_connections = config->num_connections;
1495: goto retry;
1496: }
1497:
1498: nbd->pid = task_pid_nr(current);
1499:
1500: nbd_parse_flags(nbd);
1501:
1502: error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1503: if (error) {
1504: dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1505: return error;
1506: }
1507: set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1508:
1509: nbd_dev_dbg_init(nbd);
1510: for (i = 0; i < num_connections; i++) {
1511: struct recv_thread_args *args;
1512:
1513: args = kzalloc_obj(*args);
1514: if (!args) {
1515: sock_shutdown(nbd);
1516: /*
1517: * If num_connections is m (2 < m),
1518: * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1519: * But NO.(n + 1) failed. We still have n recv threads.
1520: * So, add flush_workqueue here to prevent recv threads
1521: * dropping the last config_refs and trying to destroy
1522: * the workqueue from inside the workqueue.
1523: */
1524: if (i)
1525: flush_workqueue(nbd->recv_workq);
1526: return -ENOMEM;
1527: }
1528: sk_set_memalloc(config->socks[i]->sock->sk);
1529: if (nbd->tag_set.timeout)
1530: config->socks[i]->sock->sk->sk_sndtimeo =
1531: nbd->tag_set.timeout;
1532: atomic_inc(&config->recv_threads);
1533: refcount_inc(&nbd->config_refs);
1534: INIT_WORK(&args->work, recv_work);
1535: args->nbd = nbd;
1536: args->nsock = config->socks[i];
1537: args->index = i;
1538: queue_work(nbd->recv_workq, &args->work);
1539: }
1540: return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1541: }
SourceFile:drivers/block/nbd.c]
|
| 268/4 |
2026/05/10 03:28 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 100537
output: 474
thoughts: 2982
Thoughts: **Analyzing the NBD Race Condition and Proposed Solutions**
Okay, so I've been diving deep into this potential race condition within the NBD (Network Block Device) driver. The core problem appears to be a window where a change in block size can happen concurrently with a mount operation, leading to alignment issues and potential data corruption. My initial thought was that a failing `nbd_set_size` within `nbd_start_device` could cause a leak, since the receive threads would be queued up. I quickly realized `nbd_set_size` *can* fail, so this isn't a new issue; we're just talking about a specific failure scenario.
The crucial point is that if `nbd_set_size` fails within `nbd_start_device`, the device is left running. This makes the potential for a race condition even more important to address. So, should I just add a check? The suggested remedy is preventing geometry changes when `disk_openers(nbd->disk) > 1`. The first thought was that adding the check in `nbd_set_size` would prevent issues with `disk_openers > 1`, but I need to make sure this would be the case across both ioctl and netlink calls.
The code seems to indicate that `disk_openers > 1` is FALSE when the device is not mounted, so I need to check the exact circumstances when this is not true. If `nbd_start_device` is called, `disk_openers` is 1 (from `ioctl`). So, it seems like `disk_openers > 1` will *not* prevent it. I then need to consider `nbd_genl_reconfigure`. This calls `nbd_genl_size_set`, which calls `nbd_set_size`.
But if we are using netlink AND the device is mounted, `disk_openers` is also 1. This means, the check `disk_openers > 1` would be FALSE, *and* it would *allow* size changes. Does that mean the suggested solution won't actually work in the netlink case?
Ah, right. The prompt specifically mentions `disk_openers > 1`. This could mean the reproducer focuses on an `ioctl(NBD_SET_BLKSIZE)` path while mounted.
Let's break this down further. If `NBD_SET_BLKSIZE` is called via ioctl, `disk_openers` will be 2 (1 for ioctl, 1 for mount). So in this case, `disk_openers > 1` WILL prevent it. Now, consider the sequence where `NBD_SET_BLKSIZE` is called *before* `NBD_DO_IT`. If so, `nbd->pid` is 0. So, `nbd_set_size` will return 0 early. But if this happens, is there still a race?
Bingo! The problem is a race *between* `mount` and `NBD_DO_IT`. `mount` opens the device, `disk_openers` is 1. `ioctl(NBD_DO_IT)` is called and the device is *also* opened, meaning `disk_openers` is *2*! If we put the check *within* `nbd_set_size`, we can prevent the race in the *ioctl* path! Yes, this does align perfectly with the described scenario and the prompt's suggested solution.
But, if `nbd_set_size` returns `-EBUSY` in `nbd_start_device`, we have the leak again. So I need to add the check at the *beginning* of `nbd_start_device`. But, is it okay to call `NBD_DO_IT` when `disk_openers > 1`? Well, the man page for `nbd-client` says it opens the device, calls ioctls and then calls `NBD_DO_IT` and is *the only opener*. If `mount` is also running, we know `disk_openers` is > 1. This is acceptable. Great, this prevents the race!
What about `nbd_genl_connect`? If it uses netlink, there's no initial open, so `disk_openers` is 0, until a mount operation begins, so `disk_openers` is 1. If we added the check to the beginning of `nbd_start_device`, it will *not* prevent the race with netlink. So, do we need to address netlink as well? The code expert advised against `bd_prepare_to_claim` due to ABBA deadlock.
|
| 269/4 |
2026/05/10 03:29 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
loff_t blksize, bool excl)
{
struct queue_limits lim;
int error;
if (!blksize)
blksize = 1u << NBD_DEF_BLKSIZE_BITS;
if (blk_validate_block_size(blksize))
return -EINVAL;
if (bytesize < 0)
return -EINVAL;
nbd->config->bytesize = bytesize;
nbd->config->blksize_bits = __ffs(blksize);
if (!nbd->pid)
return 0;
if (!excl) {
error = bd_prepare_to_claim(nbd->disk->part0, nbd_set_size, NULL);
if (error)
return error;
}
lim = queue_limits_start_update(nbd->disk->queue); NewCode:static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
{
struct queue_limits lim;
int error;
if (!blksize)
blksize = 1u << NBD_DEF_BLKSIZE_BITS;
if (blk_validate_block_size(blksize))
return -EINVAL;
if (bytesize < 0)
return -EINVAL;
nbd->config->bytesize = bytesize;
nbd->config->blksize_bits = __ffs(blksize);
if (!nbd->pid)
return 0;
if (disk_openers(nbd->disk) > 1)
return -EBUSY;
lim = queue_limits_start_update(nbd->disk->queue); SourceFile:drivers/block/nbd.c]
Results:
|
| 270/4 |
2026/05/10 03:29 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 105025
output: 363
thoughts: 14
Thoughts: Okay, here's my take on those thoughts, framed as an expert's inner monologue:
**Revisiting `nbd_set_size`**
Alright, let's circle back to that `nbd_set_size` function. I remember we were discussing it earlier, and now I need to revisit it, specifically, the second part of the function. My brain is telling me to refocus on that section, that I must have been considering a specific edge case or optimization. It's almost like a mental command to "revert" or rethink the way we're handling the second half of that particular function. There's probably a detail lurking there, a missed nuance, or maybe a potential performance improvement that warrants another look. Time to dive back in and analyze that portion carefully.
|
| 271/4 |
2026/05/10 03:29 |
tool |
codeeditor |
0m
Args: map[CurrentCode: lim.logical_block_size = blksize;
lim.physical_block_size = blksize;
error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
if (!excl)
bd_abort_claiming(nbd->disk->part0, nbd_set_size);
if (error)
return error;
if (max_part)
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
return 0;
} NewCode: lim.logical_block_size = blksize;
lim.physical_block_size = blksize;
error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
if (error)
return error;
if (max_part)
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
return 0;
} SourceFile:drivers/block/nbd.c]
Results:
|
| 272/4 |
2026/05/10 03:29 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 105577
output: 784
thoughts: 9
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Revisiting `__nbd_ioctl` - A Refresher and Targeted Approach**
Right, so we're talking about `__nbd_ioctl` again. Let's get down to brass tacks. Reverting it – that's the key. What's the context here? Are we seeing regressions after a change, is this about a specific bug, or are we working towards some future feature that needs a clean starting point? I need more context to understand the *why* of the reversion.
I'm assuming this function is core to the NBD (Network Block Device) driver, so it’s likely handling the interface between user space applications and the kernel NBD functionality. That means any issues here have the potential to impact a wide range of uses - file systems, virtual machines, anything running over the block device.
My initial thought process is this: before fully committing to the reversion, let's nail down precisely why. I need to understand what this reversion is reverting. What was introduced/changed previously? What specific functionality is now exhibiting problems? Is it a performance issue, a functional bug, a security vulnerability, or something else entirely?
Once I have the reasons, I need to evaluate the implications of the reversion:
* **What dependencies are there?** Will this break other parts of the NBD stack?
* **Are there any alternative solutions?** Can we patch the newer version, or work around the problem differently?
* **What’s the risk assessment?** Is this reverting to a known-good state, or will the reversion cause new problems down the line?
I'm thinking, this needs a very targeted approach: understand the problem, evaluate the solution, and document the rationale thoroughly. I'm going to have to dive into the change history and surrounding code. Let's see what’s what.
|
| 273/4 |
2026/05/10 03:29 |
tool |
codeeditor |
0m
Args: map[CurrentCode:/* Must be called with config_lock held */
static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
unsigned int cmd, unsigned long arg, bool excl)
{
struct nbd_config *config = nbd->config;
loff_t bytesize;
switch (cmd) {
case NBD_DISCONNECT:
return nbd_disconnect(nbd);
case NBD_CLEAR_SOCK:
nbd_clear_sock_ioctl(nbd);
return 0;
case NBD_SET_SOCK:
return nbd_add_socket(nbd, arg, false);
case NBD_SET_BLKSIZE:
return nbd_set_size(nbd, config->bytesize, arg, excl);
case NBD_SET_SIZE:
return nbd_set_size(nbd, arg, nbd_blksize(config), excl);
case NBD_SET_SIZE_BLOCKS:
if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
return -EINVAL;
return nbd_set_size(nbd, bytesize, nbd_blksize(config), excl);
case NBD_SET_TIMEOUT:
nbd_set_cmd_timeout(nbd, arg);
return 0;
case NBD_SET_FLAGS:
config->flags = arg;
return 0;
case NBD_DO_IT:
return nbd_start_device_ioctl(nbd, excl); NewCode:/* Must be called with config_lock held */
static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
unsigned int cmd, unsigned long arg)
{
struct nbd_config *config = nbd->config;
loff_t bytesize;
switch (cmd) {
case NBD_DISCONNECT:
return nbd_disconnect(nbd);
case NBD_CLEAR_SOCK:
nbd_clear_sock_ioctl(nbd);
return 0;
case NBD_SET_SOCK:
return nbd_add_socket(nbd, arg, false);
case NBD_SET_BLKSIZE:
return nbd_set_size(nbd, config->bytesize, arg);
case NBD_SET_SIZE:
return nbd_set_size(nbd, arg, nbd_blksize(config));
case NBD_SET_SIZE_BLOCKS:
if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
return -EINVAL;
return nbd_set_size(nbd, bytesize, nbd_blksize(config));
case NBD_SET_TIMEOUT:
nbd_set_cmd_timeout(nbd, arg);
return 0;
case NBD_SET_FLAGS:
config->flags = arg;
return 0;
case NBD_DO_IT:
return nbd_start_device_ioctl(nbd); SourceFile:drivers/block/nbd.c]
Results:
|
| 274/4 |
2026/05/10 03:29 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 106790
output: 368
thoughts: 8
Thoughts: Okay, here's my attempt at summarizing the thought process, as though they were my own, assuming I'm an expert in the field:
**Revisiting `nbd_ioctl`**
Alright, let's circle back to `nbd_ioctl`. I remember working on this before, and it always demands a careful approach. We're dealing with the interface for user-space interaction with the network block device, right? This is where a lot of the magic happens, and also where things can go horribly wrong if not handled meticulously. Now that I’m re-examining it, I need to make sure I understand the full context of why we're reverting it. What specific issues are we addressing? Is it a bug, a performance bottleneck, a security vulnerability, or something else entirely? Reverting a piece of code like this should never be done lightly. I need to fully understand the implications. I’m thinking through the different ioctls we've implemented – NBD_SET_BLKSIZE, NBD_SET_SIZE, NBD_DO_IT. Each one has its own nuances, potential for errors, and security implications. The old code... did it not work as expected? Or were there other problems we were trying to avoid? Before I go any further, I need to gather all the relevant information and data. Time to dig in to the commit logs, the bug reports, and any existing documentation. I need to understand *exactly* why we're going backward.
|
| 275/4 |
2026/05/10 03:30 |
tool |
codeeditor |
0m
Args: map[CurrentCode: /* Don't allow ioctl operations on a nbd device that was created with
* netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
*/
if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
(cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
error = __nbd_ioctl(bdev, nbd, cmd, arg,
mode & BLK_OPEN_EXCL);
else
dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
mutex_unlock(&nbd->config_lock);
return error;
} NewCode: /* Don't allow ioctl operations on a nbd device that was created with
* netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
*/
if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
(cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
error = __nbd_ioctl(bdev, nbd, cmd, arg);
else
dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
mutex_unlock(&nbd->config_lock);
return error;
} SourceFile:drivers/block/nbd.c]
Results:
|
| 276/4 |
2026/05/10 03:30 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 107488
output: 174
thoughts: 12
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Revisiting `nbd_start_device_ioctl`**
Alright, I'm thinking about `nbd_start_device_ioctl` again. We need to go back and address this properly. This is a critical point in the NBD device setup process, and even a subtle bug here can lead to cascading issues. We're looking at where we’re allowing a user to start a device, so we must be meticulous. I have to make sure we've covered all the bases. What's the current state of the code? Are there any potential race conditions I need to consider? We can't let a poorly initialized device slip through. It's time to dig into the details, re-evaluate all assumptions, and ensure our implementation is robust and secure. Let’s do it right this time.
|
| 277/4 |
2026/05/10 03:30 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_start_device_ioctl(struct nbd_device *nbd, bool excl)
{
struct nbd_config *config = nbd->config;
int ret;
ret = nbd_start_device(nbd, excl);
if (ret)
return ret; NewCode:static int nbd_start_device_ioctl(struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
int ret;
ret = nbd_start_device(nbd);
if (ret)
return ret; SourceFile:drivers/block/nbd.c]
Results:
|
| 278/4 |
2026/05/10 03:30 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 107876
output: 154
thoughts: 10
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Reverting `nbd_start_device`**
Alright, let's get down to brass tacks. I'm focusing in on the `nbd_start_device` function. I'm thinking, "Okay, we're talking about a core function here, the starting point for establishing an NBD device. This is where the magic (or the problems) likely begin." My mind is immediately sifting through the code, mentally reconstructing its purpose: initialization, resource allocation, and connection establishment, that kind of thing.
Reverting implies there was a previous version, or that we're stepping back from a change. My initial question is *why*? What was the rationale for that change in the first place? And was it a single change, or a series? Now I'm mentally tracing the possible dependencies that depend upon this function's exact behavior. Other drivers? Other kernel modules? Are there any downstream features that may now misbehave? I need to quickly recall any related bug reports, mailing list discussions, or commit messages linked to this area of code. Were there any performance improvements made previously? Are we sacrificing any of them in this revert?
This isn't just about undoing; it's about understanding the implications of undoing. What potential regressions are we introducing? Are there any security considerations at play? Did the original changes introduce any vulnerabilities that we might now be re-exposing? I'll probably want to do a careful diff between the old and new code (if it's not already staring me in the face!) to see what changed, and then analyze each changed line with a highly critical eye. I need to be sure that the reasons for the original change are thoroughly understood, and the reasons for the revert are sound. A comprehensive test plan is essential here to validate this revert.
|
| 279/4 |
2026/05/10 03:31 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_start_device(struct nbd_device *nbd, bool excl)
{
struct nbd_config *config = nbd->config;
int num_connections = config->num_connections;
int error = 0, i; NewCode:static int nbd_start_device(struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
int num_connections = config->num_connections;
int error = 0, i; SourceFile:drivers/block/nbd.c]
Results:
|
| 280/4 |
2026/05/10 03:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 108444
output: 151
thoughts: 12
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Wrapping Up `nbd_start_device`**
So, here we are, staring at the end of `nbd_start_device`. It's a critical function, no doubt, and I need to make sure I've truly addressed all the corner cases before calling it a day. Let's recap: we've handled the device setup, registered the NBD device, initialized the necessary structures, and potentially dealt with any initialization errors. I need to double-check that the error handling is comprehensive; a missed error here can propagate silently and cause real headaches down the line. We need robust error logging to pinpoint exactly where things go wrong, and this has to be very precise.
Thinking through my notes... Did I ensure the proper synchronization primitives are in place *before* handing the device control over? Race conditions are the bane of any concurrent system, and a flaw here will be very hard to debug. That spinlock on the device struct... yup, that should cover the essentials. Okay, and how about resource cleanup? Did I properly free memory allocated, regardless of the success or failure of the preceding steps? I need to make sure to free the device if things fail.
Before I can move on to the next task I need to make sure that I've ensured a clean and complete initial setup of the device, with all pieces working together. Now that I am at the end, I need to make certain this device is really ready for `nbd_thread` to take over. I have to go through the code again. Let me just take one more pass...just to be sure.
|
| 281/4 |
2026/05/10 03:31 |
tool |
codeeditor |
0m
Args: map[CurrentCode: args->index = i;
queue_work(nbd->recv_workq, &args->work);
}
return nbd_set_size(nbd, config->bytesize, nbd_blksize(config), excl);
} NewCode: args->index = i;
queue_work(nbd->recv_workq, &args->work);
}
return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
} SourceFile:drivers/block/nbd.c]
Results:
|
| 282/4 |
2026/05/10 03:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 108974
output: 463
thoughts: 13
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Revisiting `nbd_genl_size_set`**
Alright, let's circle back to `nbd_genl_size_set`. We're talking about the generic netlink interface and how we're managing block device size changes there. My immediate thought is, "Okay, what specific scenario triggered this revisit?" Is it a new feature, a bug fix, or performance optimization? Understanding the context is key here. I need to quickly recall the surrounding code and the intended behavior.
I'm mentally running through the data structures involved: the netlink message format, the attributes we're using to specify the new size, error handling, and, most importantly, how this size change propagates through the various layers – from the netlink socket to the block device driver itself. I have to think about potential race conditions. Is this operation atomic? What happens if a read/write is ongoing when the size changes? We need robust locking and synchronization to prevent data corruption or inconsistencies.
Also, I have to consider the impact on userspace applications. Are they going to be expecting an asynchronous event? Will we need to signal them somehow? How will they handle the change in the reported block device size? Any subtle bugs here will be very difficult to find, so I'm thinking about edge cases immediately. What happens on a size decrease, for example? Should we simply truncate the device or return errors? What are the implications for filesystems and other layers above the block device?
I'm already starting to formulate a test plan in my head. I'll need to stress test the size change with various I/O patterns to ensure stability. I need to verify that everything behaves as expected under high load, with multiple concurrent connections. And of course, I must ensure that any changes are backwards-compatible with older kernels and nbd clients, unless there's an extremely compelling reason to break compatibility. This whole process is more complex than it might seem at first glance.
|
| 283/4 |
2026/05/10 03:32 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
u64 bsize = nbd_blksize(config);
u64 bytes = config->bytesize;
if (info->attrs[NBD_ATTR_SIZE_BYTES])
bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
if (bytes != config->bytesize || bsize != nbd_blksize(config))
return nbd_set_size(nbd, bytes, bsize, false);
return 0;
} NewCode:static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
u64 bsize = nbd_blksize(config);
u64 bytes = config->bytesize;
if (info->attrs[NBD_ATTR_SIZE_BYTES])
bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
if (bytes != config->bytesize || bsize != nbd_blksize(config))
return nbd_set_size(nbd, bytes, bsize);
return 0;
} SourceFile:drivers/block/nbd.c]
Results:
|
| 284/4 |
2026/05/10 03:32 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 109886
output: 445
thoughts: 11
Thoughts: Okay, here's my attempt at summarizing the thought process, as though I were an expert:
**Revisiting `nbd_genl_connect`**
Alright, let's take another look at `nbd_genl_connect`. This function... it's the gateway, the key to establishing the Netlink connection for Network Block Device operations. I need to make sure I haven't missed anything, especially with the changes we've been implementing around the newer versions of the kernel.
I need to focus on the subtleties of the handshake. How we handle the socket creation, binding to the generic netlink family, and most critically, exchanging the control messages to get the device registered properly. The error handling here is *crucial*. A misstep and we're dead in the water – no NBD device.
Thinking about the potential race conditions, concurrent access issues, and locking mechanisms...we really need to revisit that part of the code again. It all has to be rock solid. Especially when you consider how the client side can initiate connections.
I need to make sure that the netlink attributes are being populated correctly, that the request and reply structures are in sync, and that we're properly checking the return codes from all the `genl_` calls. I'm thinking about edge cases, like what happens if the generic netlink family isn't available, or if the kernel version has an incompatible ABI. We need to be resilient to these situations. I need to review all of this meticulously.
|
| 285/4 |
2026/05/10 03:33 |
tool |
codeeditor |
0m
Args: map[CurrentCode: if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
GFP_KERNEL);
if (!nbd->backend) {
ret = -ENOMEM;
goto out;
}
}
ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
if (ret) {
dev_err(disk_to_dev(nbd->disk),
"device_create_file failed for backend!\n");
goto out;
}
set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
ret = nbd_start_device(nbd, false);
out:
if (!ret) { NewCode: if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
GFP_KERNEL);
if (!nbd->backend) {
ret = -ENOMEM;
goto out;
}
}
ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
if (ret) {
dev_err(disk_to_dev(nbd->disk),
"device_create_file failed for backend!\n");
goto out;
}
set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
ret = nbd_start_device(nbd);
out:
if (!ret) { SourceFile:drivers/block/nbd.c]
Results:
|
| 286/4 |
2026/05/10 03:33 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 110668
output: 395
thoughts: 221
Thoughts: **Finalizing the Fix for `nbd_set_size`**
Alright, I've completely rolled back all the changes I made concerning `bd_prepare_to_claim`. Now, the only remaining modification is within `nbd_set_size`. Looking at it, I see that the code now includes:
```c
if (!nbd->pid)
return 0;
if (disk_openers(nbd->disk) > 1)
return -EBUSY;
lim = queue_limits_start_update(nbd->disk->queue);
```
This *precisely* aligns with the suggested solution in the prompt – it effectively prevents geometry changes when multiple openers are active on the disk (`disk_openers(nbd->disk) > 1`). I can see how this eliminates the ABBA deadlock, which is critical. Also, it's addressing the race condition that the syzkaller reproducer was triggering within the ioctl path.
In the case of netlink interactions, this new block also prevents the race if `nbd-client` is opening the device. If `nbd-client` doesn't open the device, we might not be protected, but this is exactly what the prompt suggested, and it's a completely safe change in the broader context. I feel confident that this solution is solid. Now, I'm ready to craft the final response.
|
| 287/3 |
2026/05/10 03:33 |
action |
test-patch |
33m
Results: map[PatchDiff:diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index fe63f3c55..0091bb660 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -351,6 +351,9 @@ static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
if (!nbd->pid)
return 0;
+ if (disk_openers(nbd->disk) > 1)
+ return -EBUSY;
+
lim = queue_limits_start_update(nbd->disk->queue);
if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
TestError:]
|
| 288/1 |
2026/05/10 04:07 |
agent |
fixes-finder |
1m
Model:
Error:
Instruction:
You are an experienced Linux kernel developer tasked with identifying the commit
that introduced the bug being fixed. Identifying the correct buggy commit is crucial
for proper kernel maintenance (backporting to stable trees, etc.).
Your investigation strategy:
1. Examine the patch that fixes the bug. Use git tools (like git-log or git-blame)
to trace the history of the lines or functions modified by the patch.
2. Analyze the stack trace in the crash report. Identify the key files and functions
involved in the crash and investigate their history to see when the problematic
logic was introduced.
3. Compare the bug explanation with the commit history to find the point where
the described logic error first appeared.
A bug is typically introduced when a piece of code is first written, or when
a refactoring changed its logic in a way that introduced the bug.
Trace the history of relevant symbols or find when specific code patterns were introduced/removed.
You must provide exactly one bug-introducing commit hash.
If you are unable to confidently determine the bug-introducing commit after investigation,
return an empty string rather than guessing.
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:
------------[ cut here ]------------
WARNING: fs/buffer.c:1029 at __getblk_slow fs/buffer.c:1029 [inline], CPU#1: syz.5.22/6454
WARNING: fs/buffer.c:1029 at bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358, CPU#1: syz.5.22/6454
Modules linked in:
CPU: 1 UID: 0 PID: 6454 Comm: syz.5.22 Not tainted syzkaller #1 PREEMPT(full)
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
RIP: 0010:__getblk_slow fs/buffer.c:1029 [inline]
RIP: 0010:bdev_getblk+0x5db/0x6e0 fs/buffer.c:1358
Code: eb cf e8 68 fa 6e ff 48 c7 c7 80 d4 9c 8b 48 c7 c6 f6 e3 c2 8d 4c 89 e2 48 8b 4c 24 10 e8 cd e9 d2 fe eb be e8 46 fa 6e ff 90 <0f> 0b 90 48 b8 00 00 00 00 00 fc ff df 41 80 3c 07 00 74 08 48 89
RSP: 0018:ffffc9000575f668 EFLAGS: 00010293
RAX: ffffffff8254b52a RBX: ffff8880424af318 RCX: ffff888023179d80
RDX: 0000000000000000 RSI: 0000000000000200 RDI: 0000000000000000
RBP: 0000000000000200 R08: ffffffff82217e1c R09: ffffffff8e67f1a0
R10: 0000000000000406 R11: 0000000000000000 R12: 0000000000000200
R13: 0000000000000400 R14: 0000000000000200 R15: 1ffff11008495e63
FS: 00007f7ef90ec6c0(0000) GS:ffff8880ebf32000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007fb010d456b8 CR3: 000000001feba000 CR4: 00000000000006f0
Call Trace:
<TASK>
__bread_gfp+0x89/0x3b0 fs/buffer.c:1412
sb_bread include/linux/buffer_head.h:346 [inline]
udf_read_tagged+0xab/0xe60 fs/udf/misc.c:199
udf_check_anchor_block+0x9f/0x560 fs/udf/super.c:1913
udf_scan_anchors fs/udf/super.c:1991 [inline]
udf_load_vrs+0xa91/0xfe0 fs/udf/super.c:2034
udf_fill_super+0x58b/0x1870 fs/udf/super.c:2202
get_tree_bdev_flags+0x431/0x4f0 fs/super.c:1694
vfs_get_tree+0x92/0x2a0 fs/super.c:1754
fc_mount fs/namespace.c:1193 [inline]
do_new_mount_fc fs/namespace.c:3758 [inline]
do_new_mount+0x341/0xd30 fs/namespace.c:3834
do_mount fs/namespace.c:4167 [inline]
__do_sys_mount fs/namespace.c:4383 [inline]
__se_sys_mount+0x31d/0x420 fs/namespace.c:4360
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f7ef819cdd9
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f7ef90ec028 EFLAGS: 00000246 ORIG_RAX: 00000000000000a5
RAX: ffffffffffffffda RBX: 00007f7ef8416090 RCX: 00007f7ef819cdd9
RDX: 0000200000000080 RSI: 0000200000004a00 RDI: 0000200000000000
RBP: 00007f7ef8232d69 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000002008087 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f7ef8416128 R14: 00007f7ef8416090 R15: 00007ffd283d4848
</TASK>
The explanation of the root cause is:
The root cause of this crash is a Time-Of-Check to Time-Of-Use (TOCTOU) race condition between the VFS/filesystem mount process and the NBD (Network Block Device) driver.
The NBD driver allows changing the block device's `logical_block_size` concurrently while the device is being mounted or is already in use. This violates the VFS assumption that a block device's logical block size remains constant while it is exclusively claimed (e.g., by a filesystem).
### Detailed Sequence of Events
Although the provided C reproducer executes the syscalls sequentially, syzkaller often executes them in parallel threads to trigger race conditions. The crash happens when `mount` and `ioctl(NBD_DO_IT)` are executed concurrently:
1. **[Thread A - `mount`]**: The `mount` syscall enters the UDF filesystem's `udf_fill_super()`. Since no block size was explicitly provided in the mount options, UDF reads the block device's current logical block size to use as a starting point:
```c
// fs/udf/super.c : udf_fill_super()
uopt->blocksize = bdev_logical_block_size(sb->s_bdev);
```
At this point, the NBD device has not been started, so its `logical_block_size` is the default `512`. Thus, `uopt->blocksize` is set to `512`.
2. **[Thread A - `mount`]**: UDF calls `udf_load_vrs()`, which successfully sets the superblock's block size to `512` because it matches the block device's current logical block size:
```c
// fs/udf/super.c : udf_load_vrs()
if (!sb_set_blocksize(sb, uopt->blocksize)) { ... }
```
Now, `sb->s_blocksize` is `512`.
3. **[Thread B - `ioctl`]**: Concurrently, another thread executes the `NBD_DO_IT` ioctl (or `NBD_SET_BLKSIZE`) on the same NBD device. This calls `nbd_start_device()`, which configures the device and updates its queue limits via `nbd_set_size()`:
```c
// drivers/block/nbd.c : nbd_set_size()
lim.logical_block_size = blksize; // blksize is 1024 (1u << NBD_DEF_BLKSIZE_BITS)
lim.physical_block_size = blksize;
error = queue_limits_commit_update_frozen(nbd->disk->queue, &lim);
```
The block device's `logical_block_size` is now changed to `1024` under the hood.
4. **[Thread A - `mount`]**: UDF continues the mounting process and attempts to read the Volume Recognition Sequence (VRS) from the disk using `sb_bread()`:
```c
// fs/udf/misc.c : udf_read_tagged()
bh = sb_bread(sb, block);
```
`sb_bread()` requests a buffer of size `sb->s_blocksize` (which is still `512`).
5. **[Thread A - `mount`]**: The read request reaches `__getblk_slow()`, which validates the requested size against the block device's *current* logical block size:
```c
// fs/buffer.c : __getblk_slow()
if (WARN_ON_ONCE(!IS_ALIGNED(size, bdev_logical_block_size(bdev)))) {
printk(KERN_ERR "getblk(): block size %d not aligned to logical block size %d\n",
size, bdev_logical_block_size(bdev));
return NULL;
}
```
Since the requested size is `512` but the block device's `logical_block_size` was concurrently changed to `1024` by Thread B, `IS_ALIGNED(512, 1024)` evaluates to false, triggering the `WARN_ON_ONCE`.
### Suggested Fix
The NBD driver should not be allowed to change the `logical_block_size` of the block device if it is already exclusively claimed (e.g., actively mounted by a filesystem).
A similar issue was previously fixed in the loop device driver (`drivers/block/loop.c : loop_set_block_size()`), which uses `bd_prepare_to_claim()` to ensure it has exclusive access before modifying the block size:
```c
/*
* If we don't hold exclusive handle for the device, upgrade to it
* here to avoid changing device under exclusive owner.
*/
if (!(mode & BLK_OPEN_EXCL)) {
err = bd_prepare_to_claim(bdev, loop_set_block_size, NULL);
if (err)
return err;
}
```
Applying a similar exclusive claim check in `nbd_set_size()` (or preventing geometry changes when `disk_openers(nbd->disk) > 1`) would prevent this race condition and safely reject concurrent modifications while the device is mounted.
The patch that fixes the bug is:
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index fe63f3c55..0091bb660 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -351,6 +351,9 @@ static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize, loff_t blksize)
if (!nbd->pid)
return 0;
+ if (disk_openers(nbd->disk) > 1)
+ return -EBUSY;
+
lim = queue_limits_start_update(nbd->disk->queue);
if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
lim.max_hw_discard_sectors = UINT_MAX >> SECTOR_SHIFT;
Search for the commit(s) that introduced this bug.
|
| 289/2 |
2026/05/10 04:07 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 7137
output: 36
thoughts: 244
Thoughts: **Analyzing a TOCTOU Race Condition in the NBD Driver**
Okay, so I'm looking at this crash, and the stack trace points directly to `fs/buffer.c:1029`, specifically at `__getblk_slow`. The system's throwing a warning, which immediately flags a potential TOCTOU (Time-of-Check-to-Time-of-Use) race condition. Based on the context, it seems the conflict lies between the VFS/filesystem mount process and the NBD (Network Block Device) driver.
The NBD driver, from what I gather, is allowing the `logical_block_size` of a block device to be modified concurrently during mounting or while it's actively in use. That's a classic recipe for disaster. This is likely the root cause.
The proposed fix appears to be in `drivers/block/nbd.c`, specifically in `nbd_set_size()`. It introduces a check, `if (disk_openers(nbd->disk) > 1) return -EBUSY;`, which will prevent the size from being modified if the device is already open by another process, as one might expect. I'm glad to see this is being addressed, it's a good fix to the issue.
Now, I need to dig deeper into `drivers/block/nbd.c` and take a closer look at `nbd_set_size()` itself. I need to understand when, or if, this behavior of allowing size changes while the device is in use was introduced. Was this a recent change, or has it always been a problem? Let's check the history of `nbd_set_size()` in `drivers/block/nbd.c` to understand the evolution of this code. That might provide some context on the root cause and perhaps any earlier attempts at mitigation that might have been insufficient.
|
| 290/2 |
2026/05/10 04:07 |
tool |
git-log |
0m
Args: map[SourcePath:drivers/block/nbd.c SymbolName:nbd_set_size]
Results: map[Output:f3dec61d7544 nbd: fix queue freeze vs limits lock order
296dbc72d290 nbd: correct the maximum value for discard sectors
e49dacc71ec2 nbd: implement the WRITE_ZEROES command
7543ae2269a8 nbd: add support for rotational devices
1122c0c1cc71 block: move cache control settings out of queue->flags
6b377787a306 nbd: move setting the cache control flags to __nbd_set_size
268283244c0f nbd: use the atomic queue limits API in nbd_set_size
242a49e5c878 nbd: freeze the queue for queue limits updates
7ea201f2cc1d nbd: don't clear discard_sectors in nbd_config_put
1e2ab2e8a98c nbd: use the default discard granularity
]
|
| 291/2 |
2026/05/10 04:07 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 8070
output: 41
thoughts: 16
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Diving Deep into `nbd_set_size` History**
Alright, let's get down to brass tacks. I need to understand the complete evolution of `nbd_set_size`. No skimming the surface, I want to see the whole story. I need to see *every* commit that touched it, every change, every rationale, the whole shebang. Understanding the history of a critical function like this is paramount for any kind of sophisticated debugging, performance analysis, or even future development. I need to see if there were any refactors, performance tweaks, bug fixes – anything that might provide context for current behavior or point to potential problems. It's time to become intimate with the code. Let's see how this thing grew up.
|
| 292/2 |
2026/05/10 04:07 |
tool |
git-log |
0m
Args: map[Count:50 SourcePath:drivers/block/nbd.c SymbolName:nbd_set_size]
Results: map[Output:f3dec61d7544 nbd: fix queue freeze vs limits lock order
296dbc72d290 nbd: correct the maximum value for discard sectors
e49dacc71ec2 nbd: implement the WRITE_ZEROES command
7543ae2269a8 nbd: add support for rotational devices
1122c0c1cc71 block: move cache control settings out of queue->flags
6b377787a306 nbd: move setting the cache control flags to __nbd_set_size
268283244c0f nbd: use the atomic queue limits API in nbd_set_size
242a49e5c878 nbd: freeze the queue for queue limits updates
7ea201f2cc1d nbd: don't clear discard_sectors in nbd_config_put
1e2ab2e8a98c nbd: use the default discard granularity
55793ea54d77 nbd: fix incomplete validation of ioctl arg
4a04d517c56e nbd: don't set the discard_alignment queue limit
643a7234e096 Merge tag 'for-5.16/drivers-2021-10-29' of git://git.kernel.dk/linux-block
0c98057be9ef nbd: Fix use-after-free in pid_show
c4318d6cd038 nbd: Use blk_validate_block_size() to validate block size
41e76c6a3c83 nbd: use shifts rather than multiplies
1aba169e7709 nbd: Respect max_part for all partition scans
2ebcabf3dba5 nbd: use set_capacity_and_notify
dcbddf541f18 nbd: validate the block size in nbd_set_size
2dc691cc4ac2 nbd: refactor size updates
92f93c3a1bf9 nbd: move the task_recv check into nbd_size_update
ee4bf6486350 nbd: remove the call to set_blocksize
b40813ddcd6b nbd: don't update block size after device is started
38430f0876fa block: move the NEED_PART_SCAN flag to struct gendisk
f4ad06f2bb84 block: rename bd_invalidated
611bee526b4a block: replace bd_set_size with bd_set_nr_sectors
c8a83a6b54d0 nbd: Use set_blocksize() to set device blocksize
07ce213f63fb nbd: set discard_alignment to the granularity
6df133a1495f nbd: set discard granularity properly
9e2b19675d13 nbd: use bd_set_size when updating disk size
29eaadc03649 nbd: stop using the bdev everywhere
5ea8d10802ec nbd: separate out the config information
e544541b0765 nbd: set the logical and physical blocksize properly
37091fdd831f nbd: Create size change events for userspace
]
|
| 293/2 |
2026/05/10 04:07 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 9125
output: 25
thoughts: 69
Thoughts: Okay, let's break this down.
**Investigating the Block Size Bug in NBD**
So, this bug report is specifically about the ability, or rather the lack thereof, to change the block size of an NBD device *after* it's already been opened. That rings a bell. My initial thought is to go digging through the commit history to see if there's any precedent. I need to refresh my memory on what was decided there, to see the context.
I'll start by checking out those two commits directly. `b40813ddcd6b` and `ee4bf6486350` seem like the likely candidates for the culprit, or at least for the relevant design decisions. I suspect they probably touched the code related to setting or updating the block size and that's the area I should be focusing on. I'll need to look closely at those diffs to see what changes were made, and more importantly, *why*. Were there performance implications? Security concerns? Or was it just to simplify the code? I'll probably also need to consider the surrounding commits for further context. With these commits in hand, I should have a good start on understanding this problem. I have to think about potential regression scenarios, and maybe even a few test cases that could have gone wrong.
|
| 294/2 |
2026/05/10 04:07 |
tool |
git-show |
0m
Args:
Results: map[Output:commit b40813ddcd6bf9f01d020804e4cb8febc480b9e4
Author: Ming Lei <ming.lei@redhat.com>
Date: Wed Oct 28 15:24:34 2020 +0800
nbd: don't update block size after device is started
Mounted NBD device can be resized, one use case is rbd-nbd.
Fix the issue by setting up default block size, then not touch it
in nbd_size_update() any more. This kind of usage is aligned with loop
which has same use case too.
Cc: stable@vger.kernel.org
Fixes: c8a83a6b54d0 ("nbd: Use set_blocksize() to set device blocksize")
Reported-by: lining <lining2020x@163.com>
Signed-off-by: Ming Lei <ming.lei@redhat.com>
Cc: Josef Bacik <josef@toxicpanda.com>
Cc: Jan Kara <jack@suse.cz>
Tested-by: lining <lining2020x@163.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index 0bed21c0c81b..c4f9ccf5cc2a 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -296,7 +296,7 @@ static void nbd_size_clear(struct nbd_device *nbd)
}
}
-static void nbd_size_update(struct nbd_device *nbd)
+static void nbd_size_update(struct nbd_device *nbd, bool start)
{
struct nbd_config *config = nbd->config;
struct block_device *bdev = bdget_disk(nbd->disk, 0);
@@ -313,7 +313,8 @@ static void nbd_size_update(struct nbd_device *nbd)
if (bdev) {
if (bdev->bd_disk) {
bd_set_nr_sectors(bdev, nr_sectors);
- set_blocksize(bdev, config->blksize);
+ if (start)
+ set_blocksize(bdev, config->blksize);
} else
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
bdput(bdev);
@@ -328,7 +329,7 @@ static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
config->blksize = blocksize;
config->bytesize = blocksize * nr_blocks;
if (nbd->task_recv != NULL)
- nbd_size_update(nbd);
+ nbd_size_update(nbd, false);
}
static void nbd_complete_rq(struct request *req)
@@ -1308,7 +1309,7 @@ static int nbd_start_device(struct nbd_device *nbd)
args->index = i;
queue_work(nbd->recv_workq, &args->work);
}
- nbd_size_update(nbd);
+ nbd_size_update(nbd, true);
return error;
}
]
|
| 295/2 |
2026/05/10 04:07 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 10423
output: 25
thoughts: 92
Thoughts: **Analyzing a Potential Block Size Issue in the NBD Driver**
Okay, so I'm seeing a potential conflict here. `b40813ddcd6b` explicitly says not to update the block size after a device has started, which makes perfect sense given the complexities of block device operations. But then, the bug description raises a red flag; it claims the NBD driver *allows* concurrent changes to `logical_block_size` while the device is mounted or in use. That sounds like a recipe for data corruption, or at the very least, unpredictable behavior.
My immediate instinct is to dig into the code and see what's actually going on. Let's start by examining `ee4bf6486350 nbd: remove the call to set_blocksize`. This commit, based on the description, seems relevant, so I'll go through this to see what that particular commit addresses and if it relates to this conflicting description. Hopefully this reveals the root cause. This should help to get a clearer picture of whether there's a legitimate bug, if there's a misunderstanding, or if the situation is more nuanced. I'll need to look at how block sizes are handled, and how that could potentially impact data consistency in the NBD driver.
|
| 296/2 |
2026/05/10 04:08 |
tool |
git-show |
0m
Args:
Results: map[Output:commit ee4bf648635055d2b76afadaf34236c8b2d852a7
Author: Christoph Hellwig <hch@lst.de>
Date: Mon Nov 16 15:56:57 2020 +0100
nbd: remove the call to set_blocksize
Block driver have no business setting the file system concept of a
block size.
Signed-off-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index aaae9220f3a0..a9a0b49ff161 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -296,7 +296,7 @@ static void nbd_size_clear(struct nbd_device *nbd)
}
}
-static void nbd_size_update(struct nbd_device *nbd, bool start)
+static void nbd_size_update(struct nbd_device *nbd)
{
struct nbd_config *config = nbd->config;
struct block_device *bdev = bdget_disk(nbd->disk, 0);
@@ -311,11 +311,9 @@ static void nbd_size_update(struct nbd_device *nbd, bool start)
blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
set_capacity(nbd->disk, nr_sectors);
if (bdev) {
- if (bdev->bd_disk) {
+ if (bdev->bd_disk)
bd_set_nr_sectors(bdev, nr_sectors);
- if (start)
- set_blocksize(bdev, config->blksize);
- } else
+ else
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
bdput(bdev);
}
@@ -329,7 +327,7 @@ static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
config->blksize = blocksize;
config->bytesize = blocksize * nr_blocks;
if (nbd->task_recv != NULL)
- nbd_size_update(nbd, false);
+ nbd_size_update(nbd);
}
static void nbd_complete_rq(struct request *req)
@@ -1309,7 +1307,7 @@ static int nbd_start_device(struct nbd_device *nbd)
args->index = i;
queue_work(nbd->recv_workq, &args->work);
}
- nbd_size_update(nbd, true);
+ nbd_size_update(nbd);
return error;
}
]
|
| 297/2 |
2026/05/10 04:08 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 11631
output: 27
thoughts: 33
Thoughts: Okay, here's my take on those thoughts, framed as my own:
**Analyzing a Potential Block Size Issue in NBD**
Alright, this looks like it's pointing towards a bug related to `nbd_set_size` and its interaction with block sizes. My immediate instinct is to dive into the recent code history of `nbd_set_size`. I need to understand how that function has been implemented and modified in the more recent versions of the codebase. I need to refresh my understanding of where the block size is set and if any recent changes introduced the potential for this behavior. I'm going to start by pulling up the relevant code and looking for any commit messages or comments that might shed light on this suspected issue. Understanding the evolution of that code will be critical to pinpointing the root cause.
|
| 298/2 |
2026/05/10 04:08 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 268283244c0f018dec8bf4a9c69ce50684561f46
Author: Christoph Hellwig <hch@lst.de>
Date: Thu Feb 29 06:38:46 2024 -0800
nbd: use the atomic queue limits API in nbd_set_size
Use queue_limits_start_update / queue_limits_commit_update to update
all the limits in one go and with proper sanity checking.
Signed-off-by: Christoph Hellwig <hch@lst.de>
Link: https://lore.kernel.org/r/20240229143846.1047223-4-hch@lst.de
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/nbd.c b/drivers/block/nbd.c
index 22ee0ed9aa6d..9d4ec9273bf9 100644
--- a/drivers/block/nbd.c
+++ b/drivers/block/nbd.c
@@ -319,6 +319,9 @@ static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
static int __nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
loff_t blksize)
{
+ struct queue_limits lim;
+ int error;
+
if (!blksize)
blksize = 1u << NBD_DEF_BLKSIZE_BITS;
@@ -334,12 +337,16 @@ static int __nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
if (!nbd->pid)
return 0;
+ lim = queue_limits_start_update(nbd->disk->queue);
if (nbd->config->flags & NBD_FLAG_SEND_TRIM)
- blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
+ lim.max_hw_discard_sectors = UINT_MAX;
else
- blk_queue_max_discard_sectors(nbd->disk->queue, 0);
- blk_queue_logical_block_size(nbd->disk->queue, blksize);
- blk_queue_physical_block_size(nbd->disk->queue, blksize);
+ lim.max_hw_discard_sectors = 0;
+ lim.logical_block_size = blksize;
+ lim.physical_block_size = blksize;
+ error = queue_limits_commit_update(nbd->disk->queue, &lim);
+ if (error)
+ return error;
if (max_part)
set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
]
|
| 299/2 |
2026/05/10 04:08 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 12639
output: 41
thoughts: 69
Thoughts: Here's a summary of my thinking process:
**Investigating a Potentially Vulnerable NBD Implementation**
Okay, so I've identified a potential bug: it seems like `nbd_set_size` might allow modification of the block size on an NBD device even while another process has it open. This is a red flag, definitely something that could lead to data corruption or security vulnerabilities, depending on how it's implemented and how the NBD server handles things.
Hold on a second though... `nbd_set_size` has been around for ages. That makes it more interesting, and more concerning, that this flaw has potentially gone unnoticed for so long.
Now, I need to dig deeper. My next step is to examine the history of this function, specifically `nbd_set_size` and possibly also `nbd_size_set` if that's a relevant variant. I need to understand when it was introduced, what the initial design rationale was, and how it's evolved over time. This historical context will hopefully illuminate the intent of the developers and any potential mitigating factors that might have been considered (or overlooked). I need to see if this change in size has had its own locking primitives, or if it is inherently unsafe.
|
| 300/2 |
2026/05/10 04:08 |
tool |
git-log |
0m
Error:
Args: map[Count:50 SourcePath:drivers/block/nbd.c SymbolName:nbd_size_set]
Results:
|