| 0/0 |
2026/09/09 16:22 |
flow |
patching |
3h17m
Results: map[AckedBy:[] Fixes:map[AuthorEmail:fujita.tomonori@lab.ntt.co.jp AuthorName:FUJITA Tomonori Hash:10db10d144c0248f285242f79daf6b9de6b00a62 Title:sg: convert the indirect IO path to use the block layer] KernelBranch:master KernelCommit:df2908090cda368b01ff43709f51890076c56157 KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git PatchDescription:scsi: sg: Validate scatter_elem_sz module parameter
Writing an invalid value such as 0 to
/sys/module/sg/parameters/scatter_elem_sz causes a shift-out-of-bounds bug
during subsequent device operations. When opening a device via sg_open(),
the driver calls sg_build_indirect() to allocate scatter-gather buffers. In
sg_build_indirect(), the code checks if the local variable num is less than
PAGE_SIZE and updates the global scatter_elem_sz and scatter_elem_sz_prev
variables, but fails to update num. As a result, num remains 0 and is
passed to order = get_order(num). Calling get_order(0) is undefined and
underflows to 52 on 64-bit systems, causing ret_sz = 1 << (PAGE_SHIFT +
order) to compute 1 << 64. Shifting a 32-bit int by 64 bits triggers a
UBSAN shift-out-of-bounds warning:
UBSAN: shift-out-of-bounds in drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
</TASK>
Additionally, excessively large values written to scatter_elem_sz can cause
order to exceed MAX_PAGE_ORDER, which can overflow signed 32-bit arithmetic
and trigger warnings in the page allocator. Mutating global variables
scatter_elem_sz and scatter_elem_sz_prev inside the I/O path without
locking also introduces data races between concurrent device accesses.
Fix this by replacing module_param_named() with module_param_cb() for
scatter_elem_sz, similar to def_reserved_size. The setter callback
scatter_elem_sz_set() validates that the input value is within [PAGE_SIZE,
PAGE_SIZE << MAX_PAGE_ORDER], rejecting invalid values with -ERANGE or
-EINVAL at the sysfs boundary. Remove scatter_elem_sz_prev and the runtime
parameter modification from sg_build_indirect(), compute the allocation
order directly from scatter_elem_sz, and simplify the per-element size
calculation using min(rem_sz, ret_sz). PatchDiff:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..4c82fc00d 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,33 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1690,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1894,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
Recipients:[map[Email:James.Bottomley@HansenPartnership.com Name:James E.J. Bottomley To:true] map[Email:dgilbert@interlog.com Name:Doug Gilbert To:true] map[Email:linux-kernel@vger.kernel.org Name: To:false] map[Email:linux-scsi@vger.kernel.org Name: To:true] map[Email:mkp@kernel.org Name:Martin K. Petersen To:true] map[Email:fujita.tomonori@lab.ntt.co.jp Name:FUJITA Tomonori To:true]] ReportedBy:[] ReviewedBy:[] SuggestedBy:[] TestedBy:[]]
|
| 1/1 |
2026/09/09 16:22 |
action |
base-commit-picker |
0m
Results: map[KernelBranch:master KernelCommit:df2908090cda368b01ff43709f51890076c56157 KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git]
|
| 2/1 |
2026/09/09 16:22 |
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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
uint64_t r[1] = {0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffffffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000, /*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=*/0x1000, /*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$auto_kernfs_file_fops_kernfs_internal arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 73 79 73 2f 6d 6f 64 75 6c 65 2f 73 67 2f 70 61 72 61 6d 65 74 65 72 73 2f 73 63 61 74 74 65 72 5f 65 6c 65 6d 5f 73 7a 00} (length 0x2a)
// }
// flags: open_flags = 0x22001 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_kernfs_file_fops_kernfs_internal
memcpy((void*)0x200000000000, "/sys/module/sg/parameters/scatter_elem_sz\000", 42);
res = syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000000000ul, /*flags=O_NOFOLLOW|FASYNC|O_WRONLY*/0x22001, /*mode=*/0);
if (res != -1)
r[0] = res;
// write$auto arguments: [
// fd: fd (resource)
// buf: ptr[in, buffer] {
// buffer: {30 00 a6 cc 0d 91 51 55 9d 49 da 1b ad b1 9e c8 54 74 a8 94 9c 8a e2 c7 63 4f 4d b6 a3 2c 21 6f 9e b0 ad 54 fb 52 a1 59 94 56 5b 38 04 63 df 3a 5d d9 94 26 81 e2 13 8f ea 23 f8 46 bb 4f 4f 5d 65 5b ab 78 6f d9 90 bb f9 cd c0 c9 00 da ac dd 1a dd dd b9 6f 1a ab d5 08 c1 04 7a d0 49 3e 8f 00 e5 1c 2a ed 60 fd 15 88 0f 9a d5 a7 14 0c 7d 3b ab 74 d1 61 6b e5 98 ea e3 7d 10 ab 0c 5f 19 9b 11 b2 35 56 55 4b 93 cd 64 17 e4 cb 41 a5 5b 08 b8 3b 02 74 63 66 06 fb 44 91 ca 47 da 61 3a 6b 5b 72 06 eb f0 c4 cb 10 ae a5 e9 75 9f de 4b a5 8e d6 8f d0 55 56 11 cb dd 81 be de 4c 2f 06 28 1d a5 59 07 c1 e9 28 85 52 96 e4 86 5c 13 a9 1a 26 19 8a 39 82 f0 83 0c f7 eb 00 00 00 00 00 00 00 00 76 92 3c 65 8b 3f 23 61 a3 20 aa 19 de 7d 10 a4 95 02 12 bb 13 eb 3c c8 78 86 c6 12 77 32 75 e5 b0 8f da 88 52 f4 20 40 dc 8e aa f0 7b a8 2c a3 c7 01 5c 03 28 c0 b3 f3 f8 30 65 71 6f 1a e0 c6 d9 cf ab f4 5f f2 ed 59 ff e0 be 82 63 58 5f 26 6f c4 53 87 9a 27 77 18 91 5d cf 17 39 3f 41 67 25 0b 12 86 f0 e2 64 dc aa 0f a8 76 c3 83 89 be 1c 5e 0d fb db 14 8c 43 e9 3e fc f3 1a 2f 99 64 63 41 f4 42 f3 ba 17 ea} (length 0x16b)
// }
// count: intptr = 0xe (8 bytes)
// ]
memcpy((void*)0x200000000200, "... [truncated large byte array] ...", 363);
syscall(__NR_write, /*fd=*/r[0], /*buf=*/0x200000000200ul, /*count=*/0xeul);
// openat$auto_sg_fops_sg arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 73 67 30 00} (length 0x9)
// }
// flags: open_flags = 0xc0482 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_sg_fops_sg
memcpy((void*)0x200000000000, "/dev/sg0\000", 9);
syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000000000ul, /*flags=O_NOATIME|O_EXCL|O_CLOEXEC|O_APPEND|0x2*/0xc0482, /*mode=*/0);
return 0;
}
]
|
| 3/1 |
2026/09/09 16:22 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b]
|
| 4/1 |
2026/09/09 16:22 |
action |
kernel-builder |
19m
Results: map[KernelObj:/app/workdir/cache/build/8dc1dcb09751613ebc027b951dbac5744a1f5e9e]
|
| 5/1 |
2026/09/09 16:41 |
action |
crash-reproducer |
2m
Results: map[OtherCrashReports:<nil> ReproducedBugTitle:UBSAN: shift-out-of-bounds in sg_build_indirect ReproducedCrashReport:------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
ReproducedFaultInjection:]
|
| 6/1 |
2026/09/09 16:44 |
action |
codesearch-prepare |
10m
Results: map[Index:codesearch-index]
|
| 7/1 |
2026/09/09 16:54 |
agent |
debugger |
5m
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.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
uint64_t r[1] = {0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffffffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000, /*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=*/0x1000, /*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$auto_kernfs_file_fops_kernfs_internal arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 73 79 73 2f 6d 6f 64 75 6c 65 2f 73 67 2f 70 61 72 61 6d 65 74 65 72 73 2f 73 63 61 74 74 65 72 5f 65 6c 65 6d 5f 73 7a 00} (length 0x2a)
// }
// flags: open_flags = 0x22001 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_kernfs_file_fops_kernfs_internal
memcpy((void*)0x200000000000, "/sys/module/sg/parameters/scatter_elem_sz\000", 42);
res = syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000000000ul, /*flags=O_NOFOLLOW|FASYNC|O_WRONLY*/0x22001, /*mode=*/0);
if (res != -1)
r[0] = res;
// write$auto arguments: [
// fd: fd (resource)
// buf: ptr[in, buffer] {
// buffer: {30 00 a6 cc 0d 91 51 55 9d 49 da 1b ad b1 9e c8 54 74 a8 94 9c 8a e2 c7 63 4f 4d b6 a3 2c 21 6f 9e b0 ad 54 fb 52 a1 59 94 56 5b 38 04 63 df 3a 5d d9 94 26 81 e2 13 8f ea 23 f8 46 bb 4f 4f 5d 65 5b ab 78 6f d9 90 bb f9 cd c0 c9 00 da ac dd 1a dd dd b9 6f 1a ab d5 08 c1 04 7a d0 49 3e 8f 00 e5 1c 2a ed 60 fd 15 88 0f 9a d5 a7 14 0c 7d 3b ab 74 d1 61 6b e5 98 ea e3 7d 10 ab 0c 5f 19 9b 11 b2 35 56 55 4b 93 cd 64 17 e4 cb 41 a5 5b 08 b8 3b 02 74 63 66 06 fb 44 91 ca 47 da 61 3a 6b 5b 72 06 eb f0 c4 cb 10 ae a5 e9 75 9f de 4b a5 8e d6 8f d0 55 56 11 cb dd 81 be de 4c 2f 06 28 1d a5 59 07 c1 e9 28 85 52 96 e4 86 5c 13 a9 1a 26 19 8a 39 82 f0 83 0c f7 eb 00 00 00 00 00 00 00 00 76 92 3c 65 8b 3f 23 61 a3 20 aa 19 de 7d 10 a4 95 02 12 bb 13 eb 3c c8 78 86 c6 12 77 32 75 e5 b0 8f da 88 52 f4 20 40 dc 8e aa f0 7b a8 2c a3 c7 01 5c 03 28 c0 b3 f3 f8 30 65 71 6f 1a e0 c6 d9 cf ab f4 5f f2 ed 59 ff e0 be 82 63 58 5f 26 6f c4 53 87 9a 27 77 18 91 5d cf 17 39 3f 41 67 25 0b 12 86 f0 e2 64 dc aa 0f a8 76 c3 83 89 be 1c 5e 0d fb db 14 8c 43 e9 3e fc f3 1a 2f 99 64 63 41 f4 42 f3 ba 17 ea} (length 0x16b)
// }
// count: intptr = 0xe (8 bytes)
// ]
memcpy((void*)0x200000000200, "... [truncated large byte array] ...", 363);
syscall(__NR_write, /*fd=*/r[0], /*buf=*/0x200000000200ul, /*count=*/0xeul);
// openat$auto_sg_fops_sg arguments: [
// fd: const = 0xffffffffffffff9c (8 bytes)
// file: ptr[in, buffer] {
// buffer: {2f 64 65 76 2f 73 67 30 00} (length 0x9)
// }
// flags: open_flags = 0xc0482 (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd_sg_fops_sg
memcpy((void*)0x200000000000, "/dev/sg0\000", 9);
syscall(__NR_openat, /*fd=*/0xffffffffffffff9cul, /*file=*/0x200000000000ul, /*flags=O_NOATIME|O_EXCL|O_CLOEXEC|O_APPEND|0x2*/0xc0482, /*mode=*/0);
return 0;
}
Reply: An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
|
| 8/2 |
2026/09/09 16:54 |
llm |
debugger |
0m
Model:
Tokens:
input: 7331
output: 38
thoughts: 551
Thoughts: **Crash Analysis: Shift-Out-of-Bounds in SCSI SG Driver**
Okay, so we have a crash. The UBSAN report indicates a shift-out-of-bounds error, specifically in the `sg.c` driver, line 1887. The error is quite clear: a shift exponent of 64 is too large for a 32-bit integer type. This smells like a classic integer overflow issue. The call trace points directly to `sg_build_indirect`, and further down into functions that are called, like `sg_build_reserve`, and `sg_open`.
The reproducer provides some crucial clues. It modifies `/sys/module/sg/parameters/scatter_elem_sz`, writing "0\0" (or just "0") to this parameter. And *then* it opens `/dev/sg0`. This suggests that the value of `scatter_elem_sz` might be the trigger. I need to understand how `scatter_elem_sz` impacts the shift operation within `sg_build_indirect`, or one of the functions called directly by it. The crash happens when the driver is opened.
My next step is to examine the `sg.c` code around line 1887, focusing on the `sg_build_indirect` function and how it uses the value of `scatter_elem_sz`, with an aim to identify the specific integer shift operation that is causing the overflow. I'll need to figure out what data is being shifted, and how the value from the module parameter is being used in the calculation. A zero value for `scatter_elem_sz` almost certainly points to a division by zero or a zero-based multiplication that’s ending in this shift operation, but I’ll need to confirm that. I know the crash report shows a 32-bit integer that is being passed a shift value of 64, and the module parameter seems to be involved.
|
| 9/2 |
2026/09/09 16:54 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1850 LineCount:100]
Results: map[Contents:1850: return tablesize; /* number of scat_gath elements allocated */
1851: }
1852:
1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
1931: static void
1932: sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
1933: {
1934: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1935: "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
1936: if (schp->pages && schp->sglist_len > 0) {
1937: if (!schp->dio_in_use) {
1938: int k;
1939:
1940: for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
1941: SCSI_LOG_TIMEOUT(5,
1942: sg_printk(KERN_INFO, sfp->parentdp,
1943: "sg_remove_scat: k=%d, pg=0x%p\n",
1944: k, schp->pages[k]));
1945: __free_pages(schp->pages[k], schp->page_order);
1946: }
1947:
1948: kfree(schp->pages);
1949: }
]
|
| 10/2 |
2026/09/09 16:54 |
llm |
debugger |
0m
Model:
Tokens:
input: 10054
output: 37
thoughts: 105
Thoughts: **Debugging a Memory Allocation Issue**
Okay, so I've got a crash, and it's pinpointed to line 1887. The error message is pretty clear: I'm trying to left-shift 1 by an exponent of 64, but the result overflows an `int` on a 32-bit architecture. That's a classic bit-shift problem.
The problem seems to stem from `ret_sz = 1 << (PAGE_SHIFT + order);`. So, `order` must be the culprit. It's derived from `get_order(num)` where `num` is actually `scatter_elem_sz`. Alright, `scatter_elem_sz` must be causing the `order` calculation to return a value that, when added to `PAGE_SHIFT` is too large to represent in an integer. Let's trace back how `scatter_elem_sz` is defined. This is likely a module parameter, so I'll need to figure out what values were passed in. Time to dig into the module parameters and figure out what the user set it to!
|
| 11/2 |
2026/09/09 16:54 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c Name:scatter_elem_sz]
Results: map[SourceCode: 94: static int scatter_elem_sz = SG_SCATTER_SZ;
SourceFile:drivers/scsi/sg.c]
|
| 12/2 |
2026/09/09 16:54 |
llm |
debugger |
0m
Model:
Tokens:
input: 10485
output: 33
thoughts: 19
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating `scatter_elem_sz` Parameter Definitions**
Okay, so I'm diving into this. My initial thought is to quickly ascertain if and where `scatter_elem_sz` is actually defined as a module parameter. I need to understand its scope and potential impact. This is probably the first thing I would check when encountering an unfamiliar variable like this. I'm looking for a formal declaration or assignment that establishes its data type, default value (if any), and possibly even a description of its intended purpose. Understanding this will be crucial before I can make any informed decisions about how it functions or how I might want to modify it. I'll need to know where to find these definitions, and then I can move on to other considerations.
|
| 13/2 |
2026/09/09 16:54 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 14/2 |
2026/09/09 16:54 |
llm |
debugger |
0m
Model:
Tokens:
input: 11734
output: 37
thoughts: 1594
Thoughts: **Analyzing the 'sg' Module Parameter Vulnerability**
Okay, so the reproducer's writing '0' to `/sys/module/sg/parameters/scatter_elem_sz`, and it seems straightforward enough: root can write, it's an integer. The reproducer's actually writing "0\0", but the null terminator gets trimmed off and the module parses "0" as the integer 0 using `kstrtoint`.
Then, `sg_build_indirect` gets called, and it checks if `scatter_elem_sz` has changed since the last time, and updates `scatter_elem_sz_prev`. If the size is less than `PAGE_SIZE`, `scatter_elem_sz` gets set to `PAGE_SIZE`. But wait, what's crucial here is that `num` remains unchanged after this check. The parameter `scatter_elem_sz` is set to page size, but num remains as 0.
So it does the check:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
```
So then `order = get_order(num);` is called where `num` is still 0! This is where things get interesting! `get_order(0)` will result in a 0 for `order`. Now the question is where is `order` used and how does that affect the allocated data structures?
This is a good start. I need to dig deeper into the code that follows to understand how this 0 value of `order` is used, and how the subsequent allocation might be exploited.
|
| 15/2 |
2026/09/09 16:55 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/asm-generic/getorder.h Name:get_order]
Results: map[SourceCode: 10: /**
11: * get_order - Determine the allocation order of a memory size
12: * @size: The size for which to get the order
13: *
14: * Determine the allocation order of a particular sized block of memory. This
15: * is on a logarithmic scale, where:
16: *
17: * 0 -> 2^0 * PAGE_SIZE and below
18: * 1 -> 2^1 * PAGE_SIZE to 2^0 * PAGE_SIZE + 1
19: * 2 -> 2^2 * PAGE_SIZE to 2^1 * PAGE_SIZE + 1
20: * 3 -> 2^3 * PAGE_SIZE to 2^2 * PAGE_SIZE + 1
21: * 4 -> 2^4 * PAGE_SIZE to 2^3 * PAGE_SIZE + 1
22: * ...
23: *
24: * The order returned is used to find the smallest allocation granule required
25: * to hold an object of the specified size.
26: *
27: * The result is undefined if the size is 0.
28: */
29: static __always_inline __attribute_const__ int get_order(unsigned long size)
30: {
31: if (__builtin_constant_p(size)) {
32: if (!size)
33: return BITS_PER_LONG - PAGE_SHIFT;
34:
35: if (size < (1UL << PAGE_SHIFT))
36: return 0;
37:
38: return ilog2((size) - 1) - PAGE_SHIFT + 1;
39: }
40:
41: size--;
42: size >>= PAGE_SHIFT;
43: #if BITS_PER_LONG == 32
44: return fls(size);
45: #else
46: return fls64(size);
47: #endif
48: }
SourceFile:include/asm-generic/getorder.h]
|
| 16/2 |
2026/09/09 16:55 |
llm |
debugger |
0m
Model:
Tokens:
input: 14378
output: 38
thoughts: 908
Thoughts: **Analyzing a Shift-Out-of-Bounds Error in Kernel Code**
Okay, so I'm diving into this kernel code and there's a shift-out-of-bounds error I need to understand. The core of the problem seems to be in a `get_order(0)` call, and I'm seeing this error specifically: "shift exponent 64 is too large for 32-bit type 'int'". Let's break this down step-by-step.
First, I see that if `size` is initially zero, the `--` operator causes it to become a very large unsigned number, `0xffffffffffffffff`. Then the right bit-shift (`>>`) by `PAGE_SHIFT` (which is 12) results in `0x000fffffffffffff`. Since `size` is an `unsigned long`, this shift operation is well-defined. Then `fls64()` is called, and that calculates the most significant bit set in the provided value, which is 52 for `0x000fffffffffffffUL`.
This means `get_order(0)` ends up returning an order of 52. Next, the code calculates `ret_sz = 1 << (PAGE_SHIFT + order);`, and in this case, that's `1 << (12 + 52)`, or `1 << 64`. Here's where the problem arises. Because the literal `1` is an integer, `1 << 64` is an out-of-bounds shift for a 32-bit integer. That's exactly the error message!
Tracing it more carefully, I see that `size` becomes zero, then decrements to `0xffffffffffffffffUL`, shifts to `0x000fffffffffffffUL`, and then `fls64` provides the order of 52.
Now, why is `num` becoming zero in the first place? Ah, it looks like `scatter_elem_sz` controls this. The reproducer writes to `/sys/module/sg/parameters/scatter_elem_sz`, and that's the key. I need to investigate if this can be a negative value. If a negative `num` value is given, it's cast to `unsigned long` when passed to `get_order()`, causing a very large number. When `num < PAGE_SIZE` is true, it sets both `num` and `scatter_elem_sz` to `PAGE_SIZE`, but the original negative value of `num` is unchanged. So, `get_order(num)` could receive this negative, which again results in a large order value.
For example, if `num` is -1, `size` becomes `0xffffffffffffffffUL`, then decrements to `0xfffffffffffffffeUL`, then shifts to `0x000fffffffffffffUL`, and the `fls64` returns 52, which makes `PAGE_SHIFT + order = 64`.
The fix seems to update `num` as well, like this:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
Now, I need to look at `sg_build_indirect` in `drivers/scsi/sg.c` to see how everything fits together.
|
| 17/2 |
2026/09/09 16:55 |
tool |
git-blame |
0m
Args: map[End:1885 File:drivers/scsi/sg.c Start:1875]
Results: map[Output:d6b10348f9397 1875)
6460e75a104d1 1876) num = scatter_elem_sz;
6460e75a104d1 1877) if (unlikely(num != scatter_elem_sz_prev)) {
6460e75a104d1 1878) if (num < PAGE_SIZE) {
6460e75a104d1 1879) scatter_elem_sz = PAGE_SIZE;
6460e75a104d1 1880) scatter_elem_sz_prev = PAGE_SIZE;
6460e75a104d1 1881) } else
6460e75a104d1 1882) scatter_elem_sz_prev = num;
6460e75a104d1 1883) }
10db10d144c02 1884)
10db10d144c02 1885) order = get_order(num);
]
|
| 18/2 |
2026/09/09 16:55 |
llm |
debugger |
0m
Model:
Tokens:
input: 16453
output: 33
thoughts: 111
Thoughts: **Analyzing a Potential Integer Overflow**
Okay, hold on a second. Something isn't right here. If the value of `num` isn't getting properly updated, then the `get_order(num)` function is going to be called with a `num` value of either `0` or something negative. If that happens, and `num` is 0, the code sets `order` to 52. Then, we have this calculation: `ret_sz = 1 << (PAGE_SHIFT + order)`. That translates to `1 << 64`. My gut is telling me this is where the problem lies, it looks like a classic shift-out-of-bounds issue. The compiler probably isn't complaining because its a shift, which doesn't always signal an obvious problem.
Let me take a look through the rest of the code to see if `scatter_elem_sz` is also used elsewhere. I need to make sure I haven't missed a related issue.
|
| 19/2 |
2026/09/09 16:55 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 20/2 |
2026/09/09 16:55 |
llm |
debugger |
0m
Model:
Tokens:
input: 17832
output: 35
thoughts: 1901
Thoughts: **Analysis of Potential Integer Overflow and Undefined Behavior in `sg_build_indirect`**
Okay, let's break this down. My initial thought was centered on the impact of setting `num` to `PAGE_SIZE` within the `sg_build_indirect` function. It seemed straightforward: `get_order(PAGE_SIZE)` returns 0, resulting in `ret_sz` equalling `PAGE_SIZE`, which is perfectly acceptable.
However, the use of `scatter_elem_sz` raises a red flag. Specifically, the initialization in `init_sg`, coupled with its modifiability via sysfs, introduces a vulnerability. I can see the reproducer setting this value to zero via `/sys/module/sg/parameters/scatter_elem_sz`, and root privileges granting write access. This means that, after initialization, the `scatter_elem_sz` parameter could be maliciously set to zero at any time by root.
If `scatter_elem_sz` *is* zero, then the next call to `sg_build_indirect` leads to a cascade of issues. `num` becomes zero. The condition `num < PAGE_SIZE` is met, which sets `scatter_elem_sz` to `PAGE_SIZE` *but* leaves `num` zero. This leads to `get_order(0)`, and since zero is not a compile-time constant, the `fls64` function is called.
This is where things go south. For `num=0`, the calculation within `get_order` yields an `order` of 52. Then, the dangerous line `ret_sz = 1 << (PAGE_SHIFT + order);` comes into play. Since PAGE_SHIFT is 12, this resolves to `1 << 64`. This is a classic integer overflow – undefined behavior in 32-bit `int`s because the left-hand side is a 32-bit `int`.
I checked if 1<<64 was the only issue. I considered the scenario if we set `num` to `PAGE_SIZE` in the buggy path, the program runs correctly because `ret_sz` will be `4096`. However, I am now concerned about any large value for `scatter_elem_sz`. Let's consider another example, setting `scatter_elem_sz = 0x100000000`. Similar to what happened above, `order` will be 20, leading to `ret_sz = 1 << 32`. Again, UB, because the left hand side is a 32-bit `int`.
Now I need to consider an upper bound for `scatter_elem_sz`. Because it's an `int` parameter, it can be up to `INT_MAX`. If `scatter_elem_sz = INT_MAX` then the `order` is 19. This will make `ret_sz = 1 << 31`. This is still UB, because a 32-bit signed integer cannot represent `1 << 31` without causing an overflow into the sign bit. Although `alloc_pages` would likely fail for `order = 19`, it doesn't matter, since the UB happens first.
So, it's not just a potential `alloc_pages` failure that I need to be worried about. I have an integer overflow *before* the `alloc_pages` call, which constitutes undefined behavior, and UBSAN correctly catches this. It's a critical vulnerability that needs a fix.
|
| 21/2 |
2026/09/09 16:55 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:include/linux/gfp.h Name:alloc_pages]
Results: map[SourceCode: SourceFile:]
|
| 22/2 |
2026/09/09 16:55 |
llm |
debugger |
0m
Model:
Tokens:
input: 20554
output: 36
thoughts: 21
Thoughts: Here's my thought process, summarized as you requested:
**Navigating the Memory Allocation Landscape**
Okay, so I need to understand how the `alloc_pages` function works. It's a fundamental building block of memory management in the Linux kernel, so getting a handle on its details is crucial. My immediate instinct is to check the header file that defines its underlying structures. Based on experience, the most logical place to start is `include/linux/gfp.h`. It's where the general flags and definitions related to memory allocation are usually housed. I expect to find the relevant `gfp_t` flags, related structures, and potentially some inline documentation or comments that will shed light on how `alloc_pages` itself leverages those structures. I'm hoping to get a clear picture of the allocation's behavior in various memory zones and circumstances.
|
| 23/2 |
2026/09/09 16:56 |
tool |
grepper |
0m
Args: map[Expression:static inline struct page \*alloc_pages PathPrefix:include/linux/gfp.h]
Results: map[Output:include/linux/gfp.h=279=struct folio *vma_alloc_folio_noprof(gfp_t gfp, int order, struct vm_area_struct *vma,
--
include/linux/gfp.h-281-#else
include/linux/gfp.h:282:static inline struct page *alloc_pages_noprof(gfp_t gfp_mask, unsigned int order)
include/linux/gfp.h-283-{
]
|
| 24/2 |
2026/09/09 16:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 20922
output: 39
thoughts: 24
Thoughts: Here's my take on those thoughts:
**Peering into the Allocation Depths**
Right, `alloc_pages`... that's a macro, isn't it? Okay, I'll need to dig a little deeper. Let's see what `alloc_pages_noprof` does. I'm always looking for ways to optimize, and understanding the core allocation functions is critical for performance tuning. This is likely the lower level function that the macro expands to. And since it is named "no prof", this is probably a function call to avoid instrumentation, which may mean this could be a good point to start the analysis. Let's see.
|
| 25/2 |
2026/09/09 16:56 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/gfp.h Name:alloc_pages_noprof]
Results: map[SourceCode:2561: /**
2562: * alloc_pages - Allocate pages.
2563: * @gfp: GFP flags.
2564: * @order: Power of two of number of pages to allocate.
2565: *
2566: * Allocate 1 << @order contiguous pages. The physical address of the
2567: * first page is naturally aligned (eg an order-3 allocation will be aligned
2568: * to a multiple of 8 * PAGE_SIZE bytes). The NUMA policy of the current
2569: * process is honoured when in process context.
2570: *
2571: * Context: Can be called from any context, providing the appropriate GFP
2572: * flags are used.
2573: * Return: The page on success or NULL if allocation fails.
2574: */
2575: struct page *alloc_pages_noprof(gfp_t gfp, unsigned int order)
2576: {
2577: struct page *page = alloc_frozen_pages_noprof(gfp, order);
2578:
2579: if (page)
2580: set_page_refcounted(page);
2581: return page;
2582: }
SourceFile:mm/mempolicy.c]
|
| 26/2 |
2026/09/09 16:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 21497
output: 34
thoughts: 1032
Thoughts: **Analyzing Potential Integer Overflow in `alloc_frozen_pages_noprof`**
Okay, let's break this down. My initial thought was that the check for `order > MAX_PAGE_ORDER` in `alloc_frozen_pages_noprof` might be the key, but the real issue seems to be bubbling up *before* we even get to that point. The UB (undefined behavior) stems from a calculation.
Specifically, the code calculates `ret_sz = 1 << (PAGE_SHIFT + order)`. The problems arise in the calculation of `order` and specifically the bit shift operation.
If `num` is zero or negative, the `get_order` function produces a very large value for `order` (like 52), leading to an attempt to shift 1 by 64 bits. This is immediate UB. Even if `num` is a large positive value such as `INT_MAX`, `order` is 19 which results in `1 << 31`, another UB condition because `ret_sz` is a signed `int`.
So, the first thing I need to do is fix the calculation of `num` and `order`. The code uses `scatter_elem_sz`, which is a module parameter. I see a potential bug here: if `num` (which is initialized to `scatter_elem_sz`) is less than `PAGE_SIZE`, `scatter_elem_sz` gets updated to `PAGE_SIZE`, but `num` *isn't* updated. This is clearly an oversight! `num` also needs to be updated to `PAGE_SIZE` after this check to fix the UB.
Even with this fix, `num` can still be large, and `order` can still cause an overflow in `ret_sz` if, for example, `num` is `INT_MAX`, and `order` becomes 19. The bit shift `1 << (12 + 19) = 1 << 31` is an overflow, as is `1 << (12 + 20) = 1 << 32`.
I thought initially that the code handles potential failures from `alloc_pages` by decrementing `order` and retrying (the `retry` label). However, the critical bit-shift calculation happens *before* `alloc_pages` is called. So, the code may be able to fallback, but is still suffering the UB. If `order` is too large (like 19 or even greater) it results in an overflow, but this occurs *before* the check in `alloc_pages` is invoked, and the retry is triggered.
So, the solution is to make sure to bound `order` *before* the loop. I need to make sure the value of `order` is reasonable. I also need to make sure to not overflow the `int` by using the `1UL` literal. But, even that doesn't solve the problem entirely, because `ret_sz` is an `int`, and the overflow can still occur. I need to find the `MAX_PAGE_ORDER` which is defined in `include/linux/mmzone.h`. I think by bounding `order` to a safe maximum, this should work.
|
| 27/2 |
2026/09/09 16:56 |
tool |
grepper |
0m
Args: map[Expression:define MAX_PAGE_ORDER PathPrefix:include/linux/mmzone.h]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
]
|
| 28/2 |
2026/09/09 16:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 23377
output: 41
thoughts: 305
Thoughts: **Optimizing Memory Allocation**
Okay, so I'm looking at this `MAX_PAGE_ORDER` constant. Seems like it's usually set to 10. If I restrict the `order` variable to `MAX_PAGE_ORDER`, then `PAGE_SHIFT + order` will never exceed 22, right? And `1 << 22` is, conveniently, 4MB, which fits perfectly within an integer. Nice!
Wait a minute, let me look at how `sg_build_indirect` does it. They do `order = get_order(num);` and then, in a retry loop, `ret_sz = 1 << (PAGE_SHIFT + order);`. If I just cap that `order` at `MAX_PAGE_ORDER` upfront, I can potentially sidestep the undefined behavior (UB) and also avoid wasteful calls to `alloc_pages` that I already *know* are going to fail. Right, like this:
```c
order = get_order(num);
order = min_t(int, order, MAX_PAGE_ORDER);
retry:
```
But, hold on. Is `MAX_PAGE_ORDER` the absolute limit of the buddy allocator? Is it guaranteed that `alloc_pages` will fail if `order` is greater than `MAX_PAGE_ORDER`? Yes, I remember seeing `WARN_ON_ONCE(order > MAX_PAGE_ORDER)` in some versions of the code, or it just fails. Actually, it looks like `alloc_pages` might just trigger a warning if `order > MAX_PAGE_ORDER`. Let me just double check whether `alloc_pages` actually warns and I can be sure.
|
| 29/2 |
2026/09/09 16:56 |
tool |
grepper |
0m
Args: map[Expression:WARN_ON_ONCE.*order > MAX_PAGE_ORDER PathPrefix:mm/page_alloc.c]
Results: map[Output:mm/page_alloc.c=5330=static inline bool alloc_order_allowed(gfp_t gfp, unsigned int order,
--
mm/page_alloc.c-5339- */
mm/page_alloc.c:5340: return !(WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp));
mm/page_alloc.c-5341-}
--
mm/page_alloc.c=6445=void free_reserved_pages(struct page *page, unsigned int order)
--
mm/page_alloc.c-6450- VM_WARN_ON_ONCE(!IS_ALIGNED(page_to_pfn(page), nr_pages));
mm/page_alloc.c:6451: VM_WARN_ON_ONCE(order > MAX_PAGE_ORDER);
mm/page_alloc.c-6452-
]
|
| 30/2 |
2026/09/09 16:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 24329
output: 39
thoughts: 284
Thoughts: **My Analysis of `sg_build_indirect` and Page Allocation**
Okay, so `alloc_pages` has this guardrail in place, `WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp)`. Makes sense, you wouldn't want someone requesting, say, a huge order of pages unintentionally. So, if `order` ends up exceeding `MAX_PAGE_ORDER`, that's a bug. The code will throw a warning.
My focus has to be on `sg_build_indirect`. I need to ensure that when it calls `alloc_pages`, the `order` parameter is *never* larger than `MAX_PAGE_ORDER`. Let's see... the code currently does:
```c
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
...
schp->pages[k] = alloc_pages(gfp_mask, order);
```
Right, if `num` is large enough, then `get_order(num)` *could* return an `order` that's too big! This would definitely trigger that warning. I'm starting to get worried, because I've seen things like this lead to subtle memory issues.
But wait a minute... I need to look closer at `gfp_mask`:
```c
gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
```
Ah, it has `__GFP_NOWARN` set! My intuition tells me that means that the `WARN_ON_ONCE_GFP` will not trigger, but I should confirm that this is correct, and not just assume that the code is correct. I have to look into `WARN_ON_ONCE_GFP` now, just to make sure. I'd better be absolutely certain.
|
| 31/2 |
2026/09/09 16:56 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:mm/page_alloc.c Name:WARN_ON_ONCE_GFP]
Results: map[SourceCode: SourceFile:]
|
| 32/2 |
2026/09/09 16:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 25090
output: 32
thoughts: 15
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing `WARN_ON_ONCE_GFP`**
Okay, so I'm seeing `WARN_ON_ONCE_GFP`… my initial thought is, let's trace this. Specifically, I want to immediately get a grasp on where this macro is being used. Time to get down to brass tacks: `grep` is my friend. I'm going to run a quick search for exactly that string: `WARN_ON_ONCE_GFP`. This should give me the locations of its uses within the codebase. That's the baseline, the crucial first step. I need context. Once I have the call sites, then I can start digging into the surrounding code to understand the logic flow, what conditions trigger the warning, and, importantly, what `GFP` flags are being passed. I want to see if the warnings make sense. I'll be looking for potential problems with memory allocation contexts or possible resource leaks or synchronization issues that trigger the warning. That's the core. From there, I can analyze specific callsites, looking to understand the function being called, to understand the allocation behavior. This seems like a pretty common kernel debugging pattern, so the warning may be well-understood, or, perhaps, a sign of something that I'm going to want to deeply understand, and, perhaps, patch.
|
| 33/2 |
2026/09/09 16:56 |
tool |
grepper |
0m
Error:
Args: map[Expression:define WARN_ON_ONCE_GFP PathPrefix:include/]
Results:
|
| 34/2 |
2026/09/09 16:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 25447
output: 32
thoughts: 20
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Hunting for `WARN_ON_ONCE_GFP` in `mm/`**
Okay, so I'm thinking, "Time to dig into the memory management code." Specifically, I want to find where `WARN_ON_ONCE_GFP` is being used within the `mm/` directory. That macro, `WARN_ON_ONCE_GFP`, is always a red flag - it screams potential problems related to allocation failures that are being *conditionally* ignored, and if it's there, then something needs to be checked. I'm guessing that means a `GFP` flag (maybe `GFP_KERNEL` or `GFP_ATOMIC`) is being used in an unexpected or potentially dangerous context. I'm expecting to see calls where a memory allocation is attempted with a GFP that *could* fail, but instead of handling the failure gracefully, the code simply triggers a warning *once* and then carries on. I’m thinking there could be cases where we have non-atomic memory allocations in situations where an interrupt could be raised, but the calling function would be unable to return a failure status to the caller due to the inability to handle the failure and potential for deadlock. The "once" is a concession to not spamming the logs, but it still means we're masking a potential error. I want to figure out *why* that design decision was made, and whether the rationale still holds true. I have a hunch it might be related to some older kernel code or a specific hardware quirk. So, let's start with a `grep` and see what turns up.
|
| 35/2 |
2026/09/09 16:56 |
tool |
grepper |
0m
Args: map[Expression:define WARN_ON_ONCE_GFP PathPrefix:mm/]
Results: map[Output:mm/internal.h=117=struct pagetable_move_control {
--
mm/internal.h-162- */
mm/internal.h:163:#define WARN_ON_ONCE_GFP(cond, gfp) ({ \
mm/internal.h-164- static bool __section(".data..once") __warned; \
]
|
| 36/2 |
2026/09/09 16:56 |
llm |
debugger |
0m
Model:
Tokens:
input: 25952
output: 33
thoughts: 22
Thoughts: Here's my summary, as though I'm reading and thinking about the code:
**Diving into `WARN_ON_ONCE_GFP`**
Okay, time to dig into `WARN_ON_ONCE_GFP`, let's see what's happening. I need to refresh my memory on what this macro is intended to do, and where it fits into the larger picture of the memory management code. I'll need to go to `mm/internal.h` and take a look at the definition itself. I'm expecting this will likely relate to some kind of debugging or sanity check within the kernel's memory allocation routines. I'm interested in how it interacts with the GFP flags, particularly if it flags an event only once and the reasons behind that. I'm guessing this might be a mechanism to prevent an avalanche of warnings when an allocation goes wrong. Let's see if my hypotheses are correct.
|
| 37/2 |
2026/09/09 16:56 |
tool |
read-file |
0m
Args: map[File:mm/internal.h FirstLine:160 LineCount:20]
Results: map[Contents: 160: * Different from WARN_ON_ONCE(), no warning will be issued
161: * when we specify __GFP_NOWARN.
162: */
163: #define WARN_ON_ONCE_GFP(cond, gfp) ({ \
164: static bool __section(".data..once") __warned; \
165: int __ret_warn_once = !!(cond); \
166: \
167: if (unlikely(!(gfp & __GFP_NOWARN) && __ret_warn_once && !__warned)) { \
168: __warned = true; \
169: WARN_ON(1); \
170: } \
171: unlikely(__ret_warn_once); \
172: })
173:
174: void page_writeback_init(void);
175:
176: /*
177: * If a 16GB hugetlb folio were mapped by PTEs of all of its 4kB pages,
178: * its nr_pages_mapped would be 0x400000: choose the ENTIRELY_MAPPED bit
179: * above that range, instead of 2*(PMD_SIZE/PAGE_SIZE). Hugetlb currently
]
|
| 38/2 |
2026/09/09 16:57 |
llm |
debugger |
0m
Model:
Tokens:
input: 26583
output: 33
thoughts: 480
Thoughts: **Analyzing Potential Issues in `sg_build_indirect`**
Okay, so I'm looking at how `WARN_ON_ONCE_GFP` interacts with `alloc_order_allowed` and the implications for `alloc_pages`. It seems straightforward: if `__GFP_NOWARN` is set, `WARN_ON_ONCE_GFP` won't trigger a warning, but crucially, `alloc_order_allowed` will still return false if the order is too large. This causes `alloc_pages` to predictably fail and return NULL – which is good. We want that behavior.
Now, the crucial bit is how `sg_build_indirect` handles these failures. It calls `alloc_pages` inside a loop, and if it fails, it decrements the `order` and retries, eventually reaching a `retry:` label. This looks okay at first, but it then tries decrementing the order, potentially re-entering the `retry` label with a new order value. This could be problematic because the loop will eventually hit `MAX_PAGE_ORDER`. Then, `alloc_pages` is called, but there is still a calculation of `ret_sz = 1 << (PAGE_SHIFT + order)`.
Here's the problem: if `order` is sufficiently large (e.g., 52 or 19 in these examples), `PAGE_SHIFT + order` exceeds the bit width for the left shift operation. That triggers undefined behavior – a serious issue. We're potentially risking a crash or other unpredictable consequences.
A simple solution jumps out. If we *bound* the `order` to `MAX_PAGE_ORDER` *before* the loop, or at least before the calculation of `ret_sz`, we accomplish two things. First, we prevent the undefined behavior during the bit shift. Second, we eliminate the unnecessary `alloc_pages` calls that we *know* are going to fail (because of the initial check in `alloc_order_allowed`), which is a nice optimization. No more wasted time trying to allocate a block of memory that's too big!
The question now is whether `MAX_PAGE_ORDER` is accessible in `drivers/scsi/sg.c`? We will need to check if the value is available and exported correctly.
|
| 39/2 |
2026/09/09 16:57 |
tool |
grepper |
0m
Error:
Args: map[Expression:MAX_PAGE_ORDER PathPrefix:drivers/scsi/sg.c]
Results:
|
| 40/2 |
2026/09/09 16:57 |
llm |
debugger |
0m
Model:
Tokens:
input: 27598
output: 32
thoughts: 60
Thoughts: **Checking for Definition Inclusion**
Okay, let's quickly troubleshoot this. I need to figure out if `MAX_PAGE_ORDER` is accessible within `sg.c`. The definition is in `include/linux/mmzone.h`, so I just have to confirm if the `sg.c` file has an include directive for it. That should do the trick, right?
|
| 41/2 |
2026/09/09 16:57 |
tool |
grepper |
0m
Error:
Args: map[Expression:include.*mmzone PathPrefix:drivers/scsi/sg.c]
Results:
|
| 42/2 |
2026/09/09 16:57 |
llm |
debugger |
0m
Model:
Tokens:
input: 27785
output: 36
thoughts: 1806
Thoughts: **Analyzing Potential Integer Overflow and Shift Count Issues**
Okay, so I'm diving into this code and immediately see a potential issue stemming from how the `order` variable is derived and used in conjunction with the `ret_sz` calculation. The calculation involves left-shifting the value of 1. It's a bit of a maze, but I can see how it could lead to trouble. Initially, my thought was to use something like `min_t(int, order, MAX_PAGE_ORDER)` to ensure we stay within bounds if `MAX_PAGE_ORDER` is available or to just limit the value of `num`, but the critical observation is that the issue arises from `num` which is derived from `scatter_elem_sz` which is user controllable via sysfs!
The primary problem revolves around the use of `1ULL << (PAGE_SHIFT + order)` to calculate `ret_sz`. If the value of `PAGE_SHIFT + order` exceeds the bit-width of an integer or the resulting value cannot be represented as an integer, then there is undefined behavior. Initially I thought `1ULL << 64` was the issue, but then realized that the shift count is too big for a 64-bit integer, and then that `num` could become negative leading to an extremely high `order` value, in this case, 52.
The key insight here is that `num` can be zero or negative! This can happen because `scatter_elem_sz` can be set to 0 or negative via sysfs. When `num < PAGE_SIZE`, the code corrects `scatter_elem_sz` to `PAGE_SIZE`, but crucially it *doesn't* update `num`! Thus, `order = get_order(num);` will still receive the zero or negative value, causing the undefined behavior.
My immediate fix would be to modify the check in the `sg_build_indirect` function to *also* update `num` if it's less than `PAGE_SIZE`. Then, by setting `num = PAGE_SIZE;`, `order` would become zero, preventing the overflow, and resolving the issue of zero or negative `num` values.
However, even if `num` is large (e.g., `INT_MAX`), we still have to be cautious, as a large `num` means a large `order` and a resulting `1 << (PAGE_SHIFT + order)` can potentially overflow when assigned to `ret_sz` (an `int`). In the case of `INT_MAX`, `order` is 19. Now the `PAGE_SHIFT + order` will be 31, and `1 << 31` would be UB or cause an integer overflow.
The code does attempt to handle failures in `alloc_pages`, decrementing `order` down to a maximum value, and retrying. However, the overflow can occur *before* the allocation fails, and then causes the crash.
The best solution is to bound `order` to prevent the overflow. Since `ret_sz` is an `int`, `PAGE_SHIFT + order` must be less than 31. Therefore, `order` must be less than `31 - PAGE_SHIFT`. Since `PAGE_SHIFT` is 12, `order` should be less than 19.
To ensure safety, I think the most straightforward fix here is to bound `order` or `num`. Using `min_t(int, order, 18)` (or `19 - PAGE_SHIFT`) seems like a good approach if we don't have a reliable `MAX_PAGE_ORDER`.
The root cause, as syzbot reports, is the `shift exponent 64 is too large for 32-bit type 'int'`, indicating `order` equals 52. This happens when `num` is zero or negative. Updating `num` fixes this. If the message were `signed integer overflow: 1 << 31 cannot be represented in type 'int'`, that would also be an issue. But that's not the problem here, thanks to the fix with num.
I will need to verify if the latest kernel includes the fix to update `num` when `num < PAGE_SIZE`.
|
| 43/2 |
2026/09/09 16:57 |
tool |
git-log |
0m
Args: map[Count:10 PathPrefix:drivers/scsi/sg.c Since:1 year]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
5e2fde1a9433 block: pass io_comp_batch to rq_end_io_fn callback
0e1677654259 scsi: sg: Fix occasional bogus elapsed time that exceeds timeout
90449f2d1e1f scsi: sg: Do not sleep in atomic context
]
|
| 44/2 |
2026/09/09 16:57 |
llm |
debugger |
0m
Model:
Tokens:
input: 30831
output: 41
thoughts: 12
Thoughts: Okay, here's my attempt at summarizing that thought process, tailored for an expert audience:
**Investigating Potential Fixes**
Alright, I'm diving in. Before I start tearing things apart, I need to see if this issue has already been addressed, ideally with a commit. The first step, logically, is to check the commit history. I'm going to look for any relevant commits that might offer a quick resolution to the problem. Hopefully, someone's already encountered this and put in a fix. If I can find it, that'll save a huge amount of time, and potential troubleshooting.
|
| 45/2 |
2026/09/09 16:57 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz Count:10 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 46/2 |
2026/09/09 16:57 |
llm |
debugger |
0m
Model:
Tokens:
input: 31074
output: 27
thoughts: 739
Thoughts: **Analyzing the Bug Fix and Potential Overflows**
Okay, the bug's still there, so time to verify this proposed fix. Let's see... we're changing this block of code:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
Right, if `num` is zero initially, the `num < PAGE_SIZE` condition becomes true. So, `num`, `scatter_elem_sz`, and `scatter_elem_sz_prev` all get set to `PAGE_SIZE`. Then, calculating `order = get_order(num)` is equivalent to `get_order(PAGE_SIZE)`, which yields zero. Subsequently, `ret_sz = 1 << (12 + 0)` becomes 4096, which should fix that `shift exponent 64` crash. Good, it seems sound.
But, hold on a second... what if `num` is *really* big, like `INT_MAX`? Let's trace that path. If `num` is `INT_MAX`, the `num < PAGE_SIZE` condition is false, and `scatter_elem_sz_prev` becomes `INT_MAX`. Then we're calculating `order = get_order(INT_MAX)`. `INT_MAX` is `0x7fffffff`. So, `get_order(0x7fffffff)` will go through: `size = 0x7fffffff`, `size-- = 0x7ffffffe`, `size >>= 12 = 0x7ffff`, `fls(0x7ffff) = 19`, so `order` becomes 19. That means `ret_sz = 1 << (12 + 19) = 1 << 31`.
Uh oh, that's undefined behavior for a signed `int`. Is `ret_sz` even used as an `int`? Let's check the context:
```c
int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
...
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
```
Yep, `ret_sz` *is* an `int`. If `ret_sz` is `1 << 31`, it's `-2147483648`. Then `rem_sz -= ret_sz` effectively *adds* 2147483648 to `rem_sz`. `rem_sz` is also an `int`, so it will overflow and either become negative or positive, depending on what its initial value is, potentially causing an infinite loop or other weird behavior! We need to prevent `order` from getting too large.
The question now becomes: what's the maximum valid `order`? Ah, `MAX_PAGE_ORDER` is probably what we need, as that's the maximum order that `alloc_pages` can handle. But it's not available in `sg.c` unless we include `<linux/mmzone.h>`. Wait, didn't `MAX_ORDER` get renamed to `MAX_PAGE_ORDER` recently? I'll need to check if that symbol is actually defined.
|
| 47/2 |
2026/09/09 16:58 |
tool |
git-log |
0m
Args: map[CodeRegexp:MAX_PAGE_ORDER Count:10]
Results: map[Output:54cc9b384709 mm: debug_page_alloc: fix NULL buf in debug_guardpage_minorder_setup
bb3e3c5c2d63 mm: debug_page_alloc: fix type mismatch for debug_guardpage_minorder
73fe42af955a Drivers: hv: vmbus: Add vmbus_alloc_buffer()/vmbus_free_buffer() for CoCo VMs
b311af86b58f pds_core: add host backed memory support for firmware
d79db3f39684 mm: provide free_reserved_pages(), removing x86 variant
2fc4c1d51d87 mm/page_alloc: unify __alloc_frozen_pages[_nolock]_noprof()
d0850de699b0 mm: split out internal page_alloc.h
4fd1c85cc031 mm/page_owner: clamp skip_buddy_pages() PFN advance at MAX_ORDER_NR_PAGES boundary
53472eb26291 mm/page_owner: extract skip_buddy_pages() helper to unify buddy page skipping
797fe91e50d6 kho: align kho_scratch to MAX_ORDER_NR_PAGES pages
]
|
| 48/2 |
2026/09/09 16:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 33000
output: 32
thoughts: 269
Thoughts: **My Reasoning on Page Order Limits**
Okay, so `MAX_PAGE_ORDER` is the chosen name now. That's good. My initial thought was, "Great, we can just use `MAX_PAGE_ORDER` directly, since it's defined if we include `<linux/mmzone.h>`." But then the alarm bells started ringing. Even if we use that, `alloc_pages` is still going to fail if the `order` is too high! And it will decrement order down to MAX_PAGE_ORDER anyway.
Alright, so I was thinking, why don't we just set a reasonable upper bound to start with? Something safe, like 20. That would side-step any undefined behavior, and the `alloc_pages` function would handle it. But hold on... `1 << (12 + 19)` will give us `1 << 31`. That's undefined behavior! I need to be careful with bit shifts like that.
So, `order` has to be smaller than 19. If I bound it to 18, then `1 << (12 + 18)` becomes `1 << 30`, which is `1073741824`. That should be safe for a signed 32-bit `int`.
But wait, hold on. `MAX_PAGE_ORDER` is usually *much* smaller, isn't it? It's typically around 10. That means we're never even going to successfully allocate if `order` is greater than 10, no matter what. So why am I going through all this? Why not just bind `order` to `MAX_PAGE_ORDER` in the first place? It seems so obvious.
Right, let's see if `sg.c` includes `<linux/mmzone.h>` first. I need to make sure `MAX_PAGE_ORDER` will actually be available before committing to this.
|
| 49/2 |
2026/09/09 16:58 |
tool |
grepper |
0m
Error:
Args: map[Expression:include.*mmzone PathPrefix:drivers/scsi/sg.c]
Results:
|
| 50/2 |
2026/09/09 16:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 33738
output: 32
thoughts: 126
Thoughts: **My Thought Process on Including `mmzone.h`**
Okay, so I'm looking at this code and the question is: can we just directly `#include <linux/mmzone.h>`? Yes, it's a straightforward approach, we could certainly add that include. Alternatively, I was thinking we could just clamp the `order` variable using `min_t(int, order, MAX_PAGE_ORDER)`.
Ah, but hold on...isn't `MAX_PAGE_ORDER` itself defined within `<linux/mmzone.h>`? So, we'd still be implicitly depending on it for that method. Makes sense. Okay, let's see, is there anything else already included in this file that *itself* includes `mmzone.h`? A quick scan of `sg.c`... ah, yes, here we go: it already includes `<linux/gfp.h>`, which, as I recall, transitively includes `<linux/mmzone.h>`. Excellent. Problem solved. We don't need to add anything explicitly!
|
| 51/2 |
2026/09/09 16:58 |
tool |
grepper |
0m
Args: map[Expression:include.*mmzone PathPrefix:include/linux/gfp.h]
Results: map[Output:include/linux/gfp.h-6-
include/linux/gfp.h:7:#include <linux/mmzone.h>
include/linux/gfp.h-8-#include <linux/topology.h>
]
|
| 52/2 |
2026/09/09 16:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 34191
output: 33
thoughts: 41
Thoughts: **Realizing a Convenient Shortcut**
Ah, right! I see that the `gfp.h` header file includes `mmzone.h`. That's key. So, because of that inclusion, `MAX_PAGE_ORDER` is *already* accessible within `sg.c`! I completely missed that initially, but it makes this task significantly easier. Let me just quickly verify this and make sure my assumptions are correct, but if so, it will save a whole lot of work.
|
| 53/2 |
2026/09/09 16:58 |
tool |
grepper |
0m
Error:
Args: map[Expression:MAX_PAGE_ORDER PathPrefix:drivers/scsi/sg.c]
Results:
|
| 54/2 |
2026/09/09 16:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 34383
output: 34
thoughts: 38
Thoughts: Okay, here's my take on those thoughts, framed as my own mental process:
**Internal Audit of Potential Variable Usage**
Alright, I'm just quickly going over this code, and it seems like this particular variable, whatever it is, isn't *directly* being used within `sg.c`. However, I know it's *available* within the project. I'd better be sure it's defined and how it's handled. First things first, let's double-check the header files to make sure that `MAX_PAGE_ORDER` is defined in `mmzone.h`. This will keep me honest so that when I go back to modify things, or to implement the other pieces I know will eventually leverage this variable, I'm not running afoul of any definitions or dependencies. Always good to take a moment and confirm.
|
| 55/2 |
2026/09/09 16:58 |
tool |
grepper |
0m
Args: map[Expression:define MAX_PAGE_ORDER PathPrefix:include/linux/mmzone.h]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
]
|
| 56/2 |
2026/09/09 16:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 34750
output: 34
thoughts: 571
Thoughts: **Analyzing the Code's Safety and Effectiveness**
Okay, so we're looking at this code snippet, and the goal is to make it robust. We're setting `num`, then bounding `order`, which seems like the right approach to fix the potential issue. Specifically, bounding `order` to `MAX_PAGE_ORDER` is key to preventing those nasty undefined behavior errors from bit-shifting, like `1 << 31` or `1 << 64`.
Let's walk through a few edge cases to make sure. What if `num` is zero or negative? Well, if `num <= 0`, the code correctly handles it. The check `num < PAGE_SIZE` becomes true, so we set `num` to `PAGE_SIZE`. Then `order` becomes 0 (from `get_order(PAGE_SIZE)`). The `min_t` call ensures `order` remains 0. Finally, we get `ret_sz = 1 << 12`, which is 4096. All good, perfectly safe.
Now, what if `num` is `INT_MAX`, the largest possible integer? In this case, `num < PAGE_SIZE` is false, and `order` ends up being 19 (from `get_order(INT_MAX)`). Bounding it with `min_t` to `MAX_PAGE_ORDER`, which is usually 10, keeps `order` at 10. Consequently, `ret_sz` becomes `1 << 22`, a manageable size. This not only avoids the UB associated with bit-shifting large numbers, but also neatly side-steps a potential `WARN_ON_ONCE` in `alloc_pages` that could be triggered by an `order` of 19. So, bounding `order` is a clear win here, protecting us from those edge case shenanigans.
Just to be absolutely certain, let's confirm the availability of `MAX_PAGE_ORDER`. A quick check in `include/linux/mmzone.h` assures us it's defined. And since that header is indirectly included by our driver code, we're good to go. This whole approach seems like a robust solution to a subtle problem.
|
| 57/2 |
2026/09/09 16:58 |
tool |
grepper |
0m
Error:
Args: map[Expression:include.*gfp\.h PathPrefix:drivers/scsi/sg.c]
Results:
|
| 58/2 |
2026/09/09 16:58 |
llm |
debugger |
0m
Model:
Tokens:
input: 35848
output: 35
thoughts: 26
Thoughts: **Investigating a Potential Header Inclusion Issue**
Okay, hold on a second. I was under the impression that `sg.c` included `gfp.h`, but something's telling me that might not be right. I need to verify this assumption before I go any further. I'm going to quickly check the actual includes within the `sg.c` source file. Gotta make sure I'm working with accurate information here. This could be a critical detail, and I don't want to waste time chasing the wrong leads. Let me just confirm those includes and move on.
|
| 59/2 |
2026/09/09 16:58 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1 LineCount:100]
Results: map[Contents: 1: // SPDX-License-Identifier: GPL-2.0-or-later
2: /*
3: * History:
4: * Started: Aug 9 by Lawrence Foard (entropy@world.std.com),
5: * to allow user process control of SCSI devices.
6: * Development Sponsored by Killy Corp. NY NY
7: *
8: * Original driver (sg.c):
9: * Copyright (C) 1992 Lawrence Foard
10: * Version 2 and 3 extensions to driver:
11: * Copyright (C) 1998 - 2014 Douglas Gilbert
12: */
13:
14: static int sg_version_num = 30536; /* 2 digits for each component */
15: #define SG_VERSION_STR "3.5.36"
16:
17: /*
18: * D. P. Gilbert (dgilbert@interlog.com), notes:
19: * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
20: * the kernel/module needs to be built with CONFIG_SCSI_LOGGING
21: * (otherwise the macros compile to empty statements).
22: *
23: */
24: #include <linux/module.h>
25:
26: #include <linux/fs.h>
27: #include <linux/kernel.h>
28: #include <linux/sched.h>
29: #include <linux/string.h>
30: #include <linux/mm.h>
31: #include <linux/errno.h>
32: #include <linux/mtio.h>
33: #include <linux/ioctl.h>
34: #include <linux/major.h>
35: #include <linux/slab.h>
36: #include <linux/fcntl.h>
37: #include <linux/init.h>
38: #include <linux/poll.h>
39: #include <linux/moduleparam.h>
40: #include <linux/cdev.h>
41: #include <linux/idr.h>
42: #include <linux/seq_file.h>
43: #include <linux/blkdev.h>
44: #include <linux/delay.h>
45: #include <linux/blktrace_api.h>
46: #include <linux/mutex.h>
47: #include <linux/atomic.h>
48: #include <linux/ratelimit.h>
49: #include <linux/uio.h>
50: #include <linux/cred.h> /* for sg_check_file_access() */
51:
52: #include <scsi/scsi.h>
53: #include <scsi/scsi_cmnd.h>
54: #include <scsi/scsi_dbg.h>
55: #include <scsi/scsi_device.h>
56: #include <scsi/scsi_driver.h>
57: #include <scsi/scsi_eh.h>
58: #include <scsi/scsi_host.h>
59: #include <scsi/scsi_ioctl.h>
60: #include <scsi/scsi_tcq.h>
61: #include <scsi/sg.h>
62:
63: #include "scsi_logging.h"
64:
65: #ifdef CONFIG_SCSI_PROC_FS
66: #include <linux/proc_fs.h>
67: static char *sg_version_date = "20140603";
68:
69: static int sg_proc_init(void);
70: #endif
71:
72: #define SG_ALLOW_DIO_DEF 0
73:
74: #define SG_MAX_DEVS (1 << MINORBITS)
75:
76: /* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type
77: * of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater
78: * than 16 bytes are "variable length" whose length is a multiple of 4
79: */
80: #define SG_MAX_CDB_SIZE 252
81:
82: #define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
83:
84: /* N.B. This variable is readable and writeable via
85: * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
86: * of this size (or less if there is not enough memory) will be reserved
87: * for use by this file descriptor.
88: */
89:
90: /* picks up init parameter */
91: static int def_reserved_size = SG_DEF_RESERVED_SIZE;
92: static int sg_allow_dio = SG_ALLOW_DIO_DEF;
93:
94: static int scatter_elem_sz = SG_SCATTER_SZ;
95: static int scatter_elem_sz_prev = SG_SCATTER_SZ;
96:
97: #define SG_SECTOR_SZ 512
98:
99: static int sg_add_device(struct device *);
100: static void sg_remove_device(struct device *);
]
|
| 60/2 |
2026/09/09 16:59 |
llm |
debugger |
0m
Model:
Tokens:
input: 37622
output: 33
thoughts: 130
Thoughts: **Investigating the Availability of MAX_PAGE_ORDER in Older Kernels**
Okay, so I'm working with this code, and I see it's including `<linux/mm.h>` which, as expected, pulls in `<linux/gfp.h>`. That means `MAX_PAGE_ORDER` is definitely defined and accessible within this scope. But I need to figure out the root cause of the bug and how it is related to this.
The real question is, was it always available? The issue seems to be in `drivers/scsi/sg.c`, and I've got a syzbot crash report pointing me to a specific commit: `9d22f3af01dc24fa8887cb4af37a784370af643b`.
My next step is to go back and check the definition of `MAX_PAGE_ORDER` in *that* particular commit. I need to know if it was available back then. If it wasn't, I know I'm looking at a backward compatibility issue or possibly a missing `#ifdef` somewhere. This should give me a good start to tracking down the underlying problem.
|
| 61/2 |
2026/09/09 16:59 |
tool |
grepper |
0m
Args: map[Expression:MAX_PAGE_ORDER PathPrefix:include/linux/mmzone.h]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
include/linux/mmzone.h:35:#define MAX_ORDER_NR_PAGES (1 << MAX_PAGE_ORDER)
include/linux/mmzone.h-36-
--
include/linux/mmzone.h-38-
include/linux/mmzone.h:39:#define NR_PAGE_ORDERS (MAX_PAGE_ORDER + 1)
include/linux/mmzone.h-40-
--
include/linux/mmzone.h-42-#ifndef CONFIG_PAGE_BLOCK_MAX_ORDER
include/linux/mmzone.h:43:#define PAGE_BLOCK_MAX_ORDER MAX_PAGE_ORDER
include/linux/mmzone.h-44-#else
--
include/linux/mmzone.h-48-/*
include/linux/mmzone.h:49: * The MAX_PAGE_ORDER, which defines the max order of pages to be allocated
include/linux/mmzone.h-50- * by the buddy allocator, has to be larger or equal to the PAGE_BLOCK_MAX_ORDER,
--
include/linux/mmzone.h-52- */
include/linux/mmzone.h:53:#if (PAGE_BLOCK_MAX_ORDER > MAX_PAGE_ORDER)
include/linux/mmzone.h:54:#error MAX_PAGE_ORDER must be >= PAGE_BLOCK_MAX_ORDER
include/linux/mmzone.h-55-#endif
--
include/linux/mmzone.h-69- */
include/linux/mmzone.h:70:#define MAX_FOLIO_ORDER MAX_PAGE_ORDER
include/linux/mmzone.h-71-#elif defined(CONFIG_SPARSEMEM) && !defined(CONFIG_SPARSEMEM_VMEMMAP)
--
include/linux/mmzone.h=979=struct zone {
--
include/linux/mmzone.h-1101-#ifdef CONFIG_UNACCEPTED_MEMORY
include/linux/mmzone.h:1102: /* Pages to be accepted. All pages on the list are MAX_PAGE_ORDER */
include/linux/mmzone.h-1103- struct list_head unaccepted_pages;
--
include/linux/mmzone.h=1919=static inline bool movable_only_nodes(nodemask_t *nodes)
--
include/linux/mmzone.h-1964-
include/linux/mmzone.h:1965:#if (MAX_PAGE_ORDER + PAGE_SHIFT) > SECTION_SIZE_BITS
include/linux/mmzone.h:1966:#error Allocator MAX_PAGE_ORDER exceeds SECTION_SIZE
include/linux/mmzone.h-1967-#endif
]
|
| 62/2 |
2026/09/09 16:59 |
llm |
debugger |
0m
Model:
Tokens:
input: 38800
output: 31
thoughts: 735
Thoughts: **Analyzing a Potential Integer Overflow in the `sg` Driver**
Okay, so `MAX_PAGE_ORDER` is definitely available, which is good. Let's break down this bug and the proposed fix. It looks like the root cause stems from a vulnerability in how the `scatter_elem_sz` module parameter is handled. Root can set this value, via sysfs, to a 0 or negative value. When `sg_build_indirect()` is called, it reads this value into `num`. The problem arises if `num` is less than `PAGE_SIZE`. The code attempts to correct this by updating `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`, but crucially *doesn't* update the local variable `num`. This leaves `num` at its original, problematic value (0 or negative).
The next step, `get_order(num)`, is then called. With `num <= 0`, `get_order()` returns a very large value (depending on the architecture), something like 52 or 20. This large result, when combined with `PAGE_SHIFT` in the expression `1 << (PAGE_SHIFT + order)`, creates a shift-out-of-bounds undefined behavior, causing a UBSAN panic. Even if `num` is a large positive value, like `INT_MAX`, `order` could be as large as 19, which can cause a shift by 31, which is undefined behavior for a signed integer.
The fix seems straightforward, and I've verified the parts that matter to me. First, we need to ensure that the local variable `num` gets updated to `PAGE_SIZE` when `scatter_elem_sz` is less than `PAGE_SIZE`. This is the first correction in the code snippet.
The second part is more interesting. The code uses `min_t(int, order, MAX_PAGE_ORDER)` to bound the `order` variable. This prevents the large return value of `get_order` from resulting in the shift-out-of-bounds problem, as `order` will now be capped at `MAX_PAGE_ORDER`. This is to prevent a value to be passed to `alloc_pages()`.
I've already confirmed that `MAX_PAGE_ORDER` is reliably defined in `<linux/mmzone.h>`, so that's not a concern. I did a quick check in `sg.c` to see if there were other places where `scatter_elem_sz` or `get_order` was used. `init_sg()` also checks for values of `scatter_elem_sz` less than `PAGE_SIZE` so the code is consistent.
Alright, the fix looks solid.
|
| 63/2 |
2026/09/09 16:59 |
tool |
grepper |
0m
Args: map[Expression:get_order PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1884-
drivers/scsi/sg.c:1885: order = get_order(num);
drivers/scsi/sg.c-1886-retry:
]
|
| 64/2 |
2026/09/09 16:59 |
llm |
debugger |
0m
Model:
Tokens:
input: 40266
output: 1090
thoughts: 2082
Thoughts: **Analysis of the sg_build_indirect UBSAN Crash**
Okay, let's break this down. The issue resides solely within the `sg_build_indirect` function. It looks like the reproducer is cleverly manipulating the `scatter_elem_sz` module parameter by setting it to "0". This is key, as it feeds directly into the flaw.
The relevant code, as I see it, initializes `num` to `scatter_elem_sz`. This means `num` is also zero. The subsequent check, `if (num < PAGE_SIZE)`, should trigger, which is intended, and the code attempts to update `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. The problem is that the local variable `num` doesn't get updated to the new value, remaining as zero.
Then, we have the problematic call to `get_order(num)`. While the documentation considers `get_order(0)` undefined behavior, the implementation's handling of zero is critical. It decrements the input to `0xffffffffffffffff`, shifts it by `PAGE_SHIFT` (12), and then applies `fls64`. On a 64-bit system, `fls64(0x000fffffffffffff)` ends up returning 52.
This leads to the calculation `ret_sz = 1 << (PAGE_SHIFT + order)`, which, in this scenario, becomes `1 << (12 + 52)`, or `1 << 64`. Here's the kicker: this shift operation by 64 bits on a 32-bit `int` is undefined behavior, precisely the `shift-out-of-bounds` UBSAN error we're seeing.
Furthermore, it's worth noting that if `scatter_elem_sz` is set to a *very* large value, like `INT_MAX`, the same underlying issue surfaces but differently. In such a case, `get_order(INT_MAX)` returns 19. This leads to a similar situation where the shift `1 << (12 + 19)` which equals `1 << 31`, which is undefined behavior and effectively overflows a signed 32-bit integer, and potentially triggers a `WARN_ON_ONCE` within `alloc_pages` if the order is greater than MAX_PAGE_ORDER.
The fix is straightforward. First, we need to ensure that `num` is updated *inside* the `if (num < PAGE_SIZE)` block to reflect the new `PAGE_SIZE` value. Second, we must bound the `order` variable with `min_t(int, order, MAX_PAGE_ORDER)` before calculating `ret_sz`. This ensures that we stay within reasonable bounds and avoid the shift-out-of-bounds behavior. It is important to remember that developers may need to account for kernel versions and use the appropriate preprocessor macro to check if MAX_PAGE_ORDER or MAX_ORDER is defined.
Let me just verify that I covered all the necessary aspects. Yes, I'm confident that this accurately explains the vulnerability, root cause, and the proper fix.
|
| 65/1 |
2026/09/09 16:59 |
agent |
history-explorer |
16m
Model:
Instruction:
You are an experienced Linux kernel developer researching prior art for fixing a kernel bug.
You are given a bug explanation. This explanation details the root cause of the bug resulting
from debugging, but does not provide the final fix strategy. Your goal is to explore how
similar bugs were fixed in the past in the same subsystem or files.
CRITICAL: Do NOT attempt to debug the issue further or write a patch for it yourself.
Your ONLY objective is to research and provide the necessary historical context.
Use the git-log tool with the Since parameter set to "3 years" to focus on recent history.
Search for commits that address issues with similar root causes (e.g. similar missing locks,
incorrect refcounting, or similar error path bugs) in the affected files.
Your final reply must summarize your findings: what idioms, locking rules, or common patterns
should be followed when writing a fix for this bug based on how previous similar bugs were addressed.
If you find no relevant past fixes, clearly state that.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
The explanation of the root cause of the bug is:
An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
Reply: Based on a review of the kernel history, the proposed fix aligns perfectly with established idioms and patterns used to resolve similar bugs across the kernel.
Here is a summary of how similar issues have been addressed in the past:
### 1. Handling `get_order(0)` and Undefined Behavior
Passing `0` to `get_order()` or `ilog2()` is known to cause undefined behavior, often resulting in a shift-out-of-bounds (since it underflows and produces a massive shift exponent).
* **`null_blk` (Commit `95491fb05105`)**: A similar bug occurred where a `zone_size` of `0` was passed to `ilog2()`, causing a shift-out-of-bounds. The fix involved validating the input to ensure it was non-zero and adding a defensive check to return early if the size was `0`.
* **`perf` (Commit `dbc48c8f41c2`)**: The driver was passing a `0` to `get_order()` due to a truncation issue. The commit message explicitly notes that the result of `get_order(0)` is undefined and fixed it by validating the maximum supported value before the call.
**Conclusion for `sg.c`:** Updating the local variable `num = PAGE_SIZE` when `num < PAGE_SIZE` is the correct approach. It ensures that `get_order()` is never called with `0`, preventing the undefined behavior and subsequent shift-out-of-bounds.
### 2. Bounding Allocation Orders to `MAX_PAGE_ORDER`
Unbounded sizes passed to `get_order()` can result in an `order` that exceeds `MAX_PAGE_ORDER`. This leads to either a shift-out-of-bounds when calculating the size (`1 << (PAGE_SHIFT + order)`) or a `WARN_ON_ONCE` in the page allocator.
* **`net/smc` (Commit `4cc5130ee84a`)**: To prevent `alloc_pages()` from failing with a warning when requesting physically contiguous buffers, the allocation size was explicitly capped using `min_t(int, bufsize, PAGE_SIZE << MAX_PAGE_ORDER)`.
* **`mm/compaction` (Commit `d1366e74342e`)**: A bogus compound order caused a UBSAN shift-out-of-bounds warning `(1UL << order)`. The fix was to explicitly add an `order <= MAX_PAGE_ORDER` check before performing the shift.
* **`scsi/mpi3mr` (Commit `8c6b808c8c2a`)**: The driver was attempting to allocate massive diagnostic buffers, triggering a `MAX_PAGE_ORDER` warning in the allocator. The fix added a `get_order(size) > MAX_PAGE_ORDER` check to fall back to a retry loop with a smaller size.
**Conclusion for `sg.c`:** Capping the order with `order = min_t(int, order, MAX_PAGE_ORDER)` is a standard and safe kernel idiom. Since `sg_build_indirect()` already contains a fallback loop (`retry:`) that decrements the `order` and tries again if `alloc_pages()` fails, bounding it to `MAX_PAGE_ORDER` upfront elegantly prevents both the shift-out-of-bounds and the allocator warning without requiring any structural changes to the loop.
|
| 66/2 |
2026/09/09 16:59 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 6356
output: 31
thoughts: 210
Thoughts: **Analyzing the Bug in sg.c**
Okay, so we've got a bug in `drivers/scsi/sg.c`, and it looks like it stems from a missed update to a local variable after module parameter validation, compounded by either an unbounded shift operation or an invalid `alloc_pages()` order. The proposed fix, which seems reasonable at first glance, caps the `order` using `MAX_PAGE_ORDER` and corrects the `num` variable. Now, before I jump to any conclusions, I need to understand if this is a novel issue or if there are similar fixes already in the code. I'm thinking the best way to approach this is to look at how past bugs have been addressed in this area.
My instinct is to use `git log` to dig through the history of `drivers/scsi/sg.c` and potentially the entire `drivers/scsi/` directory. I'll need to craft a few specific search terms to narrow my focus. I'm going to look for commits related to "scatter_elem_sz," "get_order," occurrences of "MAX_PAGE_ORDER" or "MAX_ORDER," and any mentions of "shift-out-of-bounds" or "UBSAN" since those seem like likely culprits for similar issues. Let's start by getting a history of the file itself and see what the initial hits are. Hopefully, we can find some good clues there.
|
| 67/2 |
2026/09/09 16:59 |
tool |
git-log |
0m
Args: map[PathPrefix:drivers/scsi/sg.c Since:3 years]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
5e2fde1a9433 block: pass io_comp_batch to rq_end_io_fn callback
0e1677654259 scsi: sg: Fix occasional bogus elapsed time that exceeds timeout
90449f2d1e1f scsi: sg: Do not sleep in atomic context
]
|
| 68/2 |
2026/09/09 16:59 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 7189
output: 44
thoughts: 56
Thoughts: **Analyzing Potential Fixes for Scatter Element Size and Order Issues**
Okay, so none of the presented options immediately jump out as the perfect solution for those `scatter_elem_sz` or `get_order` problems I've been wrestling with. I need to dig deeper. My instinct tells me the issue is probably in the SCSI subsystem, specifically around the scatter-gather operations. Let's start by looking for `scatter_elem_sz` directly within the `drivers/scsi/sg.c` file. I'll use `git log` with the `-G` flag. That should help me zero in on commits that touch that specific string, which will hopefully reveal relevant changes or context. Hopefully, this approach will illuminate any recent modifications or discussions related to this problematic area.
|
| 69/2 |
2026/09/09 17:00 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c Since:10 years]
Results:
|
| 70/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 7466
output: 36
thoughts: 52
Thoughts: **Investigating the Longevity of `scatter_elem_sz`**
Okay, hold on a second. It just struck me that the variable `scatter_elem_sz`… could it possibly have remained untouched for an entire decade? That seems highly improbable, but it warrants immediate investigation. I need to confirm whether it's even still in use. My next step is clear. I’m going to dive straight into `drivers/scsi/sg.c`. That's the most likely place for anything SCSI-related, and it'll give me the definitive answer. Hopefully, the code comments provide some history, even if the variable itself is still present. This needs to be checked.
|
| 71/2 |
2026/09/09 17:00 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 72/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 7761
output: 27
thoughts: 76
Thoughts: Okay, here's my take on those commits, framed as my own thought process:
**Diving into SCSI and Block Layer Integration**
Alright, let's take a look at these two seemingly related commits: `"10db10d144c0 sg: convert the indirect IO path to use the block layer"` and the follow-up `"6460e75a104d [SCSI] sg: fixes for large page_size"`. Given that `10db10d144c0` seems to be the core change, I'll start with the follow up commit `6460e75a104d` to see if this provides further insight into the larger change. I need to understand what triggered the need to deal with larger page sizes, and how it relates to the first commit's ambition to integrate the indirect I/O path with the block layer. Understanding the fixes made here will definitely help frame the larger context. The fact that fixes are needed with larger page sizes immediately suggest some interaction with memory mapping or data transfer structures that are being exposed or used in a way they weren't before. It makes me wonder if there's a performance bottleneck or perhaps an issue with how the SG driver was handling large I/O requests previously. I'll need to dig deeper into the code to figure out what precisely was improved.
|
| 73/2 |
2026/09/09 17:00 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 74/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 12568
output: 26
thoughts: 78
Thoughts: Here's my thinking about that code...
**Digging into the Scatter/Gather Issue**
Okay, so I'm looking at this issue, and it's pointing me directly to commit `6460e75a104d`. Right, that's the one that introduced `scatter_elem_sz` in sysfs, and, more importantly, the logic within `sg_build_indirect` that is apparently causing trouble. Seems like that's the point where things started to go sideways. Now, wait a minute... I seem to recall another commit related to indirect IO. Let's see... ah, yes! `10db10d144c0`. That's the conversion to using the block layer for the indirect IO path. I'll need to double-check that this is what happened, as there are often subtle effects in that type of change. So, the likely area of impact seems to be near this conversion. I should check if there were any pre-existing code issues that may have become uncovered after these changes.
|
| 75/2 |
2026/09/09 17:00 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 76/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 22545
output: 44
thoughts: 60
Thoughts: Okay, here's my take on those thoughts, framed as my own:
**Analyzing the SCSI SG Driver's Indirect Build**
Right, so that commit, `10db10d144c0`, introduced that `get_order(num)` function and the retry loop. Makes sense; likely trying to manage some allocation challenges. I need to understand how this is used, especially as it relates to managing the SCSI Generic driver. Let's dig into `sg_build_indirect` in `drivers/scsi/sg.c`. I need to figure out how this `order` variable, now introduced, is being used to build the indirect descriptor. I have a feeling there's some memory management nuance at play. The previous implementation I know by heart, so changes in this area are always of primary concern. I will now examine that function carefully, specifically to see how the new `order` variable impacts the buffer handling. I will look for allocation strategies in particular.
|
| 77/2 |
2026/09/09 17:00 |
tool |
git-log |
0m
Args: map[CodeRegexp:order = get_order PathPrefix:drivers/scsi/sg.c Since:10 years]
Results:
|
| 78/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 22869
output: 44
thoughts: 58
Thoughts: Here's my summary, as if I were thinking these things:
**Digging into that `sg.c` Code**
Okay, so I'm trying to track down this issue. Let's see... the `order = get_order(num);` bit was introduced way back in 2008. Right, that gives me a reasonable starting point. Time to dig into the `drivers/scsi/sg.c` code. My gut feeling is it might be related to how they're handling scatter/gather element sizes or perhaps even the way `get_order` is used. I'm going to look specifically for any subsequent fixes in that area, anything that touches on either `scatter_elem_sz` or `get_order`. Hopefully, that will give me some clues about any related problems they might have encountered in the past and the solutions that were implemented. It's a long shot, but often the best way to tackle this is to see if someone else already ran into a similar snag.
|
| 79/2 |
2026/09/09 17:00 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c Since:20 years]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 80/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 23249
output: 44
thoughts: 53
Thoughts: Okay, here's my take on those thoughts, framed as my own:
**Digging into Scatter/Gather Size Limits**
Right, so I've been looking at this `scatter_elem_sz` thing in `drivers/scsi/sg.c`. It looks like there aren't any other obvious fixes for that specific variable within that file. Hmm... I wonder if there are some larger architectural constraints at play here, maybe related to page size limits? I should check if `MAX_PAGE_ORDER` or `MAX_ORDER` in `drivers/scsi/sg.c` have any impact here. Those constants could be indirectly affecting the maximum scatter/gather element size in a way that I'm not seeing immediately. I need to investigate if those are used in calculations or comparisons related to memory allocation or buffer management within that driver. It's a classic case of looking for the root cause in seemingly unrelated areas. Gotta get the bigger picture.
|
| 81/2 |
2026/09/09 17:00 |
tool |
git-log |
0m
Args: map[CodeRegexp:MAX_PAGE_ORDER PathPrefix:drivers/scsi/sg.c Since:20 years]
Results:
|
| 82/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 23561
output: 42
thoughts: 19
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Investigating a SCSI Driver Parameter**
Hmm, I was just mulling over something related to SCSI drivers, and specifically, I was thinking about `drivers/scsi/sg.c`. It's a key area, handling the generic SCSI access layer. What immediately popped into my head was that potential issue regarding `MAX_ORDER`. I'm wondering what the current configuration of `MAX_ORDER` is within that specific module. Is it set appropriately for modern hardware, considering increasingly large block sizes and potentially extensive scatter-gather lists that we're seeing? Could a subtle misconfiguration there be causing some of the performance bottlenecks or, even worse, data integrity issues, that we sometimes chase down in the field? I need to refresh my memory on the interactions of `MAX_ORDER` with the scatter-gather list limitations in sg.c. Time for some code spelunking to see where we're at with it.
|
| 83/2 |
2026/09/09 17:00 |
tool |
git-log |
0m
Args: map[CodeRegexp:MAX_ORDER PathPrefix:drivers/scsi/sg.c Since:20 years]
Results:
|
| 84/2 |
2026/09/09 17:00 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 23845
output: 33
thoughts: 41
Thoughts: Okay, here's my take on those thoughts, framed as my own, given my expertise:
**My Kernel Bug Hunt Strategy**
Alright, time to get serious about tracking down potential memory allocation issues in the kernel. My initial thought process is pretty straightforward: I need a focused search strategy to pinpoint code that might be vulnerable. The most likely candidates for subtle, yet serious, memory-related bugs are situations where we're calculating order sizes in a way that’s open to abuse or misuse. My hypothesis is that problematic allocations will likely arise when `get_order()` is being used in a way that suggests either an unbounded allocation request or an allocation whose upper bound is incorrectly handled. Specifically, I'm thinking of where the value passed to it is either entirely unconstrained (e.g. not validated or subject to some reasonable upper limit) or possibly artificially bounded by something like `MAX_PAGE_ORDER`. This latter case raises a flag because `MAX_PAGE_ORDER` is an implicit limit – if the *intended* limit is less, we could still have an overflow issue, an out-of-bounds access, or similar. Essentially, I need to look for calls to `get_order()` with suspicious arguments and scrutinize the *context* surrounding those calls to see if the allocation logic is sound. This is where the real work begins, I know I'll have to investigate those findings and really dive into the surrounding code.
|
| 85/2 |
2026/09/09 17:01 |
tool |
git-log |
4m
Args: map[CodeRegexp:min_t.*MAX_PAGE_ORDER Since:3 years]
Results: map[Output:4aa4abf1f14b mm/page_alloc: optimize free_contig_range()
4cc5130ee84a net/smc: cap allocation order for SMC-R physically contiguous buffers
1d3160c7cba3 drm/ttm/pool: Restructure the pool allocation code
3a7e02c040b1 minmax: avoid overly complicated constant expressions in VM code
72801513b2bf mm: set pageblock_order to HPAGE_PMD_ORDER in case with !CONFIG_HUGETLB_PAGE but THP enabled
5e0a760b4441 mm, treewide: rename MAX_ORDER to MAX_PAGE_ORDER
]
|
| 86/2 |
2026/09/09 17:05 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 24401
output: 25
thoughts: 16
Thoughts: Okay, here's my attempt at summarizing the thought process, as requested, tailored for an expert audience and presented in the first person:
**Initial Assessment: Code Snippet - 4cc5130ee84a**
Alright, let's take a look at this code snippet, identified as `4cc5130ee84a`. Immediately, my brain starts to race through potential implications based on the context I *should* have (I'm assuming this is coming to me within a relevant project). My first mental checklist goes something like this:
* **Origin:** Where did this come from? Is it new code, a refactor, a bug fix, or something else? Understanding the history of this piece is critical. Is it from a familiar component of the code, or something completely new that I'll need to wrap my head around?
* **Context:** What's the surrounding code like? What's the larger system architecture? I'm already mentally searching for related files, classes, or modules. How does this fit into the broader narrative of the system? Any prior context would be beneficial, as I can start to make connections. I'm already anticipating what to expect, and my mind is racing through what data structures or functions could be included.
* **Purpose:** What's the intended functionality? What problem is this supposed to be solving? Is there any documentation available, even minimal, that can point me in the right direction? I'm already forming hypotheses about its purpose.
* **Suspects:** Based on past experiences and the style of the snippet, I'm mentally compiling a list of potential problem areas, like memory leaks, concurrency issues, edge cases, etc. My internal compiler is checking for obvious errors, such as syntax errors, function calls, or logical flaws.
Now, I'll start with the specific code snippet and apply these initial thoughts to it. Time to dive in.
|
| 87/2 |
2026/09/09 17:05 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 4cc5130ee84adcc8904772df44d64e59727c72bd
Author: D. Wythe <alibuda@linux.alibaba.com>
Date: Wed Apr 29 10:16:37 2026 +0800
net/smc: cap allocation order for SMC-R physically contiguous buffers
The alloc_pages() cannot satisfy requests exceeding MAX_PAGE_ORDER,
and attempting such allocations will lead to guaranteed failures
and potential kernel warnings.
For SMCR_PHYS_CONT_BUFS, cap the allocation order to MAX_PAGE_ORDER.
This ensures the attempts to allocate the largest possible physically
contiguous chunk succeed, instead of failing with an invalid order.
This also avoids redundant "try-fail-degrade" cycles in
__smc_buf_create().
For SMCR_MIXED_BUFS, no cap is needed: if the order exceeds
MAX_PAGE_ORDER, alloc_pages() will silently fail (__GFP_NOWARN)
and automatically fall back to virtual memory.
Signed-off-by: D. Wythe <alibuda@linux.alibaba.com>
Reviewed-by: Dust Li <dust.li@linux.alibaba.com>
Reviewed-by: Simon Horman <horms@kernel.org>
Reviewed-by: Sidraya Jayagond <sidraya@linux.ibm.com>
Link: https://patch.msgid.link/20260429021637.21815-1-alibuda@linux.alibaba.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
diff --git a/net/smc/smc_core.c b/net/smc/smc_core.c
index e2d083daeb7e..cf6b620fef05 100644
--- a/net/smc/smc_core.c
+++ b/net/smc/smc_core.c
@@ -2440,6 +2440,10 @@ static int __smc_buf_create(struct smc_sock *smc, bool is_smcd, bool is_rmb)
/* use socket send buffer size (w/o overhead) as start value */
bufsize = smc->sk.sk_sndbuf / 2;
+ /* limit bufsize for physically contiguous buffers */
+ if (!is_smcd && lgr->buf_type == SMCR_PHYS_CONT_BUFS)
+ bufsize = min_t(int, bufsize, PAGE_SIZE << MAX_PAGE_ORDER);
+
for (bufsize_comp = smc_compress_bufsize(bufsize, is_smcd, is_rmb);
bufsize_comp >= 0; bufsize_comp--) {
if (is_rmb) {
]
|
| 88/2 |
2026/09/09 17:05 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 25587
output: 31
thoughts: 51
Thoughts: Okay, here's my interpretation of those thoughts, framed as my own, given my expertise:
**Reasoning Through a Recent Kernel Commit**
Right, so this commit's focus is on the allocation size, specifically limiting it to `MAX_PAGE_ORDER`. Makes perfect sense. The goal is clearly to prevent the kernel from trying to allocate excessively large chunks of memory, which would lead to guaranteed failures and those nasty kernel warnings we all dread. We want to avoid blowing up the system.
Now, my next step would be to dig deeper. I need to understand the history here. I'm going to search the kernel source and commit logs for instances of `get_order`, especially when it's handling a value of `0`, and also for any signs of "shift-out-of-bounds" errors. This is crucial for context. I need to see where this limit was *needed*, how the code evolved to *require* this safeguard, and whether this addresses a long-standing issue or a newly discovered vulnerability. I want to see if this is a symptom or a cure. This search will help me understand the specific scenarios this commit is protecting against and if it's a good fix, a band-aid, or needs further thought.
|
| 89/2 |
2026/09/09 17:05 |
tool |
git-log |
4m
Args: map[CodeRegexp:shift-out-of-bounds Since:3 years]
Results:
|
| 90/2 |
2026/09/09 17:10 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 25943
output: 31
thoughts: 28
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Debugging Divergence: Contextualizing the Error**
Okay, wait a minute. The critical clue here, the "shift-out-of-bounds" error, *isn't* directly in the code itself, but rather it's buried within the commit message log. That changes the game. My immediate instinct is to bypass a code-level deep dive *for now*. Given that this is a reported error, and a potentially serious one at that, I'm going to start with the commit history search. That's the most effective first step. Let's see if we can find relevant commits and identify potential contributing factors via the messages. That is where I can obtain context of the error. A thorough search of the commit messages is in order.
|
| 91/2 |
2026/09/09 17:10 |
tool |
git-log |
0m
Args: map[MessageRegexps:[shift-out-of-bounds] Since:3 years]
Results: map[Output:a60fd8c6dbaa usb: atm: usbatm: fix invalid ci_range initialization
323751a604e7 ntfs: reject invalid sectors_per_cluster in the boot sector
3838e80fcfb3 nvme: skip the zoned limits update if the zone info query failed
95491fb05105 null_blk: fix UBSAN shift-out-of-bounds when zone_size is 0 or overflows
038cf48b3170 i3c: dw: avoid shift-out-of-bounds when DAA assigns no devices
aef96eead286 net/sched: cls_u32: validate offshift to prevent shift-out-of-bounds
39e88f28fb32 netfilter: nft_payload: fix mask build for partial field offload
1d26f125501f regulator: mt6358: use regmap helper to read fixed LDO calibration
40f0b1047918 xfrm: validate selector family and prefixlen during match
1b1acf2dada0 ACPI: CPPC: Suppress UBSAN warning caused by field misuse
]
|
| 92/2 |
2026/09/09 17:10 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 26473
output: 26
thoughts: 40
Thoughts: Okay, here's my interpretation of that thought as if it were my own, presented to a field expert:
**Addressing a Subtle UBSAN Vulnerability in `null_blk`**
Alright, looking at this commit, `95491fb05105`, it's clear they're tackling a `null_blk` issue. The phrase "fix UBSAN shift-out-of-bounds" immediately flags this as a potentially nasty memory safety problem, likely caught by the Undefined Behavior Sanitizer. I'm guessing the vulnerability lies in the way shifts are being handled, specifically where the size of a "zone" or region is zero, or perhaps when calculated, leads to an integer overflow. We've got to be careful, as shifting can quickly lead to undefined behavior if the shift amount exceeds the bit-width of the operand, or if the calculation results in an undefined value. It sounds like they are working to address cases that could arise from miscalculations, especially edge cases like zero-sized zones or overflow conditions which could lead to shifts that fall outside the bounds of defined behavior.
|
| 93/2 |
2026/09/09 17:10 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 95491fb05105b61050cb623a5e0227eb26aa3525
Author: Rik van Riel <riel@surriel.com>
Date: Sat Aug 8 11:42:39 2026 -0400
null_blk: fix UBSAN shift-out-of-bounds when zone_size is 0 or overflows
null_zone_no() does sect >> ilog2(dev->zone_size_sects). When
zone_size_sects is 0, ilog2(0) returns -1, producing shift exponent -1
which UBSAN reports as shift-out-of-bounds.
UBSAN: shift-out-of-bounds in drivers/block/null_blk/zoned.c:21:14
shift exponent -1 is negative
Call Trace:
null_zone_no drivers/block/null_blk/zoned.c:21 [inline]
null_process_zoned_cmd+0xf76/0xf80 drivers/block/null_blk/zoned.c:728
null_handle_cmd drivers/block/null_blk/main.c:1455 [inline]
null_queue_rq+0x8bc/0xe70 drivers/block/null_blk/main.c:1703
__blk_mq_issue_directly block/blk-mq.c:2694 [inline]
blk_mq_try_issue_directly+0x3f4/0x880 block/blk-mq.c:2754
blk_mq_submit_bio+0x20c0/0x2a40 block/blk-mq.c:3208
submit_bio_noacct_nocheck+0x2f4/0xa40 block/blk-core.c:790
block_read_full_folio+0x7a6/0x810 fs/buffer.c:2463
filemap_read_folio+0x12c/0x3a0 mm/filemap.c:2510
read_part_sector+0xb6/0x2b0 block/partitions/core.c:724
adfspart_check_ICS+0xb1/0x960 block/partitions/acorn.c:357
check_partition block/partitions/core.c:143 [inline]
blk_add_partitions block/partitions/core.c:591 [inline]
bdev_disk_changed+0x851/0x17a0 block/partitions/core.c:695
blkdev_get_whole+0x372/0x510 block/bdev.c:751
add_disk_final block/genhd.c:412 [inline]
add_disk_fwnode+0x24b/0x3a0 block/genhd.c:606
null_add_dev+0x130b/0x1d70 drivers/block/null_blk/main.c:2052
nullb_device_power_store+0x240/0x380 drivers/block/null_blk/main.c:501
configfs_write_iter+0x337/0x430 fs/configfs/file.c:229
Syzkaller triggers this by creating a zoned null_blk device via
configfs. The Call Trace shows configfs_write_iter in configfs/file.c
handling a write to power file, which calls nullb_device_power_store in
main.c, which calls null_add_dev in main.c, which calls add_disk in
genhd.c, which triggers partition scan via bdev_disk_changed in
partitions/core.c.
A zoned null_blk device with zone_size 0 should not be legal. Existing
code tries to reject it via is_power_of_2() check in zoned.c and
!zone_size check in main.c, but syzkaller can still reach
null_zone_no() with zone_size_sects 0 via two paths:
1. Direct 0 via configfs: zone_size attribute store in main.c has
NULLB_DEVICE_ATTR(zone_size, ulong, NULL) with no validation callback,
so echo 0 > zone_size succeeds before power store. If zoned is false
at power store time, the !zone_size check in main.c is skipped, and
later zoned set true leaves zone_size 0.
2. Large value overflow: mb_to_sects() in zoned.c does
(sector_t)mb * SZ_1M >> SECTOR_SHIFT which is mb * 2048. If mb is
1UL << 53 (9PB), mb * 2048 overflows 64-bit to 0. The value is
power-of-two so is_power_of_2() passes, but mb_to_sects() returns 0.
Check for zero zone_size explicitly in null_init_zoned_dev() in
zoned.c, returning -EINVAL with "must be non-zero power-of-two".
Check for zero zone_size_sects after mb_to_sects() conversion,
returning -EINVAL for overflow case. Keep defensive check in
null_zone_no() returning 0 for zero sectors to avoid shift out-of-bounds
even if zero slips through.
This change should be safe because zone_size is set once in
null_init_zoned_dev() under device lock and never changes after, and 0
is never valid for a zoned device. Returning -EINVAL at init time fails
device creation early with clear error, while defensive return 0 in
null_zone_no() makes zoned command fail via offline zone check.
No new locking is introduced.
Reported-by: syzbot+abd6a8dca0f2b7726060@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=abd6a8dca0f2b7726060
Link: https://lore.kernel.org/all/6a75205c.01d0871a.3a0d52.0033.GAE@google.com/
Fixes: 8a3cf049af68 ("null_blk: add zoned block device emulation")
Cc: stable@vger.kernel.org
Assisted-by: Hermes:muse-spark-1.2 syzkaller
Signed-off-by: Rik van Riel <riel@surriel.com>
Reviewed-by: Damien Le Moal <dlemoal@kernel.org>
Link: https://patch.msgid.link/20260808114239.69167f68@fangorn
Signed-off-by: Jens Axboe <axboe@kernel.dk>
diff --git a/drivers/block/null_blk/zoned.c b/drivers/block/null_blk/zoned.c
index 384bdce6a9b7..7e9b5ffb9e84 100644
--- a/drivers/block/null_blk/zoned.c
+++ b/drivers/block/null_blk/zoned.c
@@ -18,6 +18,8 @@ static inline sector_t mb_to_sects(unsigned long mb)
static inline unsigned int null_zone_no(struct nullb_device *dev, sector_t sect)
{
+ if (WARN_ON_ONCE(!dev->zone_size_sects))
+ return 0;
return sect >> ilog2(dev->zone_size_sects);
}
@@ -56,8 +58,8 @@ int null_init_zoned_dev(struct nullb_device *dev,
sector_t sector = 0;
unsigned int i;
- if (!is_power_of_2(dev->zone_size)) {
- pr_err("zone_size must be power-of-two\n");
+ if (!dev->zone_size || !is_power_of_2(dev->zone_size)) {
+ pr_err("zone_size must be non-zero power-of-two\n");
return -EINVAL;
}
if (dev->zone_size > dev->size) {
@@ -88,6 +90,10 @@ int null_init_zoned_dev(struct nullb_device *dev,
zone_capacity_sects = mb_to_sects(dev->zone_capacity);
dev_capacity_sects = mb_to_sects(dev->size);
dev->zone_size_sects = mb_to_sects(dev->zone_size);
+ if (!dev->zone_size_sects) {
+ pr_err("zone_size too large or too small, leads to zero sectors\n");
+ return -EINVAL;
+ }
dev->nr_zones = round_up(dev_capacity_sects, dev->zone_size_sects)
>> ilog2(dev->zone_size_sects);
]
|
| 94/2 |
2026/09/09 17:10 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 29076
output: 37
thoughts: 87
Thoughts: **Addressing a Null Block Issue**
Okay, so I've been looking at this `null_blk` fix. The root cause, as I understand it, is this: `zone_size` was inadvertently set to zero. This, in turn, fed directly into an `ilog2(0)` call, which, as we all know, returns -1. And -1, when used in a shift operation, becomes a recipe for disaster - a shift-out-of-bounds error. Classic.
The fix, and a good one at that, is straightforward: We validate the `zone_size` parameter during initialization to prevent this from happening in the first place. That's good defensive programming. Added a check, just to be extra sure.
Now, let's dig a bit deeper. I want to see if this pattern, or something similar, has cropped up elsewhere. I'm going to run some queries through the kernel history. Specifically, I'm searching for instances where `get_order` is used in conjunction with "shift-out-of-bounds." This should help me identify any similar vulnerabilities and get a broader understanding of the context of this issue. Hopefully, it'll provide insights that are helpful for other future fixes.
|
| 95/2 |
2026/09/09 17:10 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order shift-out-of-bounds] Since:3 years]
Results:
|
| 96/2 |
2026/09/09 17:10 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 29475
output: 32
thoughts: 20
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Kernel Investigation Strategy**
Okay, so I'm looking at something… specifically, I need to figure out the history of `get_order` and how it might interact with `UBSAN` (Undefined Behavior Sanitizer) within the kernel. My immediate thought is to dive straight into the kernel's commit history. This is going to be the most efficient way to track down any potential issues, related patches, or discussions surrounding these two elements, hopefully in combination, which will narrow down the focus significantly. I'm going to start with a combined search – `git log -S get_order -S UBSAN` will likely be my first query, but I'll probably broaden it quickly if that's too specific. I anticipate needing to refine the search terms, perhaps focusing on specific subsystems or code areas if the initial results are too broad. I’m thinking memory management and error handling will be key areas to investigate initially, so I might add those terms or restrict the search to relevant paths if I need to. I'm also preparing myself to analyze commit messages thoroughly for context and potential links to bug reports or mailing list discussions. The goal is to establish a timeline of any relevant changes and understand the rationale behind them.
|
| 97/2 |
2026/09/09 17:10 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order UBSAN] Since:3 years]
Results:
|
| 98/2 |
2026/09/09 17:10 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 29811
output: 31
thoughts: 19
Thoughts: Here's my take on those thoughts:
**Investigating a Potential Kernel Issue**
Okay, so I need to dig into the kernel history. My gut feeling tells me there might be an issue with how we're handling orders, possibly related to an uninitialized variable or a situation where something is becoming `undefined`. Therefore, I'm going to kick things off by searching the kernel history for occurrences of both `get_order` and `undefined`. This will give me a focused starting point and hopefully illuminate what's going wrong. I'm hoping this dual search will allow me to narrow down the source of the potential bug more efficiently.
|
| 99/2 |
2026/09/09 17:10 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order undefined] Since:3 years]
Results: map[Output:32c9625638c2 tmpfs/ramfs: let memfd_create() work on nommu
dbc48c8f41c2 perf: Prevent passing zero nr_pages to rb_alloc_aux()
]
|
| 100/2 |
2026/09/09 17:10 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 30063
output: 25
thoughts: 16
Thoughts: Okay, here's my interpretation of that seemingly random string, presented as a first-person expert analysis:
**Decoding the Obfuscated Signifier**
Alright, that gibberish immediately triggers my pattern-recognition circuits. "dbc48c8f41c2"... that has the unmistakable *feel* of a hash. Given the length, and the character set (hexadecimal), it's highly likely this is a SHA-1 hash, or potentially MD5, although SHA-1 is more common these days. The absence of an obvious salt means there's a good chance this hash could be vulnerable to rainbow table attacks if I can determine the hashing function.
My initial assumption leans towards a cryptographic hash due to its structure. If it turns out that I am mistaken, it could be a variety of other formats that share a similar composition such as a short URL (though the length seems off) or an encoding such as Base64, but the likelihood is low.
My next steps would depend on the context. Knowing where I found this code fragment is key. Where did this come from? If it's in a database record, an API response, or within a larger chunk of code, the purpose will become much clearer. If it's a file name, then it's probably representing something else entirely, like a version control identifier or a unique asset ID. I will look for any clues. I’ll start by doing a quick search for `dbc48c8f41c2` online. The goal is to see if it's been previously identified or if its context is documented somewhere. This could yield valuable insights.
Then, I'd need to consider the system's security profile. Are we dealing with something high-security, low-security, or something in-between? If it's a low-security environment, I'd try a brute-force approach with common passwords or phrases if I'm able to. If it's high-security, I would immediately start thinking about how to perform a cryptanalysis. I'd begin by verifying the hash algorithm using an online hash checker. Then, I would consider tools. Tools like hashcat and John the Ripper are my best friends. I will try to find the "plaintext" it represents.
|
| 101/2 |
2026/09/09 17:10 |
tool |
git-show |
0m
Args:
Results: map[Output:commit dbc48c8f41c208082cfa95e973560134489e3309
Author: Adrian Hunter <adrian.hunter@intel.com>
Date: Mon Jun 24 23:10:59 2024 +0300
perf: Prevent passing zero nr_pages to rb_alloc_aux()
nr_pages is unsigned long but gets passed to rb_alloc_aux() as an int,
and is stored as an int.
Only power-of-2 values are accepted, so if nr_pages is a 64_bit value, it
will be passed to rb_alloc_aux() as zero.
That is not ideal because:
1. the value is incorrect
2. rb_alloc_aux() is at risk of misbehaving, although it manages to
return -ENOMEM in that case, it is a result of passing zero to get_order()
even though the get_order() result is documented to be undefined in that
case.
Fix by simply validating the maximum supported value in the first place.
Use -ENOMEM error code for consistency with the current error code that
is returned in that case.
Fixes: 45bfb2e50471 ("perf: Add AUX area to ring buffer for raw data streams")
Signed-off-by: Adrian Hunter <adrian.hunter@intel.com>
Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Link: https://lore.kernel.org/r/20240624201101.60186-6-adrian.hunter@intel.com
diff --git a/kernel/events/core.c b/kernel/events/core.c
index 6b0a66ed2ae3..e70d3dd65a13 100644
--- a/kernel/events/core.c
+++ b/kernel/events/core.c
@@ -6496,6 +6496,8 @@ static int perf_mmap(struct file *file, struct vm_area_struct *vma)
return -EINVAL;
nr_pages = vma_size / PAGE_SIZE;
+ if (nr_pages > INT_MAX)
+ return -ENOMEM;
mutex_lock(&event->mmap_mutex);
ret = -EINVAL;
]
|
| 102/2 |
2026/09/09 17:10 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 31210
output: 35
thoughts: 51
Thoughts: Okay, here's my interpretation of those thoughts, presented as my own mental process, given my expertise:
**Investigating a `get_order()` Vulnerability**
Alright, this commit notice is flagging a potential problem with `get_order()`. The key takeaway is that calling it with zero is *undefined behavior*. That's a red flag. Undefined behavior means the compiler can do literally *anything*, and that's the kind of thing that can lead to security vulnerabilities or outright crashes. The fix, apparently, involves validating the input against a maximum supported value, likely related to page order.
So, I need to dig deeper. I want to understand the *context* here. What's the impact of passing zero to `get_order()`? Why is it undefined? Where does this function get called, and what kind of data is being passed to it? The validation fix suggests the issue is related to `MAX_PAGE_ORDER`.
Therefore, my next step is clear: I'm going to leverage my familiarity with the kernel's history. I'll search for occurrences of both `get_order` and `MAX_PAGE_ORDER` to find related commits, patches, and discussions. I'm hoping to uncover the root cause, understand the specific scenario that triggers this, and assess the broader implications for the system's stability and security. By examining the surrounding code and the reasoning behind these changes, I'll build a more complete picture. I'll be looking for architectural discussions, performance considerations, and of course, any reports of actual bugs or exploits related to this. This seems like a potentially important piece of information, and I need to fully understand its implications.
|
| 103/2 |
2026/09/09 17:11 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order MAX_PAGE_ORDER] Since:3 years]
Results:
|
| 104/2 |
2026/09/09 17:11 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 31662
output: 33
thoughts: 21
Thoughts: Here's my take on those thoughts:
**Kernel History Search in Progress**
Alright, time to dig into the kernel's history. My immediate focus is on understanding the `get_order` function and the `MAX_ORDER` constant. These are fundamental to memory management within the kernel, and I need to see how they've evolved, how they're used, and if there have been any significant changes or issues related to them. I'm thinking I'll start with a straightforward search for both of these within the commit logs. This should quickly give me a timeline, any related bug fixes, and potentially point me towards the relevant subsystems if this is about page allocation or specific architectures. The goal is to get a handle on the historical context and spot any potential areas for deeper investigation based on the commit messages and code modifications related to these core elements. Let's see what the data reveals.
|
| 105/2 |
2026/09/09 17:11 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order MAX_ORDER] Since:3 years]
Results: map[Output:c7355d755698 mm/slub: simplify the last resort slab order calculation
]
|
| 106/2 |
2026/09/09 17:11 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 31942
output: 27
thoughts: 18
Thoughts: Okay, here's my interpretation of what's going on, formatted as you requested:
**Deconstructing `c7355d755698`**
Alright, let's dive in. I'm looking at `c7355d755698`. My initial instinct is to treat this as some kind of identifier. Given its alphanumeric nature and the typical use cases I've encountered, it could be a hash, a commit ID, a unique transaction code, or even a session token. Without context, it's hard to be definitive, but my experience tells me I need to start by considering these possibilities. I'll need to determine the system or environment it originates from to be able to fully understand its meaning. I'll need to look at the surrounding data or code to see if there's a pattern, a key, or documentation that might unlock its purpose. My next steps would be to trace its usage, see where it's stored, how it's generated, and what information is associated with it. From there, I can begin to infer the significance of `c7355d755698`.
|
| 107/2 |
2026/09/09 17:11 |
tool |
git-show |
0m
Args:
Results: map[Output:commit c7355d755698a01ff4187a0d2f6ad21ba233dc21
Author: Vlastimil Babka <vbabka@kernel.org>
Date: Fri Sep 8 09:57:13 2023 +0200
mm/slub: simplify the last resort slab order calculation
If calculate_order() can't fit even a single large object within
slub_max_order, it will try using the smallest necessary order that may
exceed slub_max_order but not MAX_ORDER.
Currently this is done with a call to calc_slab_order() which is
unnecessary. We can simply use get_order(size). No functional change.
Signed-off-by: Vlastimil Babka <vbabka@suse.cz>
Reviewed-by: Feng Tang <feng.tang@intel.com>
Reviewed-and-tested-by: Jay Patel <jaypatel@linux.ibm.com>
diff --git a/mm/slub.c b/mm/slub.c
index b36e5eb0ccb7..0710adb5642a 100644
--- a/mm/slub.c
+++ b/mm/slub.c
@@ -4193,7 +4193,7 @@ static inline int calculate_order(unsigned int size)
/*
* Doh this slab cannot be placed using slub_max_order.
*/
- order = calc_slab_order(size, 1, MAX_ORDER, 1);
+ order = get_order(size);
if (order <= MAX_ORDER)
return order;
return -ENOSYS;
]
|
| 108/2 |
2026/09/09 17:11 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 32688
output: 38
thoughts: 32
Thoughts: Okay, here's my interpretation of those thoughts, summarized from a first-person expert perspective:
**Kernel Archaeology Dive**
Alright, I'm going to dig a little deeper here. The initial search scope of three years is likely too narrow. To really understand the context and potential evolution of issues related to "shift-out-of-bounds" and how `get_order` is involved, I need a much broader view. I'm going to expand the search across the *entire* kernel history. This is essential; these types of problems could have roots much earlier, maybe related to refactoring or architectural changes made years ago that are now surfacing as seemingly new bugs. A comprehensive search will allow me to identify related commits, understand how these functionalities interacted historically, and pinpoint the exact moments these problematic patterns emerged or were introduced. The wider search will help find relevant fixes or patches. It could even expose earlier architectural decisions that now present challenges. It's time to put on the archeologist hat and unearth the historical context!
|
| 109/2 |
2026/09/09 17:11 |
tool |
git-log |
0m
Args: map[MessageRegexps:[shift-out-of-bounds get_order] Since:10 years]
Results:
|
| 110/2 |
2026/09/09 17:11 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 32984
output: 38
thoughts: 26
Thoughts: Okay, here's my attempt at summarizing those thoughts from a first-person, expert perspective:
**Kernel Memory Investigation: `shift-out-of-bounds` and `alloc_pages`**
Alright, time to dive into this. I'm going to start by getting a broad view of how these concepts relate. My immediate thought is to query the entire kernel history for instances of `shift-out-of-bounds` and `alloc_pages`. This initial search is crucial; it gives me a historical context. I want to see how these issues have been handled, which sub-systems were involved, and what the prevailing patterns are. It’s about understanding the evolution of the problem space around those two, crucial terms. I'm expecting `alloc_pages` to be a critical part of numerous security investigations over the history of the kernel, and `shift-out-of-bounds` could be related. From there, I can get a feel for the landscape, identify likely areas for deeper investigation, and spot any interesting code or commit patterns that might be relevant to the issue at hand. This should give me a solid foundation before I start targeting specific areas or versions.
|
| 111/2 |
2026/09/09 17:11 |
tool |
git-log |
0m
Args: map[MessageRegexps:[shift-out-of-bounds alloc_pages] Since:10 years]
Results: map[Output:613b065ca32e net: stmmac: fix dma queue left shift overflow issue
]
|
| 112/2 |
2026/09/09 17:11 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 33332
output: 26
thoughts: 17
Thoughts: Okay, here's my attempt at summarizing the thought process, as requested, targeting an expert audience and using the first person:
**Decoding That Hashed Mess**
Alright, so I'm looking at this seemingly random string: `613b065ca32e`. Immediately, my mind starts racing. It's short, which is interesting. Could it be a truncated hash? What algorithm was likely used? I start running through the common suspects: MD5 is a possibility given the character set, but the length is suspicious for a full MD5. SHA-1 is unlikely due to its length. SHA-256? Hmm, potentially, if it’s a partial hash, maybe a prefix? Or could it be something custom?
My initial thought is to try to identify the hash type using online tools. I'd typically employ a hashing library, run a few checks, and see if I can get a hit. I might even attempt a brute-force approach, testing common inputs against a range of hash functions to see if I get any positive results. It's a quick and dirty way to get a starting point.
If the online tools don't give me any immediate answers, I'd probably write a little script to check. I'd whip up a quick Python or Ruby script to compare the string against a set of known hash functions. I'd start with MD5, SHA-1, SHA-256 (truncated), and maybe even some less common ones, just to be thorough.
It's a little puzzle, really. The length and composition of the string are my initial clues, but I need to do some more digging. Depending on the context, I might have more information to go on, the likely source of this string, it's use case, and that could speed up the identification process.
|
| 113/2 |
2026/09/09 17:12 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 613b065ca32e90209024ec4a6bb5ca887ee70980
Author: Junxiao Chang <junxiao.chang@intel.com>
Date: Fri Jul 15 15:47:01 2022 +0800
net: stmmac: fix dma queue left shift overflow issue
When queue number is > 4, left shift overflows due to 32 bits
integer variable. Mask calculation is wrong for MTL_RXQ_DMA_MAP1.
If CONFIG_UBSAN is enabled, kernel dumps below warning:
[ 10.363842] ==================================================================
[ 10.363882] UBSAN: shift-out-of-bounds in /build/linux-intel-iotg-5.15-8e6Tf4/
linux-intel-iotg-5.15-5.15.0/drivers/net/ethernet/stmicro/stmmac/dwmac4_core.c:224:12
[ 10.363929] shift exponent 40 is too large for 32-bit type 'unsigned int'
[ 10.363953] CPU: 1 PID: 599 Comm: NetworkManager Not tainted 5.15.0-1003-intel-iotg
[ 10.363956] Hardware name: ADLINK Technology Inc. LEC-EL/LEC-EL, BIOS 0.15.11 12/22/2021
[ 10.363958] Call Trace:
[ 10.363960] <TASK>
[ 10.363963] dump_stack_lvl+0x4a/0x5f
[ 10.363971] dump_stack+0x10/0x12
[ 10.363974] ubsan_epilogue+0x9/0x45
[ 10.363976] __ubsan_handle_shift_out_of_bounds.cold+0x61/0x10e
[ 10.363979] ? wake_up_klogd+0x4a/0x50
[ 10.363983] ? vprintk_emit+0x8f/0x240
[ 10.363986] dwmac4_map_mtl_dma.cold+0x42/0x91 [stmmac]
[ 10.364001] stmmac_mtl_configuration+0x1ce/0x7a0 [stmmac]
[ 10.364009] ? dwmac410_dma_init_channel+0x70/0x70 [stmmac]
[ 10.364020] stmmac_hw_setup.cold+0xf/0xb14 [stmmac]
[ 10.364030] ? page_pool_alloc_pages+0x4d/0x70
[ 10.364034] ? stmmac_clear_tx_descriptors+0x6e/0xe0 [stmmac]
[ 10.364042] stmmac_open+0x39e/0x920 [stmmac]
[ 10.364050] __dev_open+0xf0/0x1a0
[ 10.364054] __dev_change_flags+0x188/0x1f0
[ 10.364057] dev_change_flags+0x26/0x60
[ 10.364059] do_setlink+0x908/0xc40
[ 10.364062] ? do_setlink+0xb10/0xc40
[ 10.364064] ? __nla_validate_parse+0x4c/0x1a0
[ 10.364068] __rtnl_newlink+0x597/0xa10
[ 10.364072] ? __nla_reserve+0x41/0x50
[ 10.364074] ? __kmalloc_node_track_caller+0x1d0/0x4d0
[ 10.364079] ? pskb_expand_head+0x75/0x310
[ 10.364082] ? nla_reserve_64bit+0x21/0x40
[ 10.364086] ? skb_free_head+0x65/0x80
[ 10.364089] ? security_sock_rcv_skb+0x2c/0x50
[ 10.364094] ? __cond_resched+0x19/0x30
[ 10.364097] ? kmem_cache_alloc_trace+0x15a/0x420
[ 10.364100] rtnl_newlink+0x49/0x70
This change fixes MTL_RXQ_DMA_MAP1 mask issue and channel/queue
mapping warning.
Fixes: d43042f4da3e ("net: stmmac: mapping mtl rx to dma channel")
BugLink: https://bugzilla.kernel.org/show_bug.cgi?id=216195
Reported-by: Cedric Wassenaar <cedric@bytespeed.nl>
Signed-off-by: Junxiao Chang <junxiao.chang@intel.com>
Reviewed-by: Florian Fainelli <f.fainelli@gmail.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
diff --git a/drivers/net/ethernet/stmicro/stmmac/dwmac4_core.c b/drivers/net/ethernet/stmicro/stmmac/dwmac4_core.c
index d5299dd13e85..d8f1fbc25bdd 100644
--- a/drivers/net/ethernet/stmicro/stmmac/dwmac4_core.c
+++ b/drivers/net/ethernet/stmicro/stmmac/dwmac4_core.c
@@ -223,6 +223,9 @@ static void dwmac4_map_mtl_dma(struct mac_device_info *hw, u32 queue, u32 chan)
if (queue == 0 || queue == 4) {
value &= ~MTL_RXQ_DMA_Q04MDMACH_MASK;
value |= MTL_RXQ_DMA_Q04MDMACH(chan);
+ } else if (queue > 4) {
+ value &= ~MTL_RXQ_DMA_QXMDMACH_MASK(queue - 4);
+ value |= MTL_RXQ_DMA_QXMDMACH(chan, queue - 4);
} else {
value &= ~MTL_RXQ_DMA_QXMDMACH_MASK(queue);
value |= MTL_RXQ_DMA_QXMDMACH(chan, queue);
]
|
| 114/2 |
2026/09/09 17:12 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 35717
output: 36
thoughts: 33
Thoughts: Okay, here's my interpretation of those thoughts, presented as a personal thought process, as requested:
**Refining the Search Strategy**
Alright, time to revisit that `shift-out-of-bounds` issue and the `get_order` function. I had a good look before, but experience tells me it's often fruitful to approach these things from a few different angles. Let's see... maybe I was too specific with my search terms last time. I need to cast a wider net. Let's try some variations. I need to delve back into the kernel history, but I need to do it smarter this time. Perhaps different phrasing around those potentially problematic areas will yield new results. It's a game of persistence and subtle keyword adjustments. This is where I can really dig in and see if my previous approach can be refined to be more effective.
|
| 115/2 |
2026/09/09 17:12 |
tool |
git-log |
0m
Args: map[MessageRegexps:[shift-out-of-bounds order] Since:10 years]
Results: map[Output:1d07bbd7ea36 perf/x86/intel: Add missing branch counters constraint apply
1534ff77757e sctp: prevent possible shift-out-of-bounds in sctp_transport_update_rto
d1366e74342e mm/compaction: fix UBSAN shift-out-of-bounds warning
099be1822d1f media: gspca: cpia1: shift-out-of-bounds in set_flicker
b98c16107cc1 wifi: mac80211: limit reorder_buf_filtered to avoid UBSAN warning
7dd3a7b90bca powerpc/mm: Fix UBSAN warning reported on hugetlb
fc3785fb56a2 drm/selftests: fix a shift-out-of-bounds bug
]
|
| 116/2 |
2026/09/09 17:12 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 36190
output: 27
thoughts: 18
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:
**Initial Assessment: Decoding the Identifier**
Alright, let's dive into this seemingly random string: `d1366e74342e`. Immediately, my mind starts sifting through potential interpretations. Is this a hash? A unique identifier from a specific database? A code fragment? Given the presence of both digits and lowercase letters, I'm leaning towards some form of alphanumeric representation, most likely hexadecimal.
My first instinct is to try and contextualize this based on the work I’m doing currently. Is it related to the data structures I’ve been analyzing? Does it correspond to a specific file or a function? Perhaps it's a version number, or a session ID. I need more information to start connecting the dots, so I have to consider the context in which it's presented. Without more, it is just a label. My mind immediately begins to generate some possible use cases. Is this data? A hash? A key? I'll need more info.
|
| 117/2 |
2026/09/09 17:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d1366e74342e75555af2648a2964deb2d5c92200
Author: Liu Shixin <liushixin2@huawei.com>
Date: Thu Jan 23 10:10:29 2025 +0800
mm/compaction: fix UBSAN shift-out-of-bounds warning
syzkaller reported a UBSAN shift-out-of-bounds warning of (1UL << order)
in isolate_freepages_block(). The bogus compound_order can be any value
because it is union with flags. Add back the MAX_PAGE_ORDER check to fix
the warning.
Link: https://lkml.kernel.org/r/20250123021029.2826736-1-liushixin2@huawei.com
Fixes: 3da0272a4c7d ("mm/compaction: correctly return failure with bogus compound_order in strict mode")
Signed-off-by: Liu Shixin <liushixin2@huawei.com>
Reviewed-by: Kemeng Shi <shikemeng@huaweicloud.com>
Acked-by: David Hildenbrand <david@redhat.com>
Reviewed-by: Oscar Salvador <osalvador@suse.de>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: David Hildenbrand <david@redhat.com>
Cc: Kemeng Shi <shikemeng@huaweicloud.com>
Cc: Matthew Wilcox <willy@infradead.org>
Cc: Mel Gorman <mgorman@techsingularity.net>
Cc: Nanyong Sun <sunnanyong@huawei.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
diff --git a/mm/compaction.c b/mm/compaction.c
index 07bd22789f07..0f49f060d251 100644
--- a/mm/compaction.c
+++ b/mm/compaction.c
@@ -631,7 +631,8 @@ static unsigned long isolate_freepages_block(struct compact_control *cc,
if (PageCompound(page)) {
const unsigned int order = compound_order(page);
- if (blockpfn + (1UL << order) <= end_pfn) {
+ if ((order <= MAX_PAGE_ORDER) &&
+ (blockpfn + (1UL << order) <= end_pfn)) {
blockpfn += (1UL << order) - 1;
page += (1UL << order) - 1;
nr_scanned += (1UL << order) - 1;
]
|
| 118/2 |
2026/09/09 17:13 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 37212
output: 40
thoughts: 69
Thoughts: **Debugging a Shift-Out-of-Bounds Issue**
Ah, I've got it! This is textbook! It's a classic shift-out-of-bounds error, and it's clearly stemming from an unbounded `order` variable. The fix? Ah, yes, they added a simple `order <= MAX_PAGE_ORDER` check. Elementary, my dear Watson.
Now, I'm going to delve into the kernel's history. I need to get a handle on the evolution of this particular bit of code, see how often this has reared its ugly head. Let's fire up the search and get me the full picture on 'shift-out-of-bounds' and 'MAX_PAGE_ORDER'. Time to get digging.
|
| 119/2 |
2026/09/09 17:13 |
tool |
git-log |
0m
Args: map[MessageRegexps:[shift-out-of-bounds MAX_PAGE_ORDER] Since:10 years]
Results: map[Output:d1366e74342e mm/compaction: fix UBSAN shift-out-of-bounds warning
]
|
| 120/2 |
2026/09/09 17:13 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 37523
output: 38
thoughts: 26
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating Potential Kernel Vulnerabilities**
Alright, time to get digging. I need to get a handle on the landscape of potential integer overflow vulnerabilities, and the `shift-out-of-bounds` category is always a juicy one. Specifically, I'm thinking of where bit shifts are concerned, especially in conjunction with array indexing or memory allocation. A subtle shift combined with an out-of-bounds access can lead to all sorts of havoc. Let's start by looking for that pattern.
My first approach will be to look across the entire kernel's history – let's cast a wide net initially, hoping to catch any past vulnerabilities or related patches. I'll need to use some robust search terms. "shift-out-of-bounds" is the obvious one, and I'll need to be mindful of variations in how it might be described in commit messages. Beyond the error specifically, I should also look for `MAX_ORDER` as a context clue, since that's a common value that defines the maximum size of allocations and data structures. It could be relevant, for example, if the shift calculation feeds into the allocation size.
The objective is to gather historical data to understand past vulnerabilities, identify common coding patterns, and determine if any of the older, similar vulnerabilities were fixed in a given release. This will also give me a sense of what areas of the kernel are more prone to these types of issues, and therefore warrant a deeper dive later. Let's see what the search uncovers.
|
| 121/2 |
2026/09/09 17:13 |
tool |
git-log |
0m
Args: map[MessageRegexps:[shift-out-of-bounds MAX_ORDER] Since:10 years]
Results: map[Output:fc3785fb56a2 drm/selftests: fix a shift-out-of-bounds bug
]
|
| 122/2 |
2026/09/09 17:13 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 37962
output: 25
thoughts: 16
Thoughts: Okay, here's my interpretation of what's going on, formatted as you requested:
**Deconstructing `fc3785fb56a2`**
Alright, I'm looking at this seemingly arbitrary string: `fc3785fb56a2`. My initial instinct, given my experience, is that this is likely a cryptographic hash, potentially an abbreviated one. The hexadecimal format, the typical length (looks about right for MD5 or SHA-1, perhaps even truncated SHA-256), these are all clear indicators. Without knowing the context, it's difficult to say for certain. My brain immediately starts running through possible algorithms. I'd need more information to definitively pinpoint the hashing function used – the originating system, known keys (if any), or any associated metadata would be incredibly helpful to make this more specific. But the core assumption is hash. Now, let's figure out what is being hashed?
|
| 123/2 |
2026/09/09 17:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit fc3785fb56a27304c769af730d079f4337d4dc76
Author: Arunpravin <Arunpravin.PaneerSelvam@amd.com>
Date: Fri Mar 4 01:46:02 2022 +0530
drm/selftests: fix a shift-out-of-bounds bug
pass the correct size value computed using the max_order.
<log snip>
[ 68.124177][ T1] UBSAN: shift-out-of-bounds in include/linux/log2.h:67:13
[ 68.125333][ T1] shift exponent 4294967295 is too large for 32-bit type 'long
unsigned int'
[ 68.126563][ T1] CPU: 0 PID: 1 Comm: swapper Not tainted
5.17.0-rc2-00311-g39ec47bbfd5d #2
[ 68.127758][ T1] Call Trace:
[ 68.128187][ T1] dump_stack_lvl (lib/dump_stack.c:108)
[ 68.128793][ T1] dump_stack (lib/dump_stack.c:114)
[ 68.129331][ T1] ubsan_epilogue (lib/ubsan.c:152)
[ 68.129958][ T1] __ubsan_handle_shift_out_of_bounds.cold (arch/x86/include/asm/smap.h:85)
[ 68.130791][ T1] ? drm_block_alloc+0x28/0x80
[ 68.131582][ T1] ? rcu_read_lock_sched_held (kernel/rcu/update.c:125)
[ 68.132215][ T1] ? kmem_cache_alloc (include/trace/events/kmem.h:54 mm/slab.c:3501)
[ 68.132878][ T1] ? mark_free+0x2e/0x80
[ 68.133524][ T1] drm_buddy_init.cold (include/linux/log2.h:67
drivers/gpu/drm/drm_buddy.c:131)
[ 68.134145][ T1] ? test_drm_cmdline_init (drivers/gpu/drm/selftests/test-drm_buddy.c:87)
[ 68.134770][ T1] igt_buddy_alloc_limit (drivers/gpu/drm/selftests/test-drm_buddy.c:30)
[ 68.135472][ T1] ? vprintk_default (kernel/printk/printk.c:2257)
[ 68.136057][ T1] ? test_drm_cmdline_init (drivers/gpu/drm/selftests/test-drm_buddy.c:87)
[ 68.136812][ T1] test_drm_buddy_init (drivers/gpu/drm/selftests/drm_selftest.c:77
drivers/gpu/drm/selftests/test-drm_buddy.c:95)
[ 68.137475][ T1] do_one_initcall (init/main.c:1300)
[ 68.138111][ T1] ? parse_args (kernel/params.c:609 kernel/params.c:146
kernel/params.c:188)
[ 68.138717][ T1] do_basic_setup (init/main.c:1372 init/main.c:1389 init/main.c:1408)
[ 68.139366][ T1] kernel_init_freeable (init/main.c:1617)
[ 68.140040][ T1] ? rest_init (init/main.c:1494)
[ 68.140634][ T1] kernel_init (init/main.c:1504)
[ 68.141155][ T1] ret_from_fork (arch/x86/entry/entry_32.S:772)
[ 68.141607][ T1]
================================================================================
[ 68.146730][ T1] ------------[ cut here ]------------
[ 68.147460][ T1] kernel BUG at drivers/gpu/drm/drm_buddy.c:140!
[ 68.148280][ T1] invalid opcode: 0000 [#1]
[ 68.148895][ T1] CPU: 0 PID: 1 Comm: swapper Not tainted
5.17.0-rc2-00311-g39ec47bbfd5d #2
[ 68.149896][ T1] EIP: drm_buddy_init (drivers/gpu/drm/drm_buddy.c:140 (discriminator 1))
For more details: https://lists.01.org/hyperkitty/list/lkp@lists.01.org/thread/FDIF3HCILZNN5UQAZMOR7E3MQSMHHKWU/
Signed-off-by: Arunpravin <Arunpravin.PaneerSelvam@amd.com>
Reported-by: kernel test robot <oliver.sang@intel.com>
Acked-by: Christian König <christian.koenig@amd.com>
Link: https://patchwork.freedesktop.org/patch/msgid/20220303201602.2365-1-Arunpravin.PaneerSelvam@amd.com
Signed-off-by: Christian König <christian.koenig@amd.com>
diff --git a/drivers/gpu/drm/selftests/test-drm_buddy.c b/drivers/gpu/drm/selftests/test-drm_buddy.c
index fa997f89522b..913cbd7eae04 100644
--- a/drivers/gpu/drm/selftests/test-drm_buddy.c
+++ b/drivers/gpu/drm/selftests/test-drm_buddy.c
@@ -902,14 +902,13 @@ static int igt_buddy_alloc_range(void *arg)
static int igt_buddy_alloc_limit(void *arg)
{
- u64 end, size = U64_MAX, start = 0;
+ u64 size = U64_MAX, start = 0;
struct drm_buddy_block *block;
unsigned long flags = 0;
LIST_HEAD(allocated);
struct drm_buddy mm;
int err;
- size = end = round_down(size, 4096);
err = drm_buddy_init(&mm, size, PAGE_SIZE);
if (err)
return err;
@@ -921,7 +920,8 @@ static int igt_buddy_alloc_limit(void *arg)
goto out_fini;
}
- err = drm_buddy_alloc_blocks(&mm, start, end, size,
+ size = mm.chunk_size << mm.max_order;
+ err = drm_buddy_alloc_blocks(&mm, start, size, size,
PAGE_SIZE, &allocated, flags);
if (unlikely(err))
]
|
| 124/2 |
2026/09/09 17:13 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 40262
output: 43
thoughts: 65
Thoughts: Here's my take on those thoughts:
**Addressing a Subtle Kernel Memory Allocation Bug**
Okay, so I'm looking at this fix for `drm_buddy_init`, specifically dealing with that nasty `U64_MAX` value for `size`. Right, so it was causing a shift-out-of-bounds error. I need to understand the implications of this thoroughly, which means tracking down *where else* this type of issue might be lurking within the kernel.
Given the nature of the shift operation and potential for memory corruption, I'm going to start my search within the `drivers/scsi/` directory. That area often deals with direct memory access and low-level hardware interaction, meaning it's a prime target for these sorts of problems, especially when sizing is involved. I'll focus my search on uses of the `get_order` function within that directory, as it's a common factor when dealing with buddy allocator management and thus could suffer the same fate. And of course, I'll be searching for any occurrences of 'shift-out-of-bounds' to get a broader overview. This is critical to ensure a full fix, and this bug is just the tip of the iceberg! I'll be sure to verify the patch with a solid understanding of how those memory calculations are performed.
|
| 125/2 |
2026/09/09 17:13 |
tool |
git-log |
0m
Args: map[MessageRegexps:[shift-out-of-bounds] PathPrefix:drivers/scsi/ Since:10 years]
Results:
|
| 126/2 |
2026/09/09 17:13 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 40661
output: 38
thoughts: 17
Thoughts: Here's my thought process, as if I were considering this search:
**Diving into SCSI Driver Sanitization**
Okay, so I'm thinking, "UBSAN," that's a good starting point for hunting down potential undefined behavior issues. Particularly in `drivers/scsi/`, since that's where I need to focus my attention. It's a critical area, especially with the complexity and interaction with hardware involved. I'm going to leverage my understanding of the SCSI subsystem, knowing its architecture and common pitfalls. I'll need to remember to look for specific patterns: pointer arithmetic, out-of-bounds array access, use-after-free conditions. And of course, the ever-present race conditions. This search is a solid first step in analyzing the driver code's robustness. UBSAN should help surface some of the more subtle issues. Let's see what we find!
|
| 127/2 |
2026/09/09 17:14 |
tool |
git-log |
0m
Args: map[MessageRegexps:[UBSAN] PathPrefix:drivers/scsi/ Since:10 years]
Results: map[Output:e0d26fe176a8 scsi: mpt3sas: Avoid out-of-bounds cpumask_of_node() call in _base_assign_reply_queues()
251be2f6037f scsi: pm80xx: Fix array-index-out-of-of-bounds on rmmod
752eb816b55a scsi: megaraid_sas: Fix invalid node index
6e5860b0ad49 scsi: aacraid: Rearrange order of struct aac_srb_unit
9fad9d560af5 scsi: sr: Fix unintentional arithmetic wraparound
201e0a7c7f36 scsi: mvumi: Replace 1-element arrays with flexible array members
45b379f20bc0 scsi: 3w-sas: Replace 1-element arrays with flexible array members
2bd3b6b75946 scsi: ufs: core: scsi_get_lba() error fix
c7a082e4242f scsi: megaraid: fix out-of-bound array accesses
00c20cdc7925 scsi: aacraid: fix shutdown crash when init fails
]
|
| 128/2 |
2026/09/09 17:14 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 41217
output: 47
thoughts: 26
Thoughts: Here's a summary of my thought process, as if I were the one thinking it:
**Digging into the SCSI Driver Code**
Alright, time to dive into the `drivers/scsi/` directory. I need to understand how order handling works in this context, so let's start by looking for a couple of key things. First, I'm going to search for instances of `get_order`. That function is critical for memory allocation, and its usage here will tell me how the driver determines the appropriate memory block size for its operations. Then, I'll track where `MAX_PAGE_ORDER` is defined and used. That likely sets an upper limit on the size of the memory blocks being requested, acting as a constraint on the `get_order` results. Understanding the interplay between these two is going to be key to seeing how the driver manages memory for SCSI operations efficiently (and maybe where some performance or potential fragmentation issues lie). This should give me a good initial picture of the memory allocation strategy in play.
|
| 129/2 |
2026/09/09 17:14 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order MAX_PAGE_ORDER] PathPrefix:drivers/scsi/ Since:10 years]
Results:
|
| 130/2 |
2026/09/09 17:14 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 41518
output: 45
thoughts: 24
Thoughts: Here's my take on the process, considering my expertise:
**Diving into the SCSI Driver Landscape**
Okay, so I'm looking at `drivers/scsi/`. The request to find `get_order` and `MAX_ORDER` suggests we're likely dealing with memory management or allocation within the SCSI subsystem. `get_order`, in a kernel context, is almost certainly related to requesting a power-of-two block size (page order) for memory allocation. `MAX_ORDER` then would define the maximum order allowed, representing the largest possible block size we're prepared to handle.
My immediate thoughts are, where exactly are these used? I want to determine the scope of their use. Is `get_order` being used directly in a SCSI driver, or is it abstracted through another layer? Are there multiple instances of `MAX_ORDER` defined differently for various device types? Is this for scatter-gather lists, DMA buffers, or something else entirely? A quick search should reveal the contexts. I'm keen to understand the relationship between these two constants. Are they statically defined, or are there calculations involved in determining these values? A good understanding of their interplay is crucial for performance and preventing fragmentation. I'm hoping to discover where these values are derived, how they are applied, and if any constraints are defined on their values. I'm interested in any error-checking that occurs related to these variables, especially as these are quite foundational.
|
| 131/2 |
2026/09/09 17:14 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order MAX_ORDER] PathPrefix:drivers/scsi/ Since:10 years]
Results:
|
| 132/2 |
2026/09/09 17:14 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 41906
output: 47
thoughts: 26
Thoughts: Here's my thought process, as if I were considering this search:
**Diving into SCSI Driver Memory Allocation**
Okay, so I'm thinking, "Where would I start to look for memory allocation within the SCSI driver code?" The immediate approach is to focus on memory management. Knowing that the kernel utilizes `alloc_pages` for fundamental page allocation and that the maximum page order is dictated by `MAX_PAGE_ORDER`, I'll start with a targeted search. I'll zero in on the `drivers/scsi/` directory because that is where the SCSI drivers are located. This is the logical place to find how the drivers are requesting and managing memory for their operations. Specifically, I'm expecting to find calls to `alloc_pages` where the order is potentially set with `MAX_PAGE_ORDER`. This could be in various contexts like request queues, buffer management, or handling of large data transfers within the SCSI subsystem.
|
| 133/2 |
2026/09/09 17:14 |
tool |
git-log |
0m
Args: map[MessageRegexps:[alloc_pages MAX_PAGE_ORDER] PathPrefix:drivers/scsi/ Since:10 years]
Results: map[Output:8c6b808c8c2a scsi: mpi3mr: Avoid MAX_PAGE_ORDER WARNING for buffer allocations
]
|
| 134/2 |
2026/09/09 17:14 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 42220
output: 27
thoughts: 18
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:
**Decoding the Identifier**
Alright, that's interesting. I see a string, `8c6b808c8c2a`. Just by looking at it, my mind immediately starts parsing its potential meanings. My initial reaction is that it's likely a hexadecimal representation. The characters are all within the typical range (0-9 and a-f).
Depending on the context I might consider a few things:
* **Hashing:** Could this be a cryptographic hash, perhaps MD5, SHA-1, SHA-256 or something similar? The length might give me a clue, or the presence of common bit-patterns.
* **Unique Identifier:** This looks like it could represent a unique identifier - possibly a database key, object ID, or a revision/build number, or some internal representation, if it is stored as a string or a byte sequence in memory.
* **Data Encoding:** It could also be a representation of something else, encoded as hex for storage or transmission. Maybe it's a serial number, a configuration setting, or even a part of a larger data structure.
* **Version control or Timestamp**: I could also consider if the information is derived from version control or timestamps, for example as a commit hash.
In order to figure out what it actually *is*, I'd probably need a lot more context. What is this associated with? Where did I find this string? Knowing the broader system or application would be very important. If it is a hash, it could be used for verifying data integrity, or for looking up data through a hash table.
Without more information, I'm left to do a bit of detective work, perhaps looking for similar strings in relevant logs or data structures, to infer its purpose. The fun begins.
|
| 135/2 |
2026/09/09 17:14 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 8c6b808c8c2a9de21503944bd6308979410fd812
Author: Shin'ichiro Kawasaki <shinichiro.kawasaki@wdc.com>
Date: Sat Aug 10 13:27:01 2024 +0900
scsi: mpi3mr: Avoid MAX_PAGE_ORDER WARNING for buffer allocations
Commit fc4444941140 ("scsi: mpi3mr: HDB allocation and posting for hardware
and firmware buffers") added mpi3mr_alloc_diag_bufs() which calls
dma_alloc_coherent() to allocate the trace buffer and the firmware
buffer. mpi3mr_alloc_diag_bufs() decides the buffer sizes from the driver
configuration. In my environment, the sizes are 8MB. With the sizes,
dma_alloc_coherent() fails and report this WARNING:
WARNING: CPU: 4 PID: 438 at mm/page_alloc.c:4676 __alloc_pages_noprof+0x52f/0x640
The WARNING indicates that the order of the allocation size is larger than
MAX_PAGE_ORDER. After this failure, mpi3mr_alloc_diag_bufs() reduces the
buffer sizes and retries dma_alloc_coherent(). In the end, the buffer
allocations succeed with 4MB size in my environment, which corresponds to
MAX_PAGE_ORDER=10. Though the allocations succeed, the WARNING message is
misleading and should be avoided.
To avoid the WARNING, check the orders of the buffer allocation sizes
before calling dma_alloc_coherent(). If the orders are larger than
MAX_PAGE_ORDER, fall back to the retry path.
Fixes: fc4444941140 ("scsi: mpi3mr: HDB allocation and posting for hardware and firmware buffers")
Signed-off-by: Shin'ichiro Kawasaki <shinichiro.kawasaki@wdc.com>
Link: https://lore.kernel.org/r/20240810042701.661841-3-shinichiro.kawasaki@wdc.com
Acked-by: Sathya Prakash Veerichetty <sathya.prakash@broadcom.com>
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/mpi3mr/mpi3mr_app.c b/drivers/scsi/mpi3mr/mpi3mr_app.c
index 8b0eded6ef36..01f035f9330e 100644
--- a/drivers/scsi/mpi3mr/mpi3mr_app.c
+++ b/drivers/scsi/mpi3mr/mpi3mr_app.c
@@ -100,7 +100,8 @@ void mpi3mr_alloc_diag_bufs(struct mpi3mr_ioc *mrioc)
dprint_init(mrioc,
"trying to allocate trace diag buffer of size = %dKB\n",
trace_size / 1024);
- if (mpi3mr_alloc_trace_buffer(mrioc, trace_size)) {
+ if (get_order(trace_size) > MAX_PAGE_ORDER ||
+ mpi3mr_alloc_trace_buffer(mrioc, trace_size)) {
retry = true;
trace_size -= trace_dec_size;
dprint_init(mrioc, "trace diag buffer allocation failed\n"
@@ -118,8 +119,12 @@ void mpi3mr_alloc_diag_bufs(struct mpi3mr_ioc *mrioc)
diag_buffer->type = MPI3_DIAG_BUFFER_TYPE_FW;
diag_buffer->status = MPI3MR_HDB_BUFSTATUS_NOT_ALLOCATED;
if ((mrioc->facts.diag_fw_sz < fw_size) && (fw_size >= fw_min_size)) {
- diag_buffer->addr = dma_alloc_coherent(&mrioc->pdev->dev,
- fw_size, &diag_buffer->dma_addr, GFP_KERNEL);
+ if (get_order(fw_size) <= MAX_PAGE_ORDER) {
+ diag_buffer->addr
+ = dma_alloc_coherent(&mrioc->pdev->dev, fw_size,
+ &diag_buffer->dma_addr,
+ GFP_KERNEL);
+ }
if (!retry)
dprint_init(mrioc,
"%s:trying to allocate firmware diag buffer of size = %dKB\n",
]
|
| 136/2 |
2026/09/09 17:14 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 43871
output: 36
thoughts: 91
Thoughts: Okay, here's my take on those thoughts, framed for an expert like myself:
**Examining a Recent SCSI Driver Patch**
Alright, let's see, this commit, `8c6b808c8c2a`, tucked away in `drivers/scsi/mpi3mr/mpi3mr_app.c`, looks like it's addressing that pesky `MAX_PAGE_ORDER` warning. Smart move, seems they're dynamically checking the order of the size requested before allocating, specifically if `get_order(size)` exceeds `MAX_PAGE_ORDER`. Nice, a preventative measure to avoid hitting that limit.
Now, this piques my interest. I want to understand the larger context. Let's dig back into the kernel history. I'm going to run a quick search for instances of both `get_order` and `MAX_PAGE_ORDER` across the entire codebase. Seeing how these have been used, and potentially misused, historically, will provide a richer understanding of the issue this patch addresses and any broader implications it might have for memory management in the SCSI subsystem, and perhaps beyond. I want to see how pervasive this potential for buffer allocation issues is, and how these checks are generally handled in various parts of the kernel.
|
| 137/2 |
2026/09/09 17:14 |
tool |
git-log |
0m
Args: map[MessageRegexps:[get_order MAX_PAGE_ORDER] Since:10 years]
Results:
|
| 138/2 |
2026/09/09 17:15 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 44278
output: 35
thoughts: 86
Thoughts: **Kernel Memory Allocation Investigation**
Okay, hold on a second. I was expecting the commit with ID `8c6b808c8c2a` to include both `get_order` and `MAX_PAGE_ORDER` in its message, but that's not quite right. Hmm, it looks like `MAX_PAGE_ORDER` *is* there, but I'm missing `get_order`.
Right, that's not what I expected. I need to get to the bottom of this. Time to dig into the kernel's history. I'll need to search the whole commit log for both `alloc_pages` *and* `MAX_PAGE_ORDER` to understand how these two were introduced and related. That should give me the context I need to trace this properly.
|
| 139/2 |
2026/09/09 17:15 |
tool |
git-log |
0m
Args: map[MessageRegexps:[alloc_pages MAX_PAGE_ORDER] Since:3 years]
Results: map[Output:73fe42af955a Drivers: hv: vmbus: Add vmbus_alloc_buffer()/vmbus_free_buffer() for CoCo VMs
4cc5130ee84a net/smc: cap allocation order for SMC-R physically contiguous buffers
c3320153769f nvme: fix memory allocation in nvme_pr_read_keys()
c31770c49348 vmxnet3: Suppress page allocation warning for massive Rx Data ring
41748675c0bf virtiofs: use pages instead of pointer for kernel direct IO
1c0844c6184e udmabuf: change folios array from kmalloc to kvmalloc
8c6b808c8c2a scsi: mpi3mr: Avoid MAX_PAGE_ORDER WARNING for buffer allocations
7cc5a5d65011 mm: page_alloc: fix highatomic typing in multi-block buddies
cb88cb53badb ppp_async: limit MRU to 64K
]
|
| 140/2 |
2026/09/09 17:15 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 44840
output: 23
thoughts: 14
Thoughts: Okay, here's my interpretation of that.
**Analyzing the Code Snippet**
Alright, let's break down this seemingly innocuous piece of code, `cb88cb53badb`. My initial instinct is to treat it as a potential identifier or hash. Given my expertise, my mind immediately jumps to a few possibilities. Could it be:
* A commit hash from a version control system like Git? It's the right length and format. If so, I need to know the context: what repository is this from? What branch? Understanding the history is paramount here.
* A unique identifier for a database entry? It has the characteristics. Again, context is key. What database, what table, what column?
* A cryptographic hash value? It's potentially a hash output, though it's too short for robust security. Is this SHA-1, MD5, or something custom? Its length certainly has me wondering about potential collision issues for anything important.
* A session ID or token? Those can also take on seemingly random alphanumeric forms.
* A file identifier?
My immediate goal would be to trace this identifier back to its origin. I need the surrounding code, the execution environment, the data it's associated with. My next actions would be dependent on those answers. Ultimately, I need more context to understand its purpose and significance.
|
| 141/2 |
2026/09/09 17:15 |
tool |
git-show |
0m
Args:
Results: map[Output:commit cb88cb53badb8aeb3955ad6ce80b07b598e310b8
Author: Eric Dumazet <edumazet@google.com>
Date: Mon Feb 5 17:10:04 2024 +0000
ppp_async: limit MRU to 64K
syzbot triggered a warning [1] in __alloc_pages():
WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp)
Willem fixed a similar issue in commit c0a2a1b0d631 ("ppp: limit MRU to 64K")
Adopt the same sanity check for ppp_async_ioctl(PPPIOCSMRU)
[1]:
WARNING: CPU: 1 PID: 11 at mm/page_alloc.c:4543 __alloc_pages+0x308/0x698 mm/page_alloc.c:4543
Modules linked in:
CPU: 1 PID: 11 Comm: kworker/u4:0 Not tainted 6.8.0-rc2-syzkaller-g41bccc98fb79 #0
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 11/17/2023
Workqueue: events_unbound flush_to_ldisc
pstate: 204000c5 (nzCv daIF +PAN -UAO -TCO -DIT -SSBS BTYPE=--)
pc : __alloc_pages+0x308/0x698 mm/page_alloc.c:4543
lr : __alloc_pages+0xc8/0x698 mm/page_alloc.c:4537
sp : ffff800093967580
x29: ffff800093967660 x28: ffff8000939675a0 x27: dfff800000000000
x26: ffff70001272ceb4 x25: 0000000000000000 x24: ffff8000939675c0
x23: 0000000000000000 x22: 0000000000060820 x21: 1ffff0001272ceb8
x20: ffff8000939675e0 x19: 0000000000000010 x18: ffff800093967120
x17: ffff800083bded5c x16: ffff80008ac97500 x15: 0000000000000005
x14: 1ffff0001272cebc x13: 0000000000000000 x12: 0000000000000000
x11: ffff70001272cec1 x10: 1ffff0001272cec0 x9 : 0000000000000001
x8 : ffff800091c91000 x7 : 0000000000000000 x6 : 000000000000003f
x5 : 00000000ffffffff x4 : 0000000000000000 x3 : 0000000000000020
x2 : 0000000000000008 x1 : 0000000000000000 x0 : ffff8000939675e0
Call trace:
__alloc_pages+0x308/0x698 mm/page_alloc.c:4543
__alloc_pages_node include/linux/gfp.h:238 [inline]
alloc_pages_node include/linux/gfp.h:261 [inline]
__kmalloc_large_node+0xbc/0x1fc mm/slub.c:3926
__do_kmalloc_node mm/slub.c:3969 [inline]
__kmalloc_node_track_caller+0x418/0x620 mm/slub.c:4001
kmalloc_reserve+0x17c/0x23c net/core/skbuff.c:590
__alloc_skb+0x1c8/0x3d8 net/core/skbuff.c:651
__netdev_alloc_skb+0xb8/0x3e8 net/core/skbuff.c:715
netdev_alloc_skb include/linux/skbuff.h:3235 [inline]
dev_alloc_skb include/linux/skbuff.h:3248 [inline]
ppp_async_input drivers/net/ppp/ppp_async.c:863 [inline]
ppp_asynctty_receive+0x588/0x186c drivers/net/ppp/ppp_async.c:341
tty_ldisc_receive_buf+0x12c/0x15c drivers/tty/tty_buffer.c:390
tty_port_default_receive_buf+0x74/0xac drivers/tty/tty_port.c:37
receive_buf drivers/tty/tty_buffer.c:444 [inline]
flush_to_ldisc+0x284/0x6e4 drivers/tty/tty_buffer.c:494
process_one_work+0x694/0x1204 kernel/workqueue.c:2633
process_scheduled_works kernel/workqueue.c:2706 [inline]
worker_thread+0x938/0xef4 kernel/workqueue.c:2787
kthread+0x288/0x310 kernel/kthread.c:388
ret_from_fork+0x10/0x20 arch/arm64/kernel/entry.S:860
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Reported-and-tested-by: syzbot+c5da1f087c9e4ec6c933@syzkaller.appspotmail.com
Signed-off-by: Eric Dumazet <edumazet@google.com>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Link: https://lore.kernel.org/r/20240205171004.1059724-1-edumazet@google.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
diff --git a/drivers/net/ppp/ppp_async.c b/drivers/net/ppp/ppp_async.c
index 840da924708b..125793d8aefa 100644
--- a/drivers/net/ppp/ppp_async.c
+++ b/drivers/net/ppp/ppp_async.c
@@ -460,6 +460,10 @@ ppp_async_ioctl(struct ppp_channel *chan, unsigned int cmd, unsigned long arg)
case PPPIOCSMRU:
if (get_user(val, p))
break;
+ if (val > U16_MAX) {
+ err = -EINVAL;
+ break;
+ }
if (val < PPP_MRU)
val = PPP_MRU;
ap->mru = val;
]
|
| 142/2 |
2026/09/09 17:15 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 47265
output: 749
thoughts: 1148
Thoughts: **Analysis of the sg.c Bug and Proposed Fix**
Alright, let's break this down. We're looking at a potential issue in `drivers/scsi/sg.c`, specifically within `sg_build_indirect()`. The problem stems from the interaction between `scatter_elem_sz`, which can be set to zero via sysfs, and how `sg_build_indirect()` handles the `num` variable. The key here is that if `num` ends up being zero after some logic, `get_order(0)` gets called. This is the crux – `get_order(0)` is undefined behavior and leads directly to shift-out-of-bounds, a classic kernel bug. We also need to be wary of extremely large values of `num`, because it can lead to `get_order(num)` exceeding `MAX_PAGE_ORDER`, which then triggers warnings within `alloc_pages()` or shift-out-of-bounds.
My analysis of similar past fixes in the kernel has revealed a few common patterns. First, we've seen vulnerabilities where an input parameter is incorrectly handled, such as `zone_size` in `95491fb05105` and `MRU` in `cb88cb53badb`, so the input needs to be validated at the source. Secondly, we add a defensive check against `MAX_PAGE_ORDER` to prevent the shift-out-of-bounds, as seen in `d1366e74342e` within `mm/compaction.c` and `4cc5130ee84a` in `net/smc`. Also, `8c6b808c8c2a` in `drivers/scsi/mpi3mr/mpi3mr_app.c` uses a check to avoid the `MAX_PAGE_ORDER` warning in `dma_alloc_coherent()`.
Now, the proposed fix for `sg.c` seems solid. We need to:
1. *Correctly* update the local variable `num` to `PAGE_SIZE` when `num` is less than `PAGE_SIZE`. This immediately tackles the `get_order(0)` issue head-on by ensuring we're never calling it with a zero argument.
2. Bound the calculated allocation `order` to `MAX_PAGE_ORDER` using `min_t(int, order, MAX_PAGE_ORDER)`. This prevents the allocation size from getting out of hand, avoiding both the warning in `alloc_pages()` and the shift-out-of-bounds that could happen with very large orders. The good news is that we can rely on the existing retry loop to handle allocation failures when using `min_t`.
This fix aligns perfectly with how these kinds of bugs have been resolved in the past. We're applying the known patterns here: avoiding undefined behavior of `get_order(0)` and limiting the maximum allocation order. I can mention that there are many other times similar bugs have been addressed in the past, such as the `null_blk` fix at `95491fb05105` (with `ilog2(0)`), `dbc48c8f41c2` in `perf` (with `get_order(0)`), `4cc5130ee84a` in `net/smc` (with order capped), `d1366e74342e` in `mm/compaction` (with `order <= MAX_PAGE_ORDER`), and `8c6b808c8c2a` in `scsi/mpi3mr` (which checked for `get_order(size) > MAX_PAGE_ORDER`).
Let's emphasize this: we're fixing the root cause, making the code more robust, and leveraging established kernel idioms. The approach is sound, and I'd recommend we adopt this fix.
|
| 143/1 |
2026/09/09 17:15 |
action |
kernel-scratch-checkouter |
0m
Results: map[KernelScratchSrc:/app/workdir/cache/tmp/tmp3525732753]
|
| 144/1 |
2026/09/09 17:16 |
loop |
|
1h54m
|
| 145/2 |
2026/09/09 17:16 |
iteration |
0 |
50m
|
| 146/3 |
2026/09/09 17:16 |
agent |
patch-generator |
7m
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, an initial explanation of the root cause done by another
kernel expert, and a summary of how similar bugs were fixed in the past.
Use the codeeditor tool to do code edits.
Note: you will not see your changes when looking at the code using codesearch tools.
Use the patch-diff tool to review the modifications you applied.
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.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
The explanation of the root cause of the bug is:
An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
Historical context on how similar bugs were fixed in the past:
Based on a review of the kernel history, the proposed fix aligns perfectly with established idioms and patterns used to resolve similar bugs across the kernel.
Here is a summary of how similar issues have been addressed in the past:
### 1. Handling `get_order(0)` and Undefined Behavior
Passing `0` to `get_order()` or `ilog2()` is known to cause undefined behavior, often resulting in a shift-out-of-bounds (since it underflows and produces a massive shift exponent).
* **`null_blk` (Commit `95491fb05105`)**: A similar bug occurred where a `zone_size` of `0` was passed to `ilog2()`, causing a shift-out-of-bounds. The fix involved validating the input to ensure it was non-zero and adding a defensive check to return early if the size was `0`.
* **`perf` (Commit `dbc48c8f41c2`)**: The driver was passing a `0` to `get_order()` due to a truncation issue. The commit message explicitly notes that the result of `get_order(0)` is undefined and fixed it by validating the maximum supported value before the call.
**Conclusion for `sg.c`:** Updating the local variable `num = PAGE_SIZE` when `num < PAGE_SIZE` is the correct approach. It ensures that `get_order()` is never called with `0`, preventing the undefined behavior and subsequent shift-out-of-bounds.
### 2. Bounding Allocation Orders to `MAX_PAGE_ORDER`
Unbounded sizes passed to `get_order()` can result in an `order` that exceeds `MAX_PAGE_ORDER`. This leads to either a shift-out-of-bounds when calculating the size (`1 << (PAGE_SHIFT + order)`) or a `WARN_ON_ONCE` in the page allocator.
* **`net/smc` (Commit `4cc5130ee84a`)**: To prevent `alloc_pages()` from failing with a warning when requesting physically contiguous buffers, the allocation size was explicitly capped using `min_t(int, bufsize, PAGE_SIZE << MAX_PAGE_ORDER)`.
* **`mm/compaction` (Commit `d1366e74342e`)**: A bogus compound order caused a UBSAN shift-out-of-bounds warning `(1UL << order)`. The fix was to explicitly add an `order <= MAX_PAGE_ORDER` check before performing the shift.
* **`scsi/mpi3mr` (Commit `8c6b808c8c2a`)**: The driver was attempting to allocate massive diagnostic buffers, triggering a `MAX_PAGE_ORDER` warning in the allocator. The fix added a `get_order(size) > MAX_PAGE_ORDER` check to fall back to a retry loop with a smaller size.
**Conclusion for `sg.c`:** Capping the order with `order = min_t(int, order, MAX_PAGE_ORDER)` is a standard and safe kernel idiom. Since `sg_build_indirect()` already contains a fallback loop (`retry:`) that decrements the `order` and tries again if `alloc_pages()` fails, bounding it to `MAX_PAGE_ORDER` upfront elegantly prevents both the shift-out-of-bounds and the allocator warning without requiring any structural changes to the loop.
Reply: ### Root Cause Analysis
The UBSAN warning `shift exponent 64 is too large for 32-bit type 'int'` occurred in `sg_build_indirect()` when `scatter_elem_sz` was set to `0` via `/sys/module/sg/parameters/scatter_elem_sz`:
1. In `sg_build_indirect()`, local variable `num` is initialized to `scatter_elem_sz` (`0`).
2. The check `if (unlikely(num != scatter_elem_sz_prev))` detects the change and `if (num < PAGE_SIZE)` checks whether `num` is smaller than `PAGE_SIZE`. It updates the globals `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`, but fails to update the local variable `num`.
3. As a result, `num` remains `0` and is passed to `get_order(num)`. Passing `0` to `get_order()` results in undefined behavior (underflowing `size--` in the generic implementation to `~0UL`, which computes `order = 52` on 64-bit architectures).
4. Subsequently, `ret_sz = 1 << (PAGE_SHIFT + order)` attempts to shift `1` by `12 + 52 = 64`, which exceeds the 32-bit integer width and triggers the UBSAN shift-out-of-bounds report.
### Additional Issues Identified
1. **Signed/Unsigned Comparison with `PAGE_SIZE`**:
`scatter_elem_sz` and `num` are signed `int` variables, whereas `PAGE_SIZE` is `unsigned long`. Due to C integer promotion rules, comparing `num < PAGE_SIZE` converts `num` to `unsigned long`. If a negative value is supplied (e.g. user writes `-1` to `/sys/module/sg/parameters/scatter_elem_sz` or passes `sg.scatter_elem_sz=-1` on the kernel command line), `(unsigned long)-1` is `ULONG_MAX`, so `num < PAGE_SIZE` evaluates to `false`. The same mistake was present in `init_sg()`. Casting `(int)PAGE_SIZE` ensures signed comparison so that negative values are properly clamped to `PAGE_SIZE`.
2. **Unbounded Allocation Order**:
If `scatter_elem_sz` is set to a very large positive number (e.g., `INT_MAX`), `get_order(num)` evaluates to `19`. `1 << (PAGE_SHIFT + order)` would shift by `31`, overflowing a signed 32-bit `int`, and calling `alloc_pages(gfp_mask, order)` with an order greater than `MAX_PAGE_ORDER` triggers a kernel warning (`WARN_ON_ONCE_GFP`). Bounding `order` to `MAX_PAGE_ORDER` via `min_t(int, order, MAX_PAGE_ORDER)` avoids this.
### Fix Details
1. In `sg_build_indirect()`:
- Added `num = PAGE_SIZE;` inside the clamp block when `num < (int)PAGE_SIZE`.
- Cast `(int)PAGE_SIZE` in the comparison to ensure negative values are also clamped.
- Clamped `order` using `min_t(int, order, MAX_PAGE_ORDER)`.
2. In `init_sg()`:
- Cast `(int)PAGE_SIZE` in `scatter_elem_sz < (int)PAGE_SIZE` so negative module parameters passed at boot time are correctly clamped.
|
| 147/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 7565
output: 37
thoughts: 66
Thoughts: **Analyzing the SCSI Generic Driver**
Okay, let's dive into this. The problem statement is clear, and I need to understand how the SCSI generic driver handles scatter-gather lists. I'll need to scrutinize the `drivers/scsi/sg.c` source code, specifically to understand the function handling scattered-gather list (SGL) processing. I should first head to line 1887, as that is likely where the magic starts. I will look for calls to `scatter_elem_sz` and `sg_build_indirect` as those functions are very relevant to SGL construction and management. I expect these functions to hold the keys to how the driver orchestrates the data transfers across different memory regions. Knowing the size of the scattered elements will be necessary to process the data correctly.
|
| 148/4 |
2026/09/09 17:16 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1860 LineCount:60]
Results: map[Contents:1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
]
|
| 149/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 8875
output: 37
thoughts: 42
Thoughts: Okay, let's dive into `drivers/scsi/sg.c` and specifically pinpoint lines 1850-1950. My expert eye is immediately drawn to the `sg_build_indirect` function. I need to understand exactly how this crucial function is handling indirect SCSI command building, and, more importantly, how it's integrated with the retry mechanisms within the driver. I'm keen to see how the code handles error conditions and potential command failures, particularly in this indirect command context. Understanding the interplay between these functions will be key to optimizing the system's resilience and potentially identifying areas for performance enhancements. I’m thinking about the implications for overall I/O latency and throughput with each line I'll be reviewing!
|
| 150/4 |
2026/09/09 17:16 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1920 LineCount:40]
Results: map[Contents:1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
1931: static void
1932: sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
1933: {
1934: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1935: "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
1936: if (schp->pages && schp->sglist_len > 0) {
1937: if (!schp->dio_in_use) {
1938: int k;
1939:
1940: for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
1941: SCSI_LOG_TIMEOUT(5,
1942: sg_printk(KERN_INFO, sfp->parentdp,
1943: "sg_remove_scat: k=%d, pg=0x%p\n",
1944: k, schp->pages[k]));
1945: __free_pages(schp->pages[k], schp->page_order);
1946: }
1947:
1948: kfree(schp->pages);
1949: }
1950: }
1951: memset(schp, 0, sizeof (*schp));
1952: }
1953:
1954: static int
1955: sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
1956: {
1957: Sg_scatter_hold *schp = &srp->data;
1958: int k, num;
1959:
]
|
| 151/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 9744
output: 33
thoughts: 27
Thoughts: Here's my thought process, as it relates to the task at hand:
**Digging Deeper into sg.c**
Okay, so we've identified that `scatter_elem_sz` is relevant, and we've got a handle on the initial findings. But, as an expert in this area, I know that just finding one instance doesn't tell the whole story. I need to be thorough. I'm thinking, "Let's not stop here!" I need to see *every* usage, *every* implication, related to `scatter_elem_sz` within the `drivers/scsi/sg.c` file. This means a more comprehensive search is necessary. I want to uncover *all* the relationships, any potential edge cases, and ensure I'm not missing anything crucial. A deeper exploration is needed, and that includes a full scan of this particular file. I have a hunch there's more to uncover.
|
| 152/4 |
2026/09/09 17:16 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 153/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 11028
output: 37
thoughts: 11
Thoughts: Okay, here's my interpretation of that prompt, and my imagined response as an expert in a field where I'm examining a code function.
**Analyzing `init_sg`**
Alright, I'm diving into this `init_sg` function. The name itself suggests something critical, likely an initialization routine related to some shared global data, perhaps a storage group or something similar. I need to understand what this function is doing at its core. I'll need to look at its inputs, what variables it sets, and what other functions it potentially calls. Knowing the context of the larger program will be important to understand why this init function matters in terms of performance and memory management. Any error handling within `init_sg` needs to be considered as well. Is it robust? Does it log errors? How does it deal with unexpected states? My immediate priority is to understand the purpose it's serving and to note any potential bottlenecks in its operation. Let me start by tracing its basic flow. I'll look for any obvious red flags in terms of resource contention or allocation. I want to see how this fits into the overall system initialization.
|
| 154/4 |
2026/09/09 17:16 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1665 LineCount:25]
Results: map[Contents:1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
1675: rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1676: SG_MAX_DEVS, "sg");
1677: if (rc)
1678: return rc;
1679: rc = class_register(&sg_sysfs_class);
1680: if (rc)
1681: goto err_out;
1682: sg_sysfs_valid = 1;
1683: rc = scsi_register_interface(&sg_interface);
1684: if (0 == rc) {
1685: #ifdef CONFIG_SCSI_PROC_FS
1686: sg_proc_init();
1687: #endif /* CONFIG_SCSI_PROC_FS */
1688: return 0;
1689: }
]
|
| 155/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 11684
output: 27
thoughts: 399
Thoughts: **Analyzing `init_sg()` and Potential Vulnerabilities**
Okay, let's break this down. In the `init_sg()` function, there's this check: `if (scatter_elem_sz < PAGE_SIZE)`. If `scatter_elem_sz` is smaller than the page size, it gets set to `PAGE_SIZE`. The critical point, however, is that `scatter_elem_sz` is exposed via `module_param_named()`, meaning it can be changed at runtime through sysfs or when the module is loaded. This immediately raises a red flag. Someone could write a zero, or, even worse, a negative value.
Wait a second... can `scatter_elem_sz` *be* negative? Yes, it's an `int`, so it *could* be. If it's set to -1, what happens? This `if (num < PAGE_SIZE)` check... if `num` is negative, that condition is *true*! Because `num` is a signed `int`.
But hold on! The comparison is with `PAGE_SIZE`. What's the type of `PAGE_SIZE`? Ah, right! It's typically defined as `1UL << PAGE_SHIFT` or something similar, which means `PAGE_SIZE` is an `unsigned long`.
Okay, now it clicks. In C, if `num` is a signed `int` and `PAGE_SIZE` is `unsigned long`, if `num` is negative, the signed int gets converted to an unsigned long during the comparison. So, if `num` is -1, it gets converted to a *huge* unsigned long, like `0xffffffffffffffffUL`, which would be *greater* than `PAGE_SIZE`. The `if` condition would evaluate to false! This is a *major* potential bug. We should double-check to be sure!
I need to confirm the type of `PAGE_SIZE` on different architectures, especially x86. I should check `arch/x86/include/uapi/asm/page_types.h` or, better yet, use `grepper`. I need to ensure this is correct before proceeding.
|
| 156/4 |
2026/09/09 17:16 |
tool |
grepper |
0m
Args: map[Expression:#define PAGE_SIZE PathPrefix:include/]
Results: map[Output:include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
]
|
| 157/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 12657
output: 29
thoughts: 51
Thoughts: Okay, here's my take on those thoughts, framed as my own:
**Page Size Analysis - x86 Specifics**
Alright, let's nail down this `PAGE_SIZE` thing. Right, it's defined as `(_AC(1,UL) << CONFIG_PAGE_SHIFT)`. That's using an unsigned long, which makes perfect sense for a memory address value. We want to be certain this is consistent across the architecture.
Hmm, but just to be absolutely sure, it's always a good practice to double-check architecture-specific details. Let me quickly cross-reference that with `arch/x86/include/asm/page_types.h` to confirm the unsigned long usage. Gotta be thorough, you know? Just to make sure there are no surprises with the x86 implementation.
|
| 158/4 |
2026/09/09 17:16 |
tool |
grepper |
0m
Error:
Args: map[Expression:define PAGE_SIZE PathPrefix:arch/x86]
Results:
|
| 159/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 12929
output: 30
thoughts: 15
Thoughts: Here's a summary of my thought process, as requested:
**Diving into the Architecture-Agnostic Page Definition**
Okay, I need to understand how the system defines pages at a generic level. The best place to start, given the nature of the inquiry, is likely within the include directories, and specifically the architecture-agnostic definitions. Let me take a look at `include/asm-generic/page.h`. This is where the core, high-level page structure should be defined, independent of any specific hardware details. I'm expecting to find the fundamental attributes here – the size, any key flags for memory management, and perhaps some essential macros related to page manipulation. I need to refresh my understanding of how this abstraction layer is constructed, so this is a great starting point for a deeper dive.
|
| 160/4 |
2026/09/09 17:16 |
tool |
grepper |
0m
Error:
Args: map[Expression:define PAGE_SIZE PathPrefix:include/asm-generic/]
Results:
|
| 161/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 13158
output: 34
thoughts: 14
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Grep Strategy: Unveiling the Memory Landscape**
Alright, my internal compiler just kicked in. The initial thought immediately points me toward the `PAGE_SIZE.*PAGE_SHIFT` pairing. Classic! It's a fundamental dance of hardware abstraction, and my brain instantly starts tracing the implications. I'm thinking about how the system defines the granularity of memory management and the base address calculations. `PAGE_SIZE` gives me the raw byte count, the fundamental unit, while `PAGE_SHIFT` is the elegant, bit-shifting shortcut for determining the page size from a power-of-two value. It's efficiency at its finest.
The `grep` suggests I'm looking for usages or definitions of these macros. That's a good place to start, as it gives me a wide net to look for the system-specific configurations, or potential points of interaction, right? I'm anticipating that this will give me a map of where these values are used, and therefore a view into the page size configuration within the system.
I'm probably anticipating a dive into header files, kernel source, or potentially even build configurations. I'm keen to see if this is a platform-specific query (ARM, x86, RISC-V, etc.) or something more generic. Maybe there's a surprise in there. If I'm lucky, I might uncover interesting corner cases, potential performance optimizations, or even compatibility issues related to page size changes, address space layout randomization (ASLR), or NUMA architectures. I'm essentially looking for a map of how the system uses this basic building block.
|
| 162/4 |
2026/09/09 17:16 |
tool |
grepper |
0m
Error:
Args: map[Expression:#define PAGE_SIZE.*PAGE_SHIFT PathPrefix:arch/x86]
Results:
|
| 163/4 |
2026/09/09 17:16 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 13576
output: 29
thoughts: 15
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Hunting Down PAGE_SIZE**
Okay, so I need to track down the definition of `PAGE_SIZE` within the Linux kernel source. I know it's a fundamental value, so it'll almost certainly be defined in one of the core include files. My initial thought is to start with the obvious place: `include/linux`. It's where the most basic and frequently-used definitions live, covering everything from data structures to system calls. I expect to find it defined somewhere near the memory management or architecture-specific headers. I'll need to use my preferred search tools and maybe a bit of `grep` or `find` magic to pinpoint it efficiently. I’ll start by casting a wide net, and then narrow my search based on where the results lead me. It's likely architecture-dependent, so I need to keep that in mind as I refine my search. Time to dive in.
|
| 164/4 |
2026/09/09 17:17 |
tool |
grepper |
0m
Args: map[Expression:#define PAGE_SIZE\b PathPrefix:include/]
Results: map[Output:include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
]
|
| 165/4 |
2026/09/09 17:17 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 13898
output: 37
thoughts: 80
Thoughts: **Analyzing SCSI Scatter-Gather List Construction**
Okay, so I'm looking at this `PAGE_SIZE` definition, and it's defined as `(_AC(1,UL) << CONFIG_PAGE_SHIFT)`. No surprises there, it's essentially a bit shift to determine the page size, and the type is correctly specified as `unsigned long`, which makes sense for handling potentially large memory sizes.
But wait, I need to make sure this all ties into the `sg_build_indirect` function. I have to think through what's happening. The crucial thing now is to be absolutely sure of the data types being used within that function. My main concern is the type of the `num` variable. This is critical for indexing and buffer manipulation, I need to ensure there are no implicit conversions or overflows that will result in the scatter gather list being built incorrectly.
I'll check `drivers/scsi/sg.c` lines 1850-1880, as I know that's where `sg_build_indirect` is implemented. I will scrutinize that section. I'll be looking for type declarations, how the `num` variable is used, and how it interacts with other variables to ensure no potential issues with data type consistency or overflows. Precision is key here.
|
| 166/4 |
2026/09/09 17:17 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1845 LineCount:35]
Results: map[Contents:1845:
1846: schp->pages = kzalloc(sg_bufflen, gfp_flags);
1847: if (!schp->pages)
1848: return -ENOMEM;
1849: schp->sglist_len = sg_bufflen;
1850: return tablesize; /* number of scat_gath elements allocated */
1851: }
1852:
1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
]
|
| 167/4 |
2026/09/09 17:17 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 14957
output: 36
thoughts: 302
Thoughts: **My Initial Thoughts on Memory Allocation**
Okay, so I'm looking at this code snippet, and the first thing that jumps out is the initialization of a few integer variables: `ret_sz`, `i`, `k`, `rem_sz`, `num`, and `mx_sc_elems`. `num` is definitely an integer. But hold on, I need to consider potential edge cases. What if `num` is less than or equal to zero, or even just smaller than `PAGE_SIZE`?
Then, the C language behavior catches my attention. What happens if `num` is negative, like -1, and it's compared with `PAGE_SIZE`? If `PAGE_SIZE` is an `unsigned long`, `num` is going to get converted to an unsigned long, which is a key consideration.
Aha! -1, when cast to an unsigned long, becomes `0xffffffffffffffffUL`. Now the question is: is `0xffffffffffffffffUL` less than `PAGE_SIZE`? The answer, of course, is no. This has important implications when we get to the `init_sg` function.
Inside `init_sg`, I see this conditional:
```c
if (scatter_elem_sz < PAGE_SIZE) {
```
`scatter_elem_sz` is also an integer. That makes me think... can `module_param_named` even use an unsigned integer (`uint`) instead of a signed integer (`int`)? I need to check how `scatter_elem_sz` is defined in `module_param_named`.
Let's look at the line: `module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);` So it's defined as an int, which is good to know, but... Now, the history of this whole section of code... I need to dive into the git logs for `drivers/scsi/sg.c` to look for mentions of `scatter_elem_sz` or `sg_build_indirect` to see if there's any important context there. That should help me understand the evolution of this code and any potential pitfalls.
|
| 168/4 |
2026/09/09 17:17 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 169/4 |
2026/09/09 17:17 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 15838
output: 27
thoughts: 19
Thoughts: Okay, here's my attempt at summarizing my internal thought process as a subject matter expert, starting with a bolded header:
**Diving into Commit 6460e75a104d**
Alright, let's take a look at this commit hash, `6460e75a104d`. Right off the bat, I know I need context. A simple hash like this is useless without knowing the repository, the branch, and ideally, some surrounding commits. My first thought is: *Where did this originate?* Is it from the main development branch, a feature branch, a bugfix branch? What's the surrounding commit history looking like? I need to get a feel for the scope of this change.
I'm mentally preparing for a deep dive. I'm expecting to encounter code, configuration changes, documentation updates, maybe even test modifications. Based on the hash alone, I don't have any reason to believe a specific type of change, but it could range from a minor tweak to a substantial refactor. This implies I need to consider various likely scenarios.
My mental checklist starts: first, a quick scan of the diff to grasp the core modifications. Then, I need to evaluate its impact on the existing codebase. Are there any dependencies involved? Does this change touch areas that I am familiar with, or is this new territory? I'll be looking for potential conflicts, performance implications, and security vulnerabilities, as appropriate for the project domain. This is going to involve reading the actual changes and tracing execution paths, cross-referencing this hash with the bigger picture of the project.
Ultimately, I will be assessing this commit's merit and integrating it into the codebase, if appropriate. I will look for any potential regressions introduced by this commit, any performance, security, and stability concerns. Before I can do anything else, I need to know *what* `6460e75a104d` is actually *doing*.
|
| 170/4 |
2026/09/09 17:17 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 171/4 |
2026/09/09 17:17 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 20711
output: 26
thoughts: 173
Thoughts: **Analyzing Recent Changes in Scatter-Gather Element Size**
Okay, let's dive into this. My initial focus is on commit 6460e75a104d, specifically the addition of `num = scatter_elem_sz;`. Interesting. It looks like we're capturing the scatter element size. And there's a conditional block that follows. If `num` differs from the previous size, `scatter_elem_sz_prev`, we have some adjustments. The conditional appears to enforce a minimum size of `PAGE_SIZE` if `num` is smaller. Otherwise, it simply updates the previous size.
Now, let's pull in commit 10db10d144c0 ("sg: convert the indirect IO path to use the block layer"). This is where things should get interesting, as it indicates a significant architectural shift. I need to carefully examine how this commit interacts with the changes made in the previous one, particularly regarding scatter-gather element sizing within the block layer context. The block layer's involvement suggests potential impacts on memory management, performance, and perhaps even device compatibility. This is the critical piece I need to understand for a deeper analysis.
|
| 172/4 |
2026/09/09 17:17 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 173/4 |
2026/09/09 17:17 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 30807
output: 65
thoughts: 1822
Thoughts: **Vulnerability Analysis of Scatter Gather Element Size Calculation**
Okay, so I'm digging into this commit, 10db10d144c0, and something immediately jumps out. Originally, they were using `sg_page_malloc`, but it looks like they switched to a different method for determining the allocation size. The core issue revolves around how the `num` variable is handled when it's less than `PAGE_SIZE`.
Initially, the code checks if `num` (which is derived from `scatter_elem_sz`) is less than `PAGE_SIZE`. The original code just set `scatter_elem_sz = PAGE_SIZE;` but it didn't update the `num` variable itself. So, if `scatter_elem_sz` was initially, say, zero, then `num` *remains* zero after the check, leading to a call to `get_order(0)`. This is where things get really bad because `get_order(0)` is essentially undefined. It boils down to a bitwise operation where `fls_long` gets a huge number, specifically 52.
This, in turn, results in a `ret_sz` calculation that causes an integer shift exponent overflow. Basically, you're trying to shift a '1' left by a ridiculous number of bits (64 bits, which is too big for a 32-bit int), which triggers UBSAN.
But wait, it gets worse. I was looking at the `scatter_elem_sz` variable, and noticed it's a signed integer. If someone writes a negative value into `/sys/module/sg/parameters/scatter_elem_sz`, the `num < PAGE_SIZE` comparison becomes problematic. The comparison between `int` and `unsigned long` triggers type promotion, which means the negative `num` will be converted to a *very* large unsigned long, leading it to evaluate to `false` and cause the issue again, because `get_order` is still called on a negative number, which results in `fls_long((~0UL - 1) >> 12)` which still causes the 64 bit shift exponent.
So, negative values are a big problem! A negative value will result in `order = 52` and the same overflow. We need to prevent the negative numbers. We need to determine if `num < (int)PAGE_SIZE` is the right solution.
The proposed fix does include `num = PAGE_SIZE;` *before* the `order` calculation, but the main question is: Is `num < PAGE_SIZE` signed or unsigned when the comparison happens? We need to verify how the compiler handles this comparison, to make sure this fix is actually correct. What if `num < (int)PAGE_SIZE` is the better solution. Also, why is `num` signed in the first place? And `get_order` takes an unsigned long - how does this all fit together? And we need to double check how the compiler handles the comparison in all cases! We must make sure that `num` can never be 0 or negative.
|
| 174/4 |
2026/09/09 17:17 |
tool |
codeexpert |
2m
Args: map[Question:In C in the Linux kernel on x86_64, if `int num = -1;`, what does the condition `if (num < PAGE_SIZE)` evaluate to? Does `num` get converted to `unsigned long`?]
Results: map[Answer:In the Linux kernel on x86_64, the condition `if (num < PAGE_SIZE)` evaluates to **false (0)**, and **yes, `num` gets converted to `unsigned long`**.
### Detailed Explanation:
1. **Definition and Type of `PAGE_SIZE`:**
In the Linux kernel (defined in `include/vdso/page.h` via `arch/x86/include/asm/page_types.h`), `PAGE_SIZE` is defined as:
```c
#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
```
- In C code, `_AC(1, UL)` expands to `1UL` (defined in `include/uapi/linux/const.h`).
- On x86_64, `CONFIG_PAGE_SHIFT` is `12` (4 KB pages).
- Therefore, `PAGE_SIZE` expands to `(1UL << 12)`, which equals `4096UL`. Its type is **`unsigned long`**.
2. **Usual Arithmetic Conversions in C:**
- On x86_64 (LP64 data model), `int` is a 32-bit signed integer and `unsigned long` is a 64-bit unsigned integer.
- When evaluating the binary `<` operator between `int` and `unsigned long`, C's Usual Arithmetic Conversions (C11 §6.3.1.8) apply:
> *"if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type."*
- Because `unsigned long` has greater integer conversion rank than `int`, `num` is converted to **`unsigned long`**.
3. **Value Evaluation:**
- Converting `int` with value `-1` to `unsigned long` produces `ULONG_MAX` (`0xFFFFFFFFFFFFFFFFUL` or `18,446,744,073,709,551,615`).
- The expression evaluates as:
```c
18446744073709551615UL < 4096UL
```
- This comparison is **false** (`0`), so the body of the `if` statement is not executed.]
|
| 175/5 |
2026/09/09 17:17 |
agent |
codeexpert |
2m
Model:
Results: map[Answer:In the Linux kernel on x86_64, the condition `if (num < PAGE_SIZE)` evaluates to **false (0)**, and **yes, `num` gets converted to `unsigned long`**.
### Detailed Explanation:
1. **Definition and Type of `PAGE_SIZE`:**
In the Linux kernel (defined in `include/vdso/page.h` via `arch/x86/include/asm/page_types.h`), `PAGE_SIZE` is defined as:
```c
#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
```
- In C code, `_AC(1, UL)` expands to `1UL` (defined in `include/uapi/linux/const.h`).
- On x86_64, `CONFIG_PAGE_SHIFT` is `12` (4 KB pages).
- Therefore, `PAGE_SIZE` expands to `(1UL << 12)`, which equals `4096UL`. Its type is **`unsigned long`**.
2. **Usual Arithmetic Conversions in C:**
- On x86_64 (LP64 data model), `int` is a 32-bit signed integer and `unsigned long` is a 64-bit unsigned integer.
- When evaluating the binary `<` operator between `int` and `unsigned long`, C's Usual Arithmetic Conversions (C11 §6.3.1.8) apply:
> *"if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type."*
- Because `unsigned long` has greater integer conversion rank than `int`, `num` is converted to **`unsigned long`**.
3. **Value Evaluation:**
- Converting `int` with value `-1` to `unsigned long` produces `ULONG_MAX` (`0xFFFFFFFFFFFFFFFFUL` or `18,446,744,073,709,551,615`).
- The expression evaluates as:
```c
18446744073709551615UL < 4096UL
```
- This comparison is **false** (`0`), so the body of the `if` statement is not executed.]
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.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
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: In C in the Linux kernel on x86_64, if `int num = -1;`, what does the condition `if (num < PAGE_SIZE)` evaluate to? Does `num` get converted to `unsigned long`?
|
| 176/6 |
2026/09/09 17:17 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4093
output: 35
thoughts: 106
Thoughts: **Analyzing a Kernel Integer Comparison**
Okay, so the user's posed a good question. They're curious about an integer comparison in the Linux kernel on x86_64, specifically, `if (num < PAGE_SIZE)` where `num` is initialized to `-1`. My first thought is: let's dig into the details. I need to figure out *precisely* how `PAGE_SIZE` is defined on that architecture. We're dealing with C, so I have to be precise.
The crux of it is whether `-1` is going to be implicitly converted to an `unsigned long` during the comparison. My intuition says *yes*, but I need to confirm that. We're in the kernel, so there's potential for subtle type conversions happening. I need to confirm the underlying behavior.
Time to consult the source. Let's fire up `grepper` or `codesearch`. A quick search for the `PAGE_SIZE` definition should nail down its type, and that'll tell us everything we need to know about the comparison. Once I've got that, I'll be able to confirm whether the negative one is being compared as a negative integer, or as a large unsigned number.
|
| 177/6 |
2026/09/09 17:17 |
tool |
grepper |
0m
Error:
Args: map[Expression:#define\s+PAGE_SIZE\b PathPrefix:arch/x86]
Results:
|
| 178/6 |
2026/09/09 17:17 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4509
output: 31
thoughts: 21
Thoughts: Okay, here's my summarized thought process, presented as if I were thinking it:
**Finding PAGE_SIZE in the Kernel**
Alright, time to get to work. I need to find the definition of `#define PAGE_SIZE`. Obviously, that's a fundamental constant, and in the Linux kernel, that type of thing almost always resides in an include file. So, my initial thought is to zero in on the `include/` directory. That's the most logical place to start digging. If it's not immediately obvious in `include/`, I'll expand the search across the entire kernel source tree. This constant is so important it's likely defined globally, or at least highly accessible. Let's start with `include/`, and then widen the search if need be.
|
| 179/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Args: map[Expression:#define\s+PAGE_SIZE\b PathPrefix:include]
Results: map[Output:include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
]
|
| 180/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4798
output: 36
thoughts: 50
Thoughts: **Investigating the Definition of PAGE_SIZE for x86**
Okay, so I need to nail down where `PAGE_SIZE` is defined for the x86 architecture, specifically within the kernel. My first instinct is to check `include/vdso/page.h`, as that's often a good starting point for kernel-related definitions. However, given that it's x86 specific, it's more likely located in the `arch/x86/include` directory. Therefore, I will perform a `grep` for `PAGE_SIZE` within the `arch/x86/include` directory. This should quickly reveal the relevant header file and where the macro is actually defined. That'll be the fastest way to get to the answer.
|
| 181/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Error:
Args: map[Expression:PAGE_SIZE PathPrefix:arch/x86/include/asm/page.h]
Results:
|
| 182/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 5061
output: 38
thoughts: 47
Thoughts: Here's my summary, as though I were thinking through the problem:
**Examining Page Type Definitions**
Okay, so I need to understand how page types are defined in this x86-specific context. My first instinct is to dive into the architecture-specific include files. I'll start by checking either `arch/x86/include/asm/page_types.h` or, potentially, the more generic `page.h`. I'll see if the x86 architecture has any specialized definitions there, or if they're handled more broadly. Then, if that doesn't yield the information I need, I'll need to broaden the scope and systematically review other header files within the `arch/x86/include/asm` directory. I'm looking for the canonical definitions.
|
| 183/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SHIFT PathPrefix:arch/x86/include/asm/page_types.h]
Results: map[Output:arch/x86/include/asm/page_types.h-19-
arch/x86/include/asm/page_types.h:20:#define HPAGE_SHIFT PMD_SHIFT
arch/x86/include/asm/page_types.h:21:#define HPAGE_SIZE (_AC(1,UL) << HPAGE_SHIFT)
arch/x86/include/asm/page_types.h-22-#define HPAGE_MASK (~(HPAGE_SIZE - 1))
arch/x86/include/asm/page_types.h:23:#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
arch/x86/include/asm/page_types.h-24-
--
arch/x86/include/asm/page_types.h=58=static inline phys_addr_t get_max_mapped(void)
arch/x86/include/asm/page_types.h-59-{
arch/x86/include/asm/page_types.h:60: return (phys_addr_t)max_pfn_mapped << PAGE_SHIFT;
arch/x86/include/asm/page_types.h-61-}
]
|
| 184/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 5631
output: 36
thoughts: 35
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating PAGE_SIZE's Definition**
Right, *PAGE_SIZE*. Where in the kernel source is that defined? It's a fundamental constant, so it's probably tucked away in a header file. I'm almost certain it's in the `include/asm-generic/page.h` directory, but I'll double-check there first. If it's not immediately obvious, the quick and dirty solution is a grep across the entire header directory. Shouldn't be too hard to find. It's a frequent constant, so I'm sure it won't be missed.
|
| 185/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Error:
Args: map[Expression:#define[ \t]+PAGE_SIZE\b PathPrefix:include/asm-generic]
Results:
|
| 186/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 5867
output: 31
thoughts: 22
Thoughts: Here's my thought process, as requested:
**Finding the System's Page Size Definition**
Okay, so I need to figure out how the system defines its page size. I know this is a fundamental architectural constant, so it's probably defined in a header somewhere. Instead of guessing, I'll go straight to the source. My initial thought is to `grep` across the relevant directories. I'll focus on `arch/` (architecture-specific code) and `include/` (general headers). I'm pretty sure the definition will use a `#define` macro, and given that I know what I'm looking for, I'll search for `#define` followed by something related to "PAGE_SIZE." This will quickly reveal where the system's page size is defined. I'm using `grep` because I can quickly target just what I want.
|
| 187/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Args: map[Expression:define\s+PAGE_SIZE\b PathPrefix:arch/]
Results: map[Output:arch/arc/include/uapi/asm/page.h-26-#define PAGE_SHIFT 13
arch/arc/include/uapi/asm/page.h:27:#define PAGE_SIZE _BITUL(PAGE_SHIFT) /* Default 8K */
arch/arc/include/uapi/asm/page.h-28-#define PAGE_MASK (~(PAGE_SIZE-1))
--
arch/hexagon/kernel/vmlinux.lds.S=21=See asm-generic/sections.h for seemingly required labels.
--
arch/hexagon/kernel/vmlinux.lds.S-23-
arch/hexagon/kernel/vmlinux.lds.S:24:#define PAGE_SIZE _PAGE_SIZE
arch/hexagon/kernel/vmlinux.lds.S-25-
--
arch/loongarch/kernel/vmlinux.lds.S-6-
arch/loongarch/kernel/vmlinux.lds.S:7:#define PAGE_SIZE _PAGE_SIZE
arch/loongarch/kernel/vmlinux.lds.S-8-#define RO_EXCEPTION_TABLE_ALIGN 4
--
arch/mips/kernel/vmlinux.lds.S-4-
arch/mips/kernel/vmlinux.lds.S:5:#define PAGE_SIZE _PAGE_SIZE
arch/mips/kernel/vmlinux.lds.S-6-
--
arch/powerpc/boot/page.h-16-#define PAGE_SHIFT 12
arch/powerpc/boot/page.h:17:#define PAGE_SIZE (ASM_CONST(1) << PAGE_SHIFT)
arch/powerpc/boot/page.h-18-#define PAGE_MASK (~(PAGE_SIZE-1))
]
|
| 188/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6536
output: 34
thoughts: 57
Thoughts: **Examining the Virtual Dynamic Shared Object (VDSO) Page Size**
Okay, I need to revisit that `include/vdso/page.h` file we glanced at before. Specifically, I'm zeroing in on how the page size is defined. Let me just open up `include/vdso/page.h`. Ah, here it is: `#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)`. Right, so it's defined using `CONFIG_PAGE_SHIFT` and some bit shifting. Looks straightforward enough, but I want to make sure I understand it completely. No assumptions here, even if it seems simple. Gotta make sure the details are precise.
|
| 189/6 |
2026/09/09 17:18 |
tool |
read-file |
0m
Args: map[File:include/vdso/page.h FirstLine:1 LineCount:30]
Results: map[Contents: 1: /* SPDX-License-Identifier: GPL-2.0 */
2: #ifndef __VDSO_PAGE_H
3: #define __VDSO_PAGE_H
4:
5: #include <uapi/linux/const.h>
6:
7: /*
8: * PAGE_SHIFT determines the page size.
9: *
10: * Note: This definition is required because PAGE_SHIFT is used
11: * in several places throughout the codebase.
12: */
13: #define PAGE_SHIFT CONFIG_PAGE_SHIFT
14:
15: #define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
16:
17: #if !defined(CONFIG_64BIT)
18: /*
19: * Applies only to 32-bit architectures.
20: *
21: * Subtle: (1 << CONFIG_PAGE_SHIFT) is an int, not an unsigned long.
22: * So if we assign PAGE_MASK to a larger type it gets extended the
23: * way we want (i.e. with 1s in the high bits) while masking a
24: * 64-bit value such as phys_addr_t.
25: */
26: #define PAGE_MASK (~((1 << CONFIG_PAGE_SHIFT) - 1))
27: #else
28: #define PAGE_MASK (~(PAGE_SIZE - 1))
29: #endif
30:
]
|
| 190/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7205
output: 27
thoughts: 63
Thoughts: **Investigating the Definition of `PAGE_SIZE`**
Okay, so I need to track down all the potential sources for `PAGE_SIZE`. My initial understanding is that it's defined within the kernel, but I need to make sure I'm not missing anything crucial. I'm going to delve deeper into where `PAGE_SIZE` could be declared.
I'll check the relationships between the standard header files that are often involved: specifically, `<linux/mm.h>` and `<asm/page.h>`, and how those files might incorporate (directly or indirectly) `vdso/page.h`. I'll explore if `vdso/page.h` itself is defining the `PAGE_SIZE`.
To get a quick overview of how the header files play together, I'm going to start with a grep to search all source files. I'll search for every instance of `vdso/page.h` to see how it's included and used. This should give me a good jumping-off point to understand the interactions.
|
| 191/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Args: map[Expression:vdso/page\.h PathPrefix:include]
Results: map[Output:include/linux/cpumask.h-17-#include <linux/types.h>
include/linux/cpumask.h:18:#include <vdso/page.h>
include/linux/cpumask.h-19-
--
include/vdso/datapage.h-14-#include <vdso/cache.h>
include/vdso/datapage.h:15:#include <vdso/page.h>
include/vdso/datapage.h-16-#include <vdso/time.h>
]
|
| 192/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7659
output: 32
thoughts: 46
Thoughts: **My Immediate Thoughts on Page Size**
Okay, hold on a minute. I need to refresh my memory on where `PAGE_SIZE` is defined within the Linux kernel, specifically concerning x86. I know it's a fundamental concept, but the exact location of that macro is escaping me at the moment. Time to quickly find where this is declared...
Let's begin by searching through the obvious places: `include/` and `arch/x86/`. I'll run a quick find across all files in those directories looking for that specific macro, hoping to jog my memory or confirm its usual location. Searching through the headers should give the answer, or provide an obvious pointer. I'm aiming for speed and accuracy here; there's no need to belabor this. A quick search should be sufficient to identify the file I'm looking for.
|
| 193/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SIZE\b PathPrefix:arch/x86/include]
Results: map[Output:arch/x86/include/asm/boot.h-76-
arch/x86/include/asm/boot.h:77:#define TRAMPOLINE_32BIT_SIZE (2 * PAGE_SIZE)
arch/x86/include/asm/boot.h-78-
arch/x86/include/asm/boot.h:79:#define TRAMPOLINE_32BIT_CODE_OFFSET PAGE_SIZE
arch/x86/include/asm/boot.h-80-#define TRAMPOLINE_32BIT_CODE_SIZE 0xA0
--
arch/x86/include/asm/cpu_entry_area.h=41=struct cea_exception_stacks {
arch/x86/include/asm/cpu_entry_area.h:42: ESTACKS_MEMBERS(PAGE_SIZE, EXCEPTION_STKSZ)
arch/x86/include/asm/cpu_entry_area.h-43-};
--
arch/x86/include/asm/cpu_entry_area.h=48=enum exception_stack_ordering {
--
arch/x86/include/asm/cpu_entry_area.h-70-#define CEA_ESTACK_PAGES \
arch/x86/include/asm/cpu_entry_area.h:71: (sizeof(struct cea_exception_stacks) / PAGE_SIZE)
arch/x86/include/asm/cpu_entry_area.h-72-
--
arch/x86/include/asm/cpu_entry_area.h=76=struct doublefault_stack {
arch/x86/include/asm/cpu_entry_area.h:77: unsigned long stack[(PAGE_SIZE - sizeof(struct x86_hw_tss)) / sizeof(unsigned long)];
arch/x86/include/asm/cpu_entry_area.h-78- struct x86_hw_tss tss;
arch/x86/include/asm/cpu_entry_area.h:79:} __aligned(PAGE_SIZE);
arch/x86/include/asm/cpu_entry_area.h-80-#endif
--
arch/x86/include/asm/cpu_entry_area.h=90=struct cpu_entry_area {
arch/x86/include/asm/cpu_entry_area.h:91: char gdt[PAGE_SIZE];
arch/x86/include/asm/cpu_entry_area.h-92-
--
arch/x86/include/asm/cpu_entry_area.h-98-#ifdef CONFIG_X86_32
arch/x86/include/asm/cpu_entry_area.h:99: char guard_entry_stack[PAGE_SIZE];
arch/x86/include/asm/cpu_entry_area.h-100-#endif
--
arch/x86/include/asm/cpu_entry_area.h-103-#ifdef CONFIG_X86_32
arch/x86/include/asm/cpu_entry_area.h:104: char guard_doublefault_stack[PAGE_SIZE];
arch/x86/include/asm/cpu_entry_area.h-105- struct doublefault_stack doublefault_stack;
--
arch/x86/include/asm/desc.h=44=struct gdt_page {
arch/x86/include/asm/desc.h-45- struct desc_struct gdt[GDT_ENTRIES];
arch/x86/include/asm/desc.h:46:} __attribute__((aligned(PAGE_SIZE)));
arch/x86/include/asm/desc.h-47-
--
arch/x86/include/asm/fixmap.h=55=extern unsigned long __FIXADDR_TOP;
--
arch/x86/include/asm/fixmap.h-57-#else
arch/x86/include/asm/fixmap.h:58:#define FIXADDR_TOP (round_up(VSYSCALL_ADDR + PAGE_SIZE, 1<<PMD_SHIFT) - \
arch/x86/include/asm/fixmap.h:59: PAGE_SIZE)
arch/x86/include/asm/fixmap.h-60-#endif
--
arch/x86/include/asm/fpu/types.h=369=union fpregs_state {
--
arch/x86/include/asm/fpu/types.h-373- struct xregs_state xsave;
arch/x86/include/asm/fpu/types.h:374: u8 __padding[PAGE_SIZE];
arch/x86/include/asm/fpu/types.h-375-};
--
arch/x86/include/asm/intel_ds.h-5-
arch/x86/include/asm/intel_ds.h:6:#define BTS_BUFFER_SIZE (PAGE_SIZE << 4)
arch/x86/include/asm/intel_ds.h-7-#define PEBS_BUFFER_SHIFT 4
arch/x86/include/asm/intel_ds.h:8:#define PEBS_BUFFER_SIZE (PAGE_SIZE << PEBS_BUFFER_SHIFT)
arch/x86/include/asm/intel_ds.h-9-
--
arch/x86/include/asm/intel_ds.h-13- */
arch/x86/include/asm/intel_ds.h:14:#define ARCH_PEBS_THRESH_MULTI ((PEBS_BUFFER_SIZE - PAGE_SIZE) >> PEBS_BUFFER_SHIFT)
arch/x86/include/asm/intel_ds.h-15-#define ARCH_PEBS_THRESH_SINGLE 1
--
arch/x86/include/asm/intel_ds.h=28=struct debug_store {
--
arch/x86/include/asm/intel_ds.h-37- u64 pebs_event_reset[MAX_PEBS_EVENTS + MAX_FIXED_PEBS_EVENTS];
arch/x86/include/asm/intel_ds.h:38:} __aligned(PAGE_SIZE);
arch/x86/include/asm/intel_ds.h-39-
--
arch/x86/include/asm/kexec.h-24-
arch/x86/include/asm/kexec.h:25:# define KEXEC_CONTROL_PAGE_SIZE 4096
arch/x86/include/asm/kexec.h-26-# define KEXEC_CONTROL_CODE_MAX_SIZE 2048
--
arch/x86/include/asm/kfence.h=22=static inline bool arch_kfence_init_pool(void)
--
arch/x86/include/asm/kfence.h-26- for (addr = (unsigned long)__kfence_pool; is_kfence_address((void *)addr);
arch/x86/include/asm/kfence.h:27: addr += PAGE_SIZE) {
arch/x86/include/asm/kfence.h-28- unsigned int level;
--
arch/x86/include/asm/kvm_host.h-137-#define KVM_HPAGE_SHIFT(x) (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
arch/x86/include/asm/kvm_host.h:138:#define KVM_HPAGE_SIZE(x) (1UL << KVM_HPAGE_SHIFT(x))
arch/x86/include/asm/kvm_host.h:139:#define KVM_HPAGE_MASK(x) (~(KVM_HPAGE_SIZE(x) - 1))
arch/x86/include/asm/kvm_host.h:140:#define KVM_PAGES_PER_HPAGE(x) (KVM_HPAGE_SIZE(x) / PAGE_SIZE)
arch/x86/include/asm/kvm_host.h-141-
--
arch/x86/include/asm/page_32.h=26=static inline void clear_page(void *page)
arch/x86/include/asm/page_32.h-27-{
arch/x86/include/asm/page_32.h:28: memset(page, 0, PAGE_SIZE);
arch/x86/include/asm/page_32.h-29-}
--
arch/x86/include/asm/page_32.h=31=static inline void copy_page(void *to, void *from)
arch/x86/include/asm/page_32.h-32-{
arch/x86/include/asm/page_32.h:33: memcpy(to, from, PAGE_SIZE);
arch/x86/include/asm/page_32.h-34-}
--
arch/x86/include/asm/page_32_types.h-22-#define THREAD_SIZE_ORDER 1
arch/x86/include/asm/page_32_types.h:23:#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
arch/x86/include/asm/page_32_types.h-24-
--
arch/x86/include/asm/page_64.h=85=static inline void clear_pages(void *addr, unsigned int npages)
arch/x86/include/asm/page_64.h-86-{
arch/x86/include/asm/page_64.h:87: u64 len = npages * PAGE_SIZE;
arch/x86/include/asm/page_64.h-88- /*
--
arch/x86/include/asm/page_64.h=138=static __always_inline unsigned long task_size_max(void)
--
arch/x86/include/asm/page_64.h-144- "=r" (ret),
arch/x86/include/asm/page_64.h:145: [small] "i" ((1ul << 47)-PAGE_SIZE),
arch/x86/include/asm/page_64.h:146: [large] "i" ((1ul << 56)-PAGE_SIZE));
arch/x86/include/asm/page_64.h-147-
--
arch/x86/include/asm/page_64_types.h-15-#define THREAD_SIZE_ORDER (2 + KASAN_STACK_ORDER)
arch/x86/include/asm/page_64_types.h:16:#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
arch/x86/include/asm/page_64_types.h-17-
arch/x86/include/asm/page_64_types.h-18-#define EXCEPTION_STACK_ORDER (1 + KASAN_STACK_ORDER)
arch/x86/include/asm/page_64_types.h:19:#define EXCEPTION_STKSZ (PAGE_SIZE << EXCEPTION_STACK_ORDER)
arch/x86/include/asm/page_64_types.h-20-
arch/x86/include/asm/page_64_types.h-21-#define IRQ_STACK_ORDER (2 + KASAN_STACK_ORDER)
arch/x86/include/asm/page_64_types.h:22:#define IRQ_STACK_SIZE (PAGE_SIZE << IRQ_STACK_ORDER)
arch/x86/include/asm/page_64_types.h-23-
--
arch/x86/include/asm/page_64_types.h-53-#define TASK_SIZE_MAX task_size_max()
arch/x86/include/asm/page_64_types.h:54:#define DEFAULT_MAP_WINDOW ((1UL << 47) - PAGE_SIZE)
arch/x86/include/asm/page_64_types.h-55-
--
arch/x86/include/asm/page_types.h-20-#define HPAGE_SHIFT PMD_SHIFT
arch/x86/include/asm/page_types.h:21:#define HPAGE_SIZE (_AC(1,UL) << HPAGE_SHIFT)
arch/x86/include/asm/page_types.h:22:#define HPAGE_MASK (~(HPAGE_SIZE - 1))
arch/x86/include/asm/page_types.h-23-#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
--
arch/x86/include/asm/pgtable_32_areas.h=17=extern bool __vmalloc_start_set; /* set once high_memory is set */
--
arch/x86/include/asm/pgtable_32_areas.h-26-
arch/x86/include/asm/pgtable_32_areas.h:27:#define CPU_ENTRY_AREA_PAGES (NR_CPUS * DIV_ROUND_UP(sizeof(struct cpu_entry_area), PAGE_SIZE))
arch/x86/include/asm/pgtable_32_areas.h-28-
--
arch/x86/include/asm/pgtable_32_areas.h-30-#define CPU_ENTRY_AREA_BASE \
arch/x86/include/asm/pgtable_32_areas.h:31: ((FIXADDR_TOT_START - PAGE_SIZE*(CPU_ENTRY_AREA_PAGES+1)) & PMD_MASK)
arch/x86/include/asm/pgtable_32_areas.h-32-
arch/x86/include/asm/pgtable_32_areas.h-33-#define LDT_BASE_ADDR \
arch/x86/include/asm/pgtable_32_areas.h:34: ((CPU_ENTRY_AREA_BASE - PAGE_SIZE) & PMD_MASK)
arch/x86/include/asm/pgtable_32_areas.h-35-
--
arch/x86/include/asm/pgtable_32_areas.h-38-#define PKMAP_BASE \
arch/x86/include/asm/pgtable_32_areas.h:39: ((LDT_BASE_ADDR - PAGE_SIZE) & PMD_MASK)
arch/x86/include/asm/pgtable_32_areas.h-40-
arch/x86/include/asm/pgtable_32_areas.h-41-#ifdef CONFIG_HIGHMEM
arch/x86/include/asm/pgtable_32_areas.h:42:# define VMALLOC_END (PKMAP_BASE - 2 * PAGE_SIZE)
arch/x86/include/asm/pgtable_32_areas.h-43-#else
arch/x86/include/asm/pgtable_32_areas.h:44:# define VMALLOC_END (LDT_BASE_ADDR - 2 * PAGE_SIZE)
arch/x86/include/asm/pgtable_32_areas.h-45-#endif
--
arch/x86/include/asm/pgtable_64.h=277=L3_START_KERNEL = pud_index(__START_KERNEL_map)
--
arch/x86/include/asm/pgtable_64.h-279-#define SYM_DATA_START_PAGE_ALIGNED(name) \
arch/x86/include/asm/pgtable_64.h:280: SYM_START(name, SYM_L_GLOBAL, .balign PAGE_SIZE)
arch/x86/include/asm/pgtable_64.h-281-
--
arch/x86/include/asm/pgtable_64_types.h=43=extern unsigned int ptrs_per_p4d;
--
arch/x86/include/asm/pgtable_64_types.h-190-
arch/x86/include/asm/pgtable_64_types.h:191:#define PGD_KERNEL_START ((PAGE_SIZE / 2) / sizeof(pgd_t))
arch/x86/include/asm/pgtable_64_types.h-192-
--
arch/x86/include/asm/pgtable_areas.h-9-#define CPU_ENTRY_AREA_RO_IDT CPU_ENTRY_AREA_BASE
arch/x86/include/asm/pgtable_areas.h:10:#define CPU_ENTRY_AREA_PER_CPU (CPU_ENTRY_AREA_RO_IDT + PAGE_SIZE)
arch/x86/include/asm/pgtable_areas.h-11-
--
arch/x86/include/asm/processor.h=379=struct entry_stack {
arch/x86/include/asm/processor.h:380: char stack[PAGE_SIZE];
arch/x86/include/asm/processor.h-381-};
--
arch/x86/include/asm/processor.h=383=struct entry_stack_page {
arch/x86/include/asm/processor.h-384- struct entry_stack stack;
arch/x86/include/asm/processor.h:385:} __aligned(PAGE_SIZE);
arch/x86/include/asm/processor.h-386-
--
arch/x86/include/asm/processor.h=418=struct tss_struct {
--
arch/x86/include/asm/processor.h-426- struct x86_io_bitmap io_bitmap;
arch/x86/include/asm/processor.h:427:} __aligned(PAGE_SIZE);
arch/x86/include/asm/processor.h-428-
--
arch/x86/include/asm/realmode.h=81=static __always_inline size_t real_mode_size_needed(void)
--
arch/x86/include/asm/realmode.h-85-
arch/x86/include/asm/realmode.h:86: return ALIGN(real_mode_blob_end - real_mode_blob, PAGE_SIZE);
arch/x86/include/asm/realmode.h-87-}
--
arch/x86/include/asm/sev.h=206=struct snp_guest_msg {
arch/x86/include/asm/sev.h-207- struct snp_guest_msg_hdr hdr;
arch/x86/include/asm/sev.h:208: u8 payload[PAGE_SIZE - sizeof(struct snp_guest_msg_hdr)];
arch/x86/include/asm/sev.h-209-} __packed;
--
arch/x86/include/asm/sev.h=327=struct svsm_ca {
--
arch/x86/include/asm/sev.h-331-
arch/x86/include/asm/sev.h:332: u8 svsm_buffer[PAGE_SIZE - 8];
arch/x86/include/asm/sev.h-333-};
--
arch/x86/include/asm/sev.h=582=static inline void sev_evict_cache(void *va, int npages)
--
arch/x86/include/asm/sev.h-594- for (page_idx = 0; page_idx < npages; page_idx++) {
arch/x86/include/asm/sev.h:595: val = bytes[page_idx * PAGE_SIZE];
arch/x86/include/asm/sev.h:596: val = bytes[page_idx * PAGE_SIZE + PAGE_SIZE - 1];
arch/x86/include/asm/sev.h-597- }
--
arch/x86/include/asm/shmparam.h-4-
arch/x86/include/asm/shmparam.h:5:#define SHMLBA PAGE_SIZE /* attach addr a multiple of this */
arch/x86/include/asm/shmparam.h-6-
--
arch/x86/include/asm/stacktrace.h=42=bool get_stack_guard_info(unsigned long *stack, struct stack_info *info)
--
arch/x86/include/asm/stacktrace.h-47- /* but if it is in the page below it, we hit a guard */
arch/x86/include/asm/stacktrace.h:48: return get_stack_info_noinstr((void *)stack + PAGE_SIZE, current, info);
arch/x86/include/asm/stacktrace.h-49-}
--
arch/x86/include/asm/svm.h=540=struct vmcb {
--
arch/x86/include/asm/svm.h-558-#define EXPECTED_VMCB_CONTROL_AREA_SIZE 1024
arch/x86/include/asm/svm.h:559:#define EXPECTED_GHCB_SIZE PAGE_SIZE
arch/x86/include/asm/svm.h-560-
--
arch/x86/include/asm/tlbflush.h=350=static inline void flush_tlb_page(struct vm_area_struct *vma, unsigned long a)
arch/x86/include/asm/tlbflush.h-351-{
arch/x86/include/asm/tlbflush.h:352: flush_tlb_mm_range(vma->vm_mm, a, a + PAGE_SIZE, PAGE_SHIFT, false);
arch/x86/include/asm/tlbflush.h-353-}
--
arch/x86/include/asm/uaccess_64.h=98=static inline bool __access_ok(const void __user *ptr, unsigned long size)
arch/x86/include/asm/uaccess_64.h-99-{
arch/x86/include/asm/uaccess_64.h:100: if (__builtin_constant_p(size <= PAGE_SIZE) && size <= PAGE_SIZE) {
arch/x86/include/asm/uaccess_64.h-101- return valid_user_address(ptr);
--
arch/x86/include/asm/vdso.h=13=struct vdso_image {
arch/x86/include/asm/vdso.h-14- void *data;
arch/x86/include/asm/vdso.h:15: unsigned long size; /* Always a multiple of PAGE_SIZE */
arch/x86/include/asm/vdso.h-16-
--
arch/x86/include/asm/vdso/vsyscall.h-7-#define VDSO_NR_VCLOCK_PAGES 2
arch/x86/include/asm/vdso/vsyscall.h:8:#define VDSO_VCLOCK_PAGES_START(_b) ((_b) + (__VDSO_PAGES - VDSO_NR_VCLOCK_PAGES) * PAGE_SIZE)
arch/x86/include/asm/vdso/vsyscall.h-9-#define VDSO_PAGE_PVCLOCK_OFFSET 0
--
arch/x86/include/asm/xen/page.h=25=typedef struct xpaddr {
--
arch/x86/include/asm/xen/page.h-47-
arch/x86/include/asm/xen/page.h:48:#define P2M_PER_PAGE (PAGE_SIZE / sizeof(unsigned long))
arch/x86/include/asm/xen/page.h-49-
--
arch/x86/include/uapi/asm/amd_hsmp.h=641=struct hsmp_telemetry_data {
--
arch/x86/include/uapi/asm/amd_hsmp.h-656- * Fetch the firmware metric (telemetry) table for a given socket via the
arch/x86/include/uapi/asm/amd_hsmp.h:657: * HSMP character device. This avoids the PAGE_SIZE limitation of the
arch/x86/include/uapi/asm/amd_hsmp.h-658- * sysfs binary attribute path for tables larger than one page (such as the
]
|
| 194/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14061
output: 39
thoughts: 77
Thoughts: **Investigating the Definition of PAGE_SIZE**
Okay, so I need to understand how `PAGE_SIZE` is defined within the x86 architecture, specifically within the kernel. My first instinct is to navigate the kernel source tree, starting with the architecture-specific include files. Let's see... I'll check `arch/x86/include/asm/` and specifically, I'm going to look for the definition of `PAGE_SIZE`.
Since it relates to memory pages, my guess is it will be in `page.h`. Alright, I'll go ahead and take a look at `arch/x86/include/asm/page.h`. I need to figure out how the architecture defines the page size, which is a fundamental concept for memory management. Let me read that file and see what's in there.
|
| 195/6 |
2026/09/09 17:18 |
tool |
read-file |
0m
Args: map[File:arch/x86/include/asm/page.h FirstLine:1 LineCount:50]
Results: map[Contents: 1: /* SPDX-License-Identifier: GPL-2.0 */
2: #ifndef _ASM_X86_PAGE_H
3: #define _ASM_X86_PAGE_H
4:
5: #include <linux/types.h>
6:
7: #ifdef __KERNEL__
8:
9: #include <asm/page_types.h>
10:
11: #ifdef CONFIG_X86_64
12: #include <asm/page_64.h>
13: #else
14: #include <asm/page_32.h>
15: #endif /* CONFIG_X86_64 */
16:
17: #ifndef __ASSEMBLER__
18:
19: struct page;
20:
21: #include <linux/range.h>
22: extern struct range pfn_mapped[];
23: extern int nr_pfn_mapped;
24:
25: static inline void copy_user_page(void *to, void *from, unsigned long vaddr,
26: struct page *topage)
27: {
28: copy_page(to, from);
29: }
30:
31: #define vma_alloc_zeroed_movable_folio(vma, vaddr) \
32: vma_alloc_folio(GFP_HIGHUSER_MOVABLE | __GFP_ZERO, 0, vma, vaddr)
33:
34: #ifndef __pa
35: #define __pa(x) __phys_addr((unsigned long)(x))
36: #endif
37:
38: #define __pa_nodebug(x) __phys_addr_nodebug((unsigned long)(x))
39: /* __pa_symbol should be used for C visible symbols.
40: This seems to be the official gcc blessed way to do such arithmetic. */
41: /*
42: * We need __phys_reloc_hide() here because gcc may assume that there is no
43: * overflow during __pa() calculation and can optimize it unexpectedly.
44: * Newer versions of gcc provide -fno-strict-overflow switch to handle this
45: * case properly. Once all supported versions of gcc understand it, we can
46: * remove this Voodoo magic stuff. (i.e. once gcc3.x is deprecated)
47: */
48: #define __pa_symbol(x) \
49: __phys_addr_symbol(__phys_reloc_hide((unsigned long)(x)))
50:
]
|
| 196/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15093
output: 34
thoughts: 65
Thoughts: **Finding the Kernel's PAGE_SIZE Definition**
Okay, hold on a second! I need to quickly refresh my memory. Where exactly *is* `PAGE_SIZE` defined within the kernel? It's usually something fundamental, so my first thought is to check the `include/asm-generic/` directory, since that's a common place for architecture-independent definitions. But, just to be thorough, I should really broaden the search to the entire `include/` directory.
The most efficient way to pinpoint it is to perform a case-insensitive search for a line that defines it. So, a `grep` for `define PAGE_SIZE` – ignoring case and any leading or trailing whitespace, is the best approach. That should quickly turn up where the macro is declared! Then, I can get back to the actual problem at hand.
|
| 197/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Args: map[Expression:#\s*define\s+PAGE_SIZE\b PathPrefix:include]
Results: map[Output:include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
]
|
| 198/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15440
output: 41
thoughts: 85
Thoughts: **Page Size Determination**
Okay, hold on a second! I'm pretty sure I saw the `PAGE_SIZE` defined somewhere in the `include/vdso/page.h` file. Let me just double check… Yup, there it is: `#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)`. Good. But wait, I'm just quickly confirming this. Is this the only definition? Where else might this be lurking? It's crucial that I'm fully aware of where this is defined, for this to be reliable. Okay, better to be thorough. Let me quickly scan `arch/x86/include/asm/page_types.h` and confirm if there are any other definitions floating around.
|
| 199/6 |
2026/09/09 17:18 |
tool |
read-file |
0m
Args: map[File:arch/x86/include/asm/page_types.h FirstLine:1 LineCount:55]
Results: map[Contents: 1: /* SPDX-License-Identifier: GPL-2.0 */
2: #ifndef _ASM_X86_PAGE_DEFS_H
3: #define _ASM_X86_PAGE_DEFS_H
4:
5: #include <linux/const.h>
6: #include <linux/types.h>
7: #include <linux/mem_encrypt.h>
8:
9: #include <vdso/page.h>
10:
11: #define __VIRTUAL_MASK ((1UL << __VIRTUAL_MASK_SHIFT) - 1)
12:
13: /* Cast P*D_MASK to a signed type so that it is sign-extended if
14: virtual addresses are 32-bits but physical addresses are larger
15: (ie, 32-bit PAE). */
16: #define PHYSICAL_PAGE_MASK (((signed long)PAGE_MASK) & __PHYSICAL_MASK)
17: #define PHYSICAL_PMD_PAGE_MASK (((signed long)PMD_MASK) & __PHYSICAL_MASK)
18: #define PHYSICAL_PUD_PAGE_MASK (((signed long)PUD_MASK) & __PHYSICAL_MASK)
19:
20: #define HPAGE_SHIFT PMD_SHIFT
21: #define HPAGE_SIZE (_AC(1,UL) << HPAGE_SHIFT)
22: #define HPAGE_MASK (~(HPAGE_SIZE - 1))
23: #define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
24:
25: #define HUGE_MAX_HSTATE 2
26:
27: #define PAGE_OFFSET ((unsigned long)__PAGE_OFFSET)
28:
29: #define VMA_DATA_DEFAULT_FLAGS VMA_DATA_FLAGS_TSK_EXEC
30:
31: /* Physical address where kernel should be loaded. */
32: #define LOAD_PHYSICAL_ADDR __ALIGN_KERNEL_MASK(CONFIG_PHYSICAL_START, CONFIG_PHYSICAL_ALIGN - 1)
33:
34: #define __START_KERNEL (__START_KERNEL_map + LOAD_PHYSICAL_ADDR)
35:
36: #ifdef CONFIG_X86_64
37: #include <asm/page_64_types.h>
38: #define IOREMAP_MAX_ORDER (PUD_SHIFT)
39: #else
40: #include <asm/page_32_types.h>
41: #define IOREMAP_MAX_ORDER (PMD_SHIFT)
42: #endif /* CONFIG_X86_64 */
43:
44: #ifndef __ASSEMBLER__
45:
46: #ifdef CONFIG_DYNAMIC_PHYSICAL_MASK
47: extern phys_addr_t physical_mask;
48: #define __PHYSICAL_MASK physical_mask
49: #else
50: #define __PHYSICAL_MASK ((phys_addr_t)((1ULL << __PHYSICAL_MASK_SHIFT) - 1))
51: #endif
52:
53: extern int devmem_is_allowed(unsigned long pagenr);
54:
55: extern unsigned long max_low_pfn_mapped;
]
|
| 200/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16657
output: 36
thoughts: 178
Thoughts: **Examining the VDSO Page Size Definition**
Okay, let's dive into this. Line 9 immediately catches my eye: `#include <vdso/page.h>`. I know the VDSO intimately, so I suspect this holds the key to the virtual dynamic shared object's page size calculation. Let's start by looking at `include/vdso/page.h` itself. Ah, here we are:
```c
#include <uapi/linux/const.h>
/*
* PAGE_SHIFT determines the page size.
*
* Note: This definition is required because PAGE_SHIFT is used
* in several places throughout the codebase.
*/
#define PAGE_SHIFT CONFIG_PAGE_SHIFT
#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
```
Right, `PAGE_SHIFT` is defined as `CONFIG_PAGE_SHIFT`, which is fairly standard and expected. And the `PAGE_SIZE` is calculated using a left bit shift on `_AC(1,UL)` by that value. My interest is definitely piqued by that. But what is `_AC(1,UL)`? We need to know what it resolves to. Looking back, line 5 has included `<uapi/linux/const.h>`. That's where I bet we will find its definition. Time to check `include/uapi/linux/const.h`.
|
| 201/6 |
2026/09/09 17:18 |
tool |
read-file |
0m
Args: map[File:include/uapi/linux/const.h FirstLine:1 LineCount:40]
Results: map[Contents: 1: /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
2: /* const.h: Macros for dealing with constants. */
3:
4: #ifndef _UAPI_LINUX_CONST_H
5: #define _UAPI_LINUX_CONST_H
6:
7: /* Some constant macros are used in both assembler and
8: * C code. Therefore we cannot annotate them always with
9: * 'UL' and other type specifiers unilaterally. We
10: * use the following macros to deal with this.
11: *
12: * Similarly, _AT() will cast an expression with a type in C, but
13: * leave it unchanged in asm.
14: */
15:
16: #ifdef __ASSEMBLY__
17: #define _AC(X,Y) X
18: #define _AT(T,X) X
19: #else
20: #define __AC(X,Y) (X##Y)
21: #define _AC(X,Y) __AC(X,Y)
22: #define _AT(T,X) ((T)(X))
23: #endif
24:
25: #define _UL(x) (_AC(x, UL))
26: #define _ULL(x) (_AC(x, ULL))
27:
28: #define _BITUL(x) (_UL(1) << (x))
29: #define _BITULL(x) (_ULL(1) << (x))
30:
31: #if !defined(__ASSEMBLY__)
32: /*
33: * Missing asm support
34: *
35: * __BIT128() would not work in the asm code, as it shifts an
36: * 'unsigned __int128' data type as direct representation of
37: * 128 bit constants is not supported in the gcc compiler, as
38: * they get silently truncated.
39: *
40: * TODO: Please revisit this implementation when gcc compiler
]
|
| 202/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17781
output: 30
thoughts: 318
Thoughts: **Analyzing the Type of PAGE_SIZE in the Linux Kernel**
Okay, let's break this down. I'm looking at `include/uapi/linux/const.h` and the macro definitions there. I see `_AC` being used, and I know that in the C code context (when `__ASSEMBLY__` isn't defined), `_AC(1, UL)` expands to `(1UL)`. This is where it starts to get interesting. The kernel defines `PAGE_SIZE` as `_AC(1,UL) << CONFIG_PAGE_SHIFT`, which means it effectively becomes `((1UL) << CONFIG_PAGE_SHIFT)`.
My initial thought is to confirm that `_AC(1, UL)` is evaluated to `(1UL)`.
Right, but what's the resulting *type*? That's the key. `1UL` clearly gives me an `unsigned long`. Now, if I shift an `unsigned long` by `CONFIG_PAGE_SHIFT` bits, what's the result? It has to be an `unsigned long`, right? The left-hand side dictates the type. The shift operation doesn't change it.
On x86_64, which is the platform I'm generally working with, `CONFIG_PAGE_SHIFT` is typically 12. Let me confirm that really quick; I know it's a compile-time constant, and I should be able to find it in `arch/x86/Kconfig`. I need to ensure that `PAGE_SIZE` is truly `unsigned long`, and this is a good place to double-check my mental model.
|
| 203/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Error:
Args: map[Expression:CONFIG_PAGE_SHIFT PathPrefix:arch/x86]
Results:
|
| 204/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18500
output: 32
thoughts: 34
Thoughts: **Investigating PAGE_SHIFT on x86**
Alright, let's dive into this `PAGE_SHIFT` constant on x86. I need to understand how page sizes are defined and manipulated within the x86 architecture. My first instinct is to check the typical include directories. Let's see... I'll use `grep` to quickly search the `arch/x86/include` directory for instances of `PAGE_SHIFT`. That should give me a good starting point to trace its definition and usage. No point in reinventing the wheel when you can find it! Time to fire up the terminal and get to it.
|
| 205/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SHIFT PathPrefix:arch/x86/include/asm]
Results: map[Output:arch/x86/include/asm/acpi.h=251=static inline int arch_apei_report_x86_error(struct cper_ia_proc_ctx *ctx_info,
--
arch/x86/include/asm/acpi.h-257-
arch/x86/include/asm/acpi.h:258:#define ACPI_TABLE_UPGRADE_MAX_PHYS (max_low_pfn_mapped << PAGE_SHIFT)
arch/x86/include/asm/acpi.h-259-
--
arch/x86/include/asm/boot.h-12-#else
arch/x86/include/asm/boot.h:13:# define MIN_KERNEL_ALIGN_LG2 (PAGE_SHIFT + THREAD_SIZE_ORDER)
arch/x86/include/asm/boot.h-14-#endif
--
arch/x86/include/asm/dma.h-73-/* 16MB ISA DMA zone */
arch/x86/include/asm/dma.h:74:#define MAX_DMA_PFN ((16UL * 1024 * 1024) >> PAGE_SHIFT)
arch/x86/include/asm/dma.h-75-
arch/x86/include/asm/dma.h-76-/* 4GB broken PCI/AGP hardware bus master zone */
arch/x86/include/asm/dma.h:77:#define MAX_DMA32_PFN (1UL << (32 - PAGE_SHIFT))
arch/x86/include/asm/dma.h-78-
--
arch/x86/include/asm/dma.h-83-/* Compat define for old dma zone */
arch/x86/include/asm/dma.h:84:#define MAX_DMA_ADDRESS ((unsigned long)__va(MAX_DMA_PFN << PAGE_SHIFT))
arch/x86/include/asm/dma.h-85-#endif
--
arch/x86/include/asm/fixmap.h=81=enum fixed_addresses {
--
arch/x86/include/asm/fixmap.h-85-#ifdef CONFIG_X86_VSYSCALL_EMULATION
arch/x86/include/asm/fixmap.h:86: VSYSCALL_PAGE = (FIXADDR_TOP - VSYSCALL_ADDR) >> PAGE_SHIFT,
arch/x86/include/asm/fixmap.h-87-#endif
--
arch/x86/include/asm/fixmap.h=148=extern void reserve_top_address(unsigned long reserve);
arch/x86/include/asm/fixmap.h-149-
arch/x86/include/asm/fixmap.h:150:#define FIXADDR_SIZE (__end_of_permanent_fixed_addresses << PAGE_SHIFT)
arch/x86/include/asm/fixmap.h-151-#define FIXADDR_START (FIXADDR_TOP - FIXADDR_SIZE)
arch/x86/include/asm/fixmap.h:152:#define FIXADDR_TOT_SIZE (__end_of_fixed_addresses << PAGE_SHIFT)
arch/x86/include/asm/fixmap.h-153-#define FIXADDR_TOT_START (FIXADDR_TOP - FIXADDR_TOT_SIZE)
--
arch/x86/include/asm/highmem.h=31=extern unsigned long highstart_pfn, highend_pfn;
--
arch/x86/include/asm/highmem.h-56-#define LAST_PKMAP_MASK (LAST_PKMAP-1)
arch/x86/include/asm/highmem.h:57:#define PKMAP_NR(virt) ((virt-PKMAP_BASE) >> PAGE_SHIFT)
arch/x86/include/asm/highmem.h:58:#define PKMAP_ADDR(nr) (PKMAP_BASE + ((nr) << PAGE_SHIFT))
arch/x86/include/asm/highmem.h-59-
--
arch/x86/include/asm/kmsan.h=63=static inline bool kmsan_virt_addr_valid(void *addr)
--
arch/x86/include/asm/kmsan.h-93- preempt_disable();
arch/x86/include/asm/kmsan.h:94: ret = pfn_valid(x >> PAGE_SHIFT);
arch/x86/include/asm/kmsan.h-95- preempt_enable_no_resched();
--
arch/x86/include/asm/kvm_host.h-136-#define KVM_HPAGE_GFN_SHIFT(x) (((x) - 1) * 9)
arch/x86/include/asm/kvm_host.h:137:#define KVM_HPAGE_SHIFT(x) (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
arch/x86/include/asm/kvm_host.h:138:#define KVM_HPAGE_SIZE(x) (1UL << KVM_HPAGE_SHIFT(x))
arch/x86/include/asm/kvm_host.h-139-#define KVM_HPAGE_MASK(x) (~(KVM_HPAGE_SIZE(x) - 1))
--
arch/x86/include/asm/page.h=25=static inline void copy_user_page(void *to, void *from, unsigned long vaddr,
--
arch/x86/include/asm/page.h-61- */
arch/x86/include/asm/page.h:62:#define virt_to_page(kaddr) pfn_to_page(__pa(kaddr) >> PAGE_SHIFT)
arch/x86/include/asm/page.h-63-extern bool __virt_addr_valid(unsigned long kaddr);
--
arch/x86/include/asm/page.h=66=static __always_inline void *pfn_to_kaddr(unsigned long pfn)
arch/x86/include/asm/page.h-67-{
arch/x86/include/asm/page.h:68: return __va(pfn << PAGE_SHIFT);
arch/x86/include/asm/page.h-69-}
--
arch/x86/include/asm/page_types.h-19-
arch/x86/include/asm/page_types.h:20:#define HPAGE_SHIFT PMD_SHIFT
arch/x86/include/asm/page_types.h:21:#define HPAGE_SIZE (_AC(1,UL) << HPAGE_SHIFT)
arch/x86/include/asm/page_types.h-22-#define HPAGE_MASK (~(HPAGE_SIZE - 1))
arch/x86/include/asm/page_types.h:23:#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
arch/x86/include/asm/page_types.h-24-
--
arch/x86/include/asm/page_types.h=58=static inline phys_addr_t get_max_mapped(void)
arch/x86/include/asm/page_types.h-59-{
arch/x86/include/asm/page_types.h:60: return (phys_addr_t)max_pfn_mapped << PAGE_SHIFT;
arch/x86/include/asm/page_types.h-61-}
--
arch/x86/include/asm/pgalloc.h=62=static inline void pmd_populate_kernel(struct mm_struct *mm,
--
arch/x86/include/asm/pgalloc.h-64-{
arch/x86/include/asm/pgalloc.h:65: paravirt_alloc_pte(mm, __pa(pte) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-66- set_pmd(pmd, __pmd(__pa(pte) | _PAGE_TABLE));
--
arch/x86/include/asm/pgalloc.h=69=static inline void pmd_populate_kernel_safe(struct mm_struct *mm,
--
arch/x86/include/asm/pgalloc.h-71-{
arch/x86/include/asm/pgalloc.h:72: paravirt_alloc_pte(mm, __pa(pte) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-73- set_pmd_safe(pmd, __pmd(__pa(pte) | _PAGE_TABLE));
--
arch/x86/include/asm/pgalloc.h=76=static inline void pmd_populate(struct mm_struct *mm, pmd_t *pmd,
--
arch/x86/include/asm/pgalloc.h-81- paravirt_alloc_pte(mm, pfn);
arch/x86/include/asm/pgalloc.h:82: set_pmd(pmd, __pmd(((pteval_t)pfn << PAGE_SHIFT) | _PAGE_TABLE));
arch/x86/include/asm/pgalloc.h-83-}
--
arch/x86/include/asm/pgalloc.h=97=static inline void pud_populate(struct mm_struct *mm, pud_t *pud, pmd_t *pmd)
arch/x86/include/asm/pgalloc.h-98-{
arch/x86/include/asm/pgalloc.h:99: paravirt_alloc_pmd(mm, __pa(pmd) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-100- set_pud(pud, __pud(_PAGE_TABLE | __pa(pmd)));
--
arch/x86/include/asm/pgalloc.h=103=static inline void pud_populate_safe(struct mm_struct *mm, pud_t *pud, pmd_t *pmd)
arch/x86/include/asm/pgalloc.h-104-{
arch/x86/include/asm/pgalloc.h:105: paravirt_alloc_pmd(mm, __pa(pmd) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-106- set_pud_safe(pud, __pud(_PAGE_TABLE | __pa(pmd)));
--
arch/x86/include/asm/pgalloc.h=111=static inline void p4d_populate(struct mm_struct *mm, p4d_t *p4d, pud_t *pud)
arch/x86/include/asm/pgalloc.h-112-{
arch/x86/include/asm/pgalloc.h:113: paravirt_alloc_pud(mm, __pa(pud) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-114- set_p4d(p4d, __p4d(_PAGE_TABLE | __pa(pud)));
--
arch/x86/include/asm/pgalloc.h=117=static inline void p4d_populate_safe(struct mm_struct *mm, p4d_t *p4d, pud_t *pud)
arch/x86/include/asm/pgalloc.h-118-{
arch/x86/include/asm/pgalloc.h:119: paravirt_alloc_pud(mm, __pa(pud) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-120- set_p4d_safe(p4d, __p4d(_PAGE_TABLE | __pa(pud)));
--
arch/x86/include/asm/pgalloc.h=132=static inline void pgd_populate(struct mm_struct *mm, pgd_t *pgd, p4d_t *p4d)
--
arch/x86/include/asm/pgalloc.h-135- return;
arch/x86/include/asm/pgalloc.h:136: paravirt_alloc_p4d(mm, __pa(p4d) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-137- set_pgd(pgd, __pgd(_PAGE_TABLE | __pa(p4d)));
--
arch/x86/include/asm/pgalloc.h=140=static inline void pgd_populate_safe(struct mm_struct *mm, pgd_t *pgd, p4d_t *p4d)
--
arch/x86/include/asm/pgalloc.h-143- return;
arch/x86/include/asm/pgalloc.h:144: paravirt_alloc_p4d(mm, __pa(p4d) >> PAGE_SHIFT);
arch/x86/include/asm/pgalloc.h-145- set_pgd_safe(pgd, __pgd(_PAGE_TABLE | __pa(p4d)));
--
arch/x86/include/asm/pgtable.h=252=static inline u64 protnone_mask(u64 val);
arch/x86/include/asm/pgtable.h-253-
arch/x86/include/asm/pgtable.h:254:#define PFN_PTE_SHIFT PAGE_SHIFT
arch/x86/include/asm/pgtable.h-255-
arch/x86/include/asm/pgtable.h=256=static inline unsigned long pte_pfn(pte_t pte)
--
arch/x86/include/asm/pgtable.h-259- pfn ^= protnone_mask(pfn);
arch/x86/include/asm/pgtable.h:260: return (pfn & PTE_PFN_MASK) >> PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-261-}
--
arch/x86/include/asm/pgtable.h=263=static inline unsigned long pmd_pfn(pmd_t pmd)
--
arch/x86/include/asm/pgtable.h-266- pfn ^= protnone_mask(pfn);
arch/x86/include/asm/pgtable.h:267: return (pfn & pmd_pfn_mask(pmd)) >> PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-268-}
--
arch/x86/include/asm/pgtable.h=271=static inline unsigned long pud_pfn(pud_t pud)
--
arch/x86/include/asm/pgtable.h-274- pfn ^= protnone_mask(pfn);
arch/x86/include/asm/pgtable.h:275: return (pfn & pud_pfn_mask(pud)) >> PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-276-}
--
arch/x86/include/asm/pgtable.h=278=static inline unsigned long p4d_pfn(p4d_t p4d)
arch/x86/include/asm/pgtable.h-279-{
arch/x86/include/asm/pgtable.h:280: return (p4d_val(p4d) & p4d_pfn_mask(p4d)) >> PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-281-}
--
arch/x86/include/asm/pgtable.h=283=static inline unsigned long pgd_pfn(pgd_t pgd)
arch/x86/include/asm/pgtable.h-284-{
arch/x86/include/asm/pgtable.h:285: return (pgd_val(pgd) & PTE_PFN_MASK) >> PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-286-}
--
arch/x86/include/asm/pgtable.h=730=static inline pte_t pfn_pte(unsigned long page_nr, pgprot_t pgprot)
arch/x86/include/asm/pgtable.h-731-{
arch/x86/include/asm/pgtable.h:732: phys_addr_t pfn = (phys_addr_t)page_nr << PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-733- /* This bit combination is used to mark shadow stacks */
--
arch/x86/include/asm/pgtable.h=741=static inline pmd_t pfn_pmd(unsigned long page_nr, pgprot_t pgprot)
arch/x86/include/asm/pgtable.h-742-{
arch/x86/include/asm/pgtable.h:743: phys_addr_t pfn = (phys_addr_t)page_nr << PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-744- pfn ^= protnone_mask(pgprot_val(pgprot));
--
arch/x86/include/asm/pgtable.h=749=static inline pud_t pfn_pud(unsigned long page_nr, pgprot_t pgprot)
arch/x86/include/asm/pgtable.h-750-{
arch/x86/include/asm/pgtable.h:751: phys_addr_t pfn = (phys_addr_t)page_nr << PAGE_SHIFT;
arch/x86/include/asm/pgtable.h-752- pfn ^= protnone_mask(pgprot_val(pgprot));
--
arch/x86/include/asm/pgtable.h=1027=static inline unsigned long pages_to_mb(unsigned long npg)
arch/x86/include/asm/pgtable.h-1028-{
arch/x86/include/asm/pgtable.h:1029: return npg >> (20 - PAGE_SHIFT);
arch/x86/include/asm/pgtable.h-1030-}
--
arch/x86/include/asm/pgtable.h=1400=static inline bool pgdp_maps_userspace(void *__ptr)
--
arch/x86/include/asm/pgtable.h-1413- */
arch/x86/include/asm/pgtable.h:1414:#define PTI_PGTABLE_SWITCH_BIT PAGE_SHIFT
arch/x86/include/asm/pgtable.h-1415-
--
arch/x86/include/asm/pgtable.h=1479=static inline int page_level_shift(enum pg_level level)
arch/x86/include/asm/pgtable.h-1480-{
arch/x86/include/asm/pgtable.h:1481: return (PAGE_SHIFT - PTE_SHIFT) + level * PTE_SHIFT;
arch/x86/include/asm/pgtable.h-1482-}
--
arch/x86/include/asm/pgtable_32.h=42=do { \
--
arch/x86/include/asm/pgtable_32.h-71- */
arch/x86/include/asm/pgtable_32.h:72:#define LOWMEM_PAGES ((((_ULL(2)<<31) - __PAGE_OFFSET) >> PAGE_SHIFT))
arch/x86/include/asm/pgtable_32.h-73-
--
arch/x86/include/asm/processor.h=241=static inline unsigned long long l1tf_pfn_limit(void)
arch/x86/include/asm/processor.h-242-{
arch/x86/include/asm/processor.h:243: return BIT_ULL(boot_cpu_data.x86_cache_bits - 1 - PAGE_SHIFT);
arch/x86/include/asm/processor.h-244-}
--
arch/x86/include/asm/tlbflush.h=332=static inline bool mm_in_asid_transition(struct mm_struct *mm) { return false; }
--
arch/x86/include/asm/tlbflush.h-341- ? huge_page_shift(hstate_vma(vma)) \
arch/x86/include/asm/tlbflush.h:342: : PAGE_SHIFT, true)
arch/x86/include/asm/tlbflush.h-343-
--
arch/x86/include/asm/tlbflush.h=350=static inline void flush_tlb_page(struct vm_area_struct *vma, unsigned long a)
arch/x86/include/asm/tlbflush.h-351-{
arch/x86/include/asm/tlbflush.h:352: flush_tlb_mm_range(vma->vm_mm, a, a + PAGE_SIZE, PAGE_SHIFT, false);
arch/x86/include/asm/tlbflush.h-353-}
--
arch/x86/include/asm/vga.h-24- if (IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT)) \
arch/x86/include/asm/vga.h:25: set_memory_decrypted(start, (s) >> PAGE_SHIFT); \
arch/x86/include/asm/vga.h-26- \
--
arch/x86/include/asm/xen/page.h=298=static inline unsigned long virt_to_pfn(const void *v)
--
arch/x86/include/asm/xen/page.h-302-#define virt_to_mfn(v) (pfn_to_mfn(virt_to_pfn(v)))
arch/x86/include/asm/xen/page.h:303:#define mfn_to_virt(m) (__va(mfn_to_pfn(m) << PAGE_SHIFT))
arch/x86/include/asm/xen/page.h-304-
--
arch/x86/include/asm/xen/page.h-306-#define virt_to_gfn(v) (pfn_to_gfn(virt_to_pfn(v)))
arch/x86/include/asm/xen/page.h:307:#define gfn_to_virt(g) (__va(gfn_to_pfn(g) << PAGE_SHIFT))
arch/x86/include/asm/xen/page.h-308-
arch/x86/include/asm/xen/page.h=309=static inline unsigned long pte_mfn(pte_t pte)
arch/x86/include/asm/xen/page.h-310-{
arch/x86/include/asm/xen/page.h:311: return (pte.pte & XEN_PTE_MFN_MASK) >> PAGE_SHIFT;
arch/x86/include/asm/xen/page.h-312-}
--
arch/x86/include/asm/xen/page.h=314=static inline pte_t mfn_pte(unsigned long page_nr, pgprot_t pgprot)
--
arch/x86/include/asm/xen/page.h-317-
arch/x86/include/asm/xen/page.h:318: pte.pte = ((phys_addr_t)page_nr << PAGE_SHIFT) |
arch/x86/include/asm/xen/page.h-319- massage_pgprot(pgprot);
]
|
| 206/6 |
2026/09/09 17:18 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24755
output: 26
thoughts: 104
Thoughts: **Investigating the Origin of `CONFIG_PAGE_SHIFT`**
Okay, hold on a second. I need to figure out where `CONFIG_PAGE_SHIFT` is actually defined. My initial instinct is to check `arch/x86/include/asm/page_types.h`, that seems like the likely place for memory-related constants. Let's take a look. Ah, interesting, within that header, there's an include for `<vdso/page.h>`. Hmm, that suggests it *might* be defined there... or perhaps it's defined conditionally based on some other setting. Now I really need to get to the bottom of this. I'm going to have to do a proper search. The best way to get to the true source is to grep for all mentions of `CONFIG_PAGE_SHIFT` across the Kconfig files. That should reveal the configuration option that's setting it and, ultimately, where the value is assigned. That should provide the clarity I need.
|
| 207/6 |
2026/09/09 17:18 |
tool |
grepper |
0m
Error:
Args: map[Expression:CONFIG_PAGE_SHIFT PathPrefix:arch]
Results:
|
| 208/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 25111
output: 33
thoughts: 48
Thoughts: Okay, here's the summary of my thought process, tailored for an expert audience:
**Kernel Configuration Hunting**
Wait a second, I need to pinpoint the definition of `CONFIG_PAGE_SHIFT`. It's a key macro, and I know I need to track down its global definition across the kernel source. The best approach is a quick and dirty search. I'm going to leverage `grep` for a broad search. The target is the `PAGE_SHIFT` value, so I'll grep for that. Given that it's a fundamental architectural element, I'll start by checking the include files in `arch/x86/include/uapi/` and `include/` directories. These are the usual suspects for this kind of low-level configuration. I want to rapidly identify *where* `CONFIG_PAGE_SHIFT` is getting its value from a base `PAGE_SHIFT` definition.
|
| 209/6 |
2026/09/09 17:19 |
tool |
grepper |
0m
Error:
Args: map[Expression:PAGE_SHIFT PathPrefix:arch/x86/include/uapi]
Results:
|
| 210/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 25399
output: 19
thoughts: 19
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Grasping for Context: The `CONFIG_PAGE_SHIFT` Hunt**
Okay, hold on a second. Before I get too deep into this, I need to get a broader view. What's the context here? Let's take a step back and *grep* for `CONFIG_PAGE_SHIFT` across the entire codebase. This is a critical macro, and understanding where it's defined and used will illuminate the fundamental memory model assumptions in play. I need to get a lay of the land, understand the scope of how this is all interlinked before I move forward. This seems like a critical piece of information that will inform a lot more than my current line of thinking. It's time to get a good overview first. Let's see what emerges.
|
| 211/6 |
2026/09/09 17:19 |
tool |
grepper |
0m
Args: map[Expression:CONFIG_PAGE_SHIFT]
Results: map[Output:include/vdso/page.h-12- */
include/vdso/page.h:13:#define PAGE_SHIFT CONFIG_PAGE_SHIFT
include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
--
include/vdso/page.h-20- *
include/vdso/page.h:21: * Subtle: (1 << CONFIG_PAGE_SHIFT) is an int, not an unsigned long.
include/vdso/page.h-22- * So if we assign PAGE_MASK to a larger type it gets extended the
--
include/vdso/page.h-25- */
include/vdso/page.h:26:#define PAGE_MASK (~((1 << CONFIG_PAGE_SHIFT) - 1))
include/vdso/page.h-27-#else
--
scripts/gdb/linux/constants.py.in=150=if IS_BUILTIN(CONFIG_ARM64):
--
scripts/gdb/linux/constants.py.in-153- LX_VALUE(CONFIG_ARCH_FORCE_MAX_ORDER)
scripts/gdb/linux/constants.py.in:154:LX_VALUE(CONFIG_PAGE_SHIFT)
scripts/gdb/linux/constants.py.in-155-LX_CONFIG(CONFIG_SPARSEMEM)
--
scripts/gdb/linux/mm.py=34=class x86_page_ops():
--
scripts/gdb/linux/mm.py-36- self.struct_page_size = utils.get_page_type().sizeof
scripts/gdb/linux/mm.py:37: self.PAGE_SHIFT = constants.LX_CONFIG_PAGE_SHIFT
scripts/gdb/linux/mm.py-38- self.PAGE_SIZE = 1 << self.PAGE_SHIFT
--
scripts/gdb/linux/mm.py=203=class aarch64_page_ops():
--
scripts/gdb/linux/mm.py-214-
scripts/gdb/linux/mm.py:215: self.PAGE_SHIFT = constants.LX_CONFIG_PAGE_SHIFT
scripts/gdb/linux/mm.py-216- self.PAGE_SIZE = 1 << self.PAGE_SHIFT
]
|
| 212/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 26221
output: 27
thoughts: 65
Thoughts: **My Search for PAGE_SHIFT on x86**
Okay, hold on a second. I need to get this right. Where exactly is the `PAGE_SHIFT` macro defined for the x86 architecture? It's a fundamental value, so it should be easy to find. I was expecting it to be in the `arch/x86/include/asm/page_types.h` header, since that's where I usually find page-related definitions. But wait, it's not there! That's strange...
Alright, time to employ a more direct approach. Let's fire up a `grep` command. I'll search the entire repository for any instances of `#define` followed by `.*PAGE_SHIFT`. That should definitely turn up the definition, no matter where it's located. Then I can figure out why it's not where I originally expected it. Gotta love good ole grep!
|
| 213/6 |
2026/09/09 17:19 |
tool |
grepper |
0m
Args: map[Expression:#\s*define\s+PAGE_SHIFT\b]
Results: map[Output:arch/arc/include/uapi/asm/page.h-25- */
arch/arc/include/uapi/asm/page.h:26:#define PAGE_SHIFT 13
arch/arc/include/uapi/asm/page.h-27-#define PAGE_SIZE _BITUL(PAGE_SHIFT) /* Default 8K */
--
arch/powerpc/boot/page.h-15-/* PAGE_SHIFT determines the page size */
arch/powerpc/boot/page.h:16:#define PAGE_SHIFT 12
arch/powerpc/boot/page.h-17-#define PAGE_SIZE (ASM_CONST(1) << PAGE_SHIFT)
--
include/vdso/page.h-12- */
include/vdso/page.h:13:#define PAGE_SHIFT CONFIG_PAGE_SHIFT
include/vdso/page.h-14-
--
tools/include/linux/mm.h-8-
tools/include/linux/mm.h:9:#define PAGE_SHIFT 12
tools/include/linux/mm.h-10-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
--
tools/testing/scatterlist/linux/mm.h=11=typedef unsigned long dma_addr_t;
--
tools/testing/scatterlist/linux/mm.h-29-#define PAGE_SIZE (4096)
tools/testing/scatterlist/linux/mm.h:30:#define PAGE_SHIFT (12)
tools/testing/scatterlist/linux/mm.h-31-#define PAGE_MASK (~(PAGE_SIZE-1))
--
tools/testing/selftests/drivers/net/hw/ncdevmem.c-80-
tools/testing/selftests/drivers/net/hw/ncdevmem.c:81:#define PAGE_SHIFT 12
tools/testing/selftests/drivers/net/hw/ncdevmem.c-82-#define TEST_PREFIX "ncdevmem"
--
tools/testing/selftests/kvm/include/s390/processor.h-24-/* Page size definitions */
tools/testing/selftests/kvm/include/s390/processor.h:25:#define PAGE_SHIFT 12
tools/testing/selftests/kvm/include/s390/processor.h-26-#define PAGE_SIZE BIT_ULL(PAGE_SHIFT)
--
tools/testing/selftests/kvm/include/x86/processor.h=384=static inline unsigned int x86_model(unsigned int eax)
--
tools/testing/selftests/kvm/include/x86/processor.h-390-
tools/testing/selftests/kvm/include/x86/processor.h:391:#define PAGE_SHIFT 12
tools/testing/selftests/kvm/include/x86/processor.h-392-#define PAGE_SIZE (1ULL << PAGE_SHIFT)
--
tools/testing/shared/linux/kernel.h-21-#define schedule()
tools/testing/shared/linux/kernel.h:22:#define PAGE_SHIFT 12
tools/testing/shared/linux/kernel.h-23-
]
|
| 214/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 27316
output: 31
thoughts: 89
Thoughts: **Investigating the Kernel's Page Size Configuration**
Okay, so I'm looking into the `include/vdso/page.h` header file and I see these definitions:
```c
#define PAGE_SHIFT CONFIG_PAGE_SHIFT
#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
```
Pretty standard stuff for determining the page size, using the `CONFIG_PAGE_SHIFT` value. But hold on a second... where *exactly* is `CONFIG_PAGE_SHIFT` defined within the Kconfig system? I need to track this down for a deeper understanding. Time to start digging through the Kconfig files. I'll start with the obvious places – the `arch/`, `kernel/`, `mm/`, and `init/` directories – to find the Kconfig file that declares or assigns this configuration symbol. It could be in any of them, or possibly in a more specific architecture-related directory. Let's see if we can find where this important value is set.
|
| 215/6 |
2026/09/09 17:19 |
tool |
grepper |
0m
Error:
Args: map[Expression:PAGE_SHIFT PathPrefix:arch/x86/Kconfig]
Results:
|
| 216/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 27670
output: 18
thoughts: 16
Thoughts: Here's my thought process, summarized as you requested:
**Kconfig Exploration Begins**
Alright, time to get to work. My initial thought is to dive into the kernel configuration files. I want to understand how a specific macro is defined and used throughout the system. Specifically, I'm interested in how `PAGE_SHIFT` is handled. It's a fundamental constant, but I want to see how the various architectures and configurations define and use it. So, let's start with a comprehensive search. I'll reach for `grep`. I'll tell `grep` to hunt through all the `Kconfig` files – a broad starting point to see the general picture. This should give me a solid base to start investigating its impact on the system. I'm expecting this will produce a lot of output, but that's what I want for now: raw data to analyze.
|
| 217/6 |
2026/09/09 17:19 |
tool |
grepper |
0m
Args: map[Expression:config PAGE_SHIFT]
Results: map[Output:arch/Kconfig=1389=config PAGE_SIZE_LESS_THAN_256KB
--
arch/Kconfig-1392-
arch/Kconfig:1393:config PAGE_SHIFT
arch/Kconfig-1394- int
]
|
| 218/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 27967
output: 33
thoughts: 18
Thoughts: Okay, let's dive into this. Here's my take on those instructions, as if they're my internal thought process:
**Diving into the Kernel Configuration Landscape**
Right, so we're talking about kernel configuration, and specifically the `arch/Kconfig` file. That's the heart of the matter, the source code that drives the options we see in `make menuconfig` or `make config`. Let's zero in on line 1390. That area usually holds some crucial details, and to understand exactly what we are discussing, I will start by reading the code around line 1390. I will get my mental tools ready to deconstruct whatever configuration option, dependency, or block of code lives there, and place it in the context of my current mental map of the kernel's configuration mechanisms.
|
| 219/6 |
2026/09/09 17:19 |
tool |
read-file |
0m
Args: map[File:arch/Kconfig FirstLine:1385 LineCount:40]
Results: map[Contents:1385: def_bool y
1386: depends on !PAGE_SIZE_64KB
1387: depends on PAGE_SIZE_LESS_THAN_256KB
1388:
1389: config PAGE_SIZE_LESS_THAN_256KB
1390: def_bool y
1391: depends on !PAGE_SIZE_256KB
1392:
1393: config PAGE_SHIFT
1394: int
1395: default 12 if PAGE_SIZE_4KB
1396: default 13 if PAGE_SIZE_8KB
1397: default 14 if PAGE_SIZE_16KB
1398: default 15 if PAGE_SIZE_32KB
1399: default 16 if PAGE_SIZE_64KB
1400: default 18 if PAGE_SIZE_256KB
1401:
1402: # This allows to use a set of generic functions to determine mmap base
1403: # address by giving priority to top-down scheme only if the process
1404: # is not in legacy mode (compat task, unlimited stack size or
1405: # sysctl_legacy_va_layout).
1406: # Architecture that selects this option can provide its own version of:
1407: # - STACK_RND_MASK
1408: config ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT
1409: bool
1410: depends on MMU
1411: select ARCH_HAS_ELF_RANDOMIZE
1412:
1413: config HAVE_OBJTOOL
1414: bool
1415:
1416: config HAVE_JUMP_LABEL_HACK
1417: bool
1418:
1419: config HAVE_NOINSTR_HACK
1420: bool
1421:
1422: config HAVE_NOINSTR_VALIDATION
1423: bool
1424:
]
|
| 220/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 28761
output: 28
thoughts: 190
Thoughts: **My Analysis of PAGE_SIZE**
Okay, so I'm looking at `CONFIG_PAGE_SHIFT`, which, as I recall, is defined within `arch/Kconfig`. And, on x86_64, it's pretty standard that `PAGE_SIZE_4KB` is used, making `PAGE_SHIFT` equal to 12. Makes sense.
Now, the definition of `PAGE_SIZE` itself is something I've seen a million times:
```c
#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
```
Right, the `_AC(1,UL)` macro just expands to `1UL` in C, so `PAGE_SIZE` becomes `(1UL << 12)`. That calculates to `4096UL`, an `unsigned long`! Perfectly normal for a page size. I'm just quickly confirming the type here.
But, just to be thorough and because I'm thinking about it, I'm going to quickly double-check the git history. I want to see if this definition of `PAGE_SIZE` has always used `unsigned long`, or if there's been any significant commit that introduced or changed it. Just to be completely certain, I'll check `git blame` or `git log` on `include/vdso/page.h` just to be sure. It's always good practice to verify assumptions, even obvious ones.
|
| 221/6 |
2026/09/09 17:19 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:include/vdso/page.h]
Results: map[Output:763d1ebec843 vdso: Correct typo in PAGE_SHIFT comment
d4a65302dd84 vdso: Change PAGE_MASK to signed on all 32-bit architectures
efe8419ae78d vdso: Introduce vdso/page.h
]
|
| 222/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 29377
output: 24
thoughts: 16
Thoughts: Okay, here's my interpretation of that request, formatted as requested:
**Deconstructing Commit efe8419ae78d**
Alright, let's dive into commit efe8419ae78d. Immediately, my internal radar starts pinging. Just the commit hash alone tells me there's something specific the user wants my attention focused on. Without further context, I'm already formulating questions: What's the repository? What kind of project is this? What's the overall architecture? What’s the codebase's style? What tools are we using? I need to build a mental map before I even start to dissect the actual changes. I’m thinking, let's get a birds-eye view first; the usual suspects - the commit message, the changed files, any related tickets or pull requests. Then, I’ll start digging into the meat and potatoes. I expect I will want to see diffs. Hopefully they are clean. Hopefully there's a reason for every line. Let's see what we've got.
|
| 223/6 |
2026/09/09 17:19 |
tool |
git-show |
0m
Args:
Results: map[Output:commit efe8419ae78d65e83edc31aad74b605c12e7d60c
Author: Vincenzo Frascino <vincenzo.frascino@arm.com>
Date: Mon Oct 14 16:13:39 2024 +0100
vdso: Introduce vdso/page.h
The VDSO implementation includes headers from outside of the
vdso/ namespace.
Introduce vdso/page.h to make sure that the generic library
uses only the allowed namespace.
Signed-off-by: Vincenzo Frascino <vincenzo.frascino@arm.com>
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Reviewed-by: Arnd Bergmann <arnd@arndb.de>
Acked-by: Geert Uytterhoeven <geert@linux-m68k.org> # m68k
Link: https://lore.kernel.org/all/20241014151340.1639555-3-vincenzo.frascino@arm.com
diff --git a/arch/alpha/include/asm/page.h b/arch/alpha/include/asm/page.h
index 70419e6be1a3..261af54fd601 100644
--- a/arch/alpha/include/asm/page.h
+++ b/arch/alpha/include/asm/page.h
@@ -4,11 +4,7 @@
#include <linux/const.h>
#include <asm/pal.h>
-
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#ifndef __ASSEMBLY__
diff --git a/arch/arc/include/uapi/asm/page.h b/arch/arc/include/uapi/asm/page.h
index 7fd9e741b527..4606a326af5c 100644
--- a/arch/arc/include/uapi/asm/page.h
+++ b/arch/arc/include/uapi/asm/page.h
@@ -14,7 +14,7 @@
/* PAGE_SHIFT determines the page size */
#ifdef __KERNEL__
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
+#include <vdso/page.h>
#else
/*
* Default 8k
@@ -24,11 +24,10 @@
* not available
*/
#define PAGE_SHIFT 13
+#define PAGE_SIZE _BITUL(PAGE_SHIFT) /* Default 8K */
+#define PAGE_MASK (~(PAGE_SIZE-1))
#endif
-#define PAGE_SIZE _BITUL(PAGE_SHIFT) /* Default 8K */
#define PAGE_OFFSET _AC(0x80000000, UL) /* Kernel starts at 2G onwrds */
-#define PAGE_MASK (~(PAGE_SIZE-1))
-
#endif /* _UAPI__ASM_ARC_PAGE_H */
diff --git a/arch/arm/include/asm/page.h b/arch/arm/include/asm/page.h
index 62af9f7f9e96..ef11b721230e 100644
--- a/arch/arm/include/asm/page.h
+++ b/arch/arm/include/asm/page.h
@@ -7,10 +7,7 @@
#ifndef _ASMARM_PAGE_H
#define _ASMARM_PAGE_H
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)
-#define PAGE_MASK (~((1 << PAGE_SHIFT) - 1))
+#include <vdso/page.h>
#ifndef __ASSEMBLY__
diff --git a/arch/arm64/include/asm/page-def.h b/arch/arm64/include/asm/page-def.h
index 792e9fe881dc..d402e08442ee 100644
--- a/arch/arm64/include/asm/page-def.h
+++ b/arch/arm64/include/asm/page-def.h
@@ -10,9 +10,6 @@
#include <linux/const.h>
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#endif /* __ASM_PAGE_DEF_H */
diff --git a/arch/csky/include/asm/page.h b/arch/csky/include/asm/page.h
index 0ca6c408c07f..f8beae295afb 100644
--- a/arch/csky/include/asm/page.h
+++ b/arch/csky/include/asm/page.h
@@ -7,12 +7,8 @@
#include <asm/cache.h>
#include <linux/const.h>
-/*
- * PAGE_SHIFT determines the page size: 4KB
- */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE - 1))
+#include <vdso/page.h>
+
#define THREAD_SIZE (PAGE_SIZE * 2)
#define THREAD_MASK (~(THREAD_SIZE - 1))
#define THREAD_SHIFT (PAGE_SHIFT + 1)
diff --git a/arch/hexagon/include/asm/page.h b/arch/hexagon/include/asm/page.h
index 8a6af57274c2..b01f8df69dd4 100644
--- a/arch/hexagon/include/asm/page.h
+++ b/arch/hexagon/include/asm/page.h
@@ -45,9 +45,7 @@
#define HVM_HUGEPAGE_SIZE 0x5
#endif
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (1UL << PAGE_SHIFT)
-#define PAGE_MASK (~((1 << PAGE_SHIFT) - 1))
+#include <vdso/page.h>
#ifdef __KERNEL__
#ifndef __ASSEMBLY__
diff --git a/arch/loongarch/include/asm/page.h b/arch/loongarch/include/asm/page.h
index e85df33f11c7..83f3533e31a4 100644
--- a/arch/loongarch/include/asm/page.h
+++ b/arch/loongarch/include/asm/page.h
@@ -8,12 +8,7 @@
#include <linux/const.h>
#include <asm/addrspace.h>
-/*
- * PAGE_SHIFT determines the page size
- */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE - 1))
+#include <vdso/page.h>
#define HPAGE_SHIFT (PAGE_SHIFT + PAGE_SHIFT - 3)
#define HPAGE_SIZE (_AC(1, UL) << HPAGE_SHIFT)
diff --git a/arch/m68k/include/asm/page.h b/arch/m68k/include/asm/page.h
index 8cfb84b49975..b173ba27d36f 100644
--- a/arch/m68k/include/asm/page.h
+++ b/arch/m68k/include/asm/page.h
@@ -6,10 +6,8 @@
#include <asm/setup.h>
#include <asm/page_offset.h>
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
+
#define PAGE_OFFSET (PAGE_OFFSET_RAW)
#ifndef __ASSEMBLY__
diff --git a/arch/microblaze/include/asm/page.h b/arch/microblaze/include/asm/page.h
index 8810f4f1c3b0..d1ec3806edab 100644
--- a/arch/microblaze/include/asm/page.h
+++ b/arch/microblaze/include/asm/page.h
@@ -19,10 +19,7 @@
#ifdef __KERNEL__
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (ASM_CONST(1) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#define LOAD_OFFSET ASM_CONST((CONFIG_KERNEL_START-CONFIG_KERNEL_BASE_ADDR))
diff --git a/arch/mips/include/asm/page.h b/arch/mips/include/asm/page.h
index 4609cb0326cf..bc3e3484c1bf 100644
--- a/arch/mips/include/asm/page.h
+++ b/arch/mips/include/asm/page.h
@@ -14,12 +14,7 @@
#include <linux/kernel.h>
#include <asm/mipsregs.h>
-/*
- * PAGE_SHIFT determines the page size
- */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)
-#define PAGE_MASK (~((1 << PAGE_SHIFT) - 1))
+#include <vdso/page.h>
/*
* This is used for calculating the real page sizes
diff --git a/arch/nios2/include/asm/page.h b/arch/nios2/include/asm/page.h
index 0722f88e63cc..2897ec1b74f6 100644
--- a/arch/nios2/include/asm/page.h
+++ b/arch/nios2/include/asm/page.h
@@ -18,12 +18,7 @@
#include <linux/pfn.h>
#include <linux/const.h>
-/*
- * PAGE_SHIFT determines the page size
- */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE - 1))
+#include <vdso/page.h>
/*
* PAGE_OFFSET -- the first address of the first page of memory.
diff --git a/arch/openrisc/include/asm/page.h b/arch/openrisc/include/asm/page.h
index 1d5913f67c31..124a2db4b160 100644
--- a/arch/openrisc/include/asm/page.h
+++ b/arch/openrisc/include/asm/page.h
@@ -15,16 +15,7 @@
#ifndef __ASM_OPENRISC_PAGE_H
#define __ASM_OPENRISC_PAGE_H
-
-/* PAGE_SHIFT determines the page size */
-
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#ifdef __ASSEMBLY__
-#define PAGE_SIZE (1 << PAGE_SHIFT)
-#else
-#define PAGE_SIZE (1UL << PAGE_SHIFT)
-#endif
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#define PAGE_OFFSET 0xc0000000
#define KERNELBASE PAGE_OFFSET
diff --git a/arch/parisc/include/asm/page.h b/arch/parisc/include/asm/page.h
index 4bea2e95798f..6c4836fb5407 100644
--- a/arch/parisc/include/asm/page.h
+++ b/arch/parisc/include/asm/page.h
@@ -4,9 +4,7 @@
#include <linux/const.h>
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#define HAVE_ARCH_HUGETLB_UNMAPPED_AREA
diff --git a/arch/powerpc/include/asm/page.h b/arch/powerpc/include/asm/page.h
index 83d0a4fc5f75..af9a2628d1df 100644
--- a/arch/powerpc/include/asm/page.h
+++ b/arch/powerpc/include/asm/page.h
@@ -21,8 +21,7 @@
* page size. When using 64K pages however, whether we are really supporting
* 64K pages in HW or not is irrelevant to those definitions.
*/
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (ASM_CONST(1) << PAGE_SHIFT)
+#include <vdso/page.h>
#ifndef __ASSEMBLY__
#ifndef CONFIG_HUGETLB_PAGE
@@ -41,13 +40,6 @@ extern unsigned int hpage_shift;
#define HUGE_MAX_HSTATE (MMU_PAGE_COUNT-1)
#endif
-/*
- * Subtle: (1 << PAGE_SHIFT) is an int, not an unsigned long. So if we
- * assign PAGE_MASK to a larger type it gets extended the way we want
- * (i.e. with 1s in the high bits)
- */
-#define PAGE_MASK (~((1 << PAGE_SHIFT) - 1))
-
/*
* KERNELBASE is the virtual address of the start of the kernel, it's often
* the same as PAGE_OFFSET, but _might not be_.
diff --git a/arch/riscv/include/asm/page.h b/arch/riscv/include/asm/page.h
index 32d308a3355f..9875399827c7 100644
--- a/arch/riscv/include/asm/page.h
+++ b/arch/riscv/include/asm/page.h
@@ -12,9 +12,7 @@
#include <linux/pfn.h>
#include <linux/const.h>
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE - 1))
+#include <vdso/page.h>
#define HPAGE_SHIFT PMD_SHIFT
#define HPAGE_SIZE (_AC(1, UL) << HPAGE_SHIFT)
diff --git a/arch/s390/include/asm/page.h b/arch/s390/include/asm/page.h
index 73e1e03317b4..dbc25dc5fa0a 100644
--- a/arch/s390/include/asm/page.h
+++ b/arch/s390/include/asm/page.h
@@ -11,14 +11,11 @@
#include <linux/const.h>
#include <asm/types.h>
-#define _PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define _PAGE_SIZE (_AC(1, UL) << _PAGE_SHIFT)
-#define _PAGE_MASK (~(_PAGE_SIZE - 1))
-
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT _PAGE_SHIFT
-#define PAGE_SIZE _PAGE_SIZE
-#define PAGE_MASK _PAGE_MASK
+#include <vdso/page.h>
+
+#define _PAGE_SHIFT PAGE_SHIFT
+#define _PAGE_SIZE PAGE_SIZE
+#define _PAGE_MASK PAGE_MASK
#define PAGE_DEFAULT_ACC _AC(0, UL)
/* storage-protection override */
#define PAGE_SPO_ACC 9
diff --git a/arch/sh/include/asm/page.h b/arch/sh/include/asm/page.h
index f780b467e75d..fc39b8171bfb 100644
--- a/arch/sh/include/asm/page.h
+++ b/arch/sh/include/asm/page.h
@@ -8,10 +8,8 @@
#include <linux/const.h>
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
+
#define PTE_MASK PAGE_MASK
#if defined(CONFIG_HUGETLB_PAGE_SIZE_64K)
diff --git a/arch/sparc/include/asm/page_32.h b/arch/sparc/include/asm/page_32.h
index 9977c77374cd..9954254ea569 100644
--- a/arch/sparc/include/asm/page_32.h
+++ b/arch/sparc/include/asm/page_32.h
@@ -11,9 +11,7 @@
#include <linux/const.h>
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#ifndef __ASSEMBLY__
diff --git a/arch/sparc/include/asm/page_64.h b/arch/sparc/include/asm/page_64.h
index e9bd24821c93..2a68ff5b6eab 100644
--- a/arch/sparc/include/asm/page_64.h
+++ b/arch/sparc/include/asm/page_64.h
@@ -4,9 +4,7 @@
#include <linux/const.h>
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
/* Flushing for D-cache alias handling is only needed if
* the page size is smaller than 16K.
diff --git a/arch/um/include/asm/page.h b/arch/um/include/asm/page.h
index 9ef9a8aedfa6..834313ecd3d6 100644
--- a/arch/um/include/asm/page.h
+++ b/arch/um/include/asm/page.h
@@ -9,10 +9,7 @@
#include <linux/const.h>
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1, UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#ifndef __ASSEMBLY__
diff --git a/arch/x86/include/asm/page_types.h b/arch/x86/include/asm/page_types.h
index 52f1b4ff0cc1..974688973cf6 100644
--- a/arch/x86/include/asm/page_types.h
+++ b/arch/x86/include/asm/page_types.h
@@ -6,10 +6,7 @@
#include <linux/types.h>
#include <linux/mem_encrypt.h>
-/* PAGE_SHIFT determines the page size */
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#define __VIRTUAL_MASK ((1UL << __VIRTUAL_MASK_SHIFT) - 1)
diff --git a/arch/xtensa/include/asm/page.h b/arch/xtensa/include/asm/page.h
index 4db56ef052d2..595c1037b738 100644
--- a/arch/xtensa/include/asm/page.h
+++ b/arch/xtensa/include/asm/page.h
@@ -18,13 +18,7 @@
#include <asm/cache.h>
#include <asm/kmem_layout.h>
-/*
- * PAGE_SHIFT determines the page size
- */
-
-#define PAGE_SHIFT CONFIG_PAGE_SHIFT
-#define PAGE_SIZE (__XTENSA_UL_CONST(1) << PAGE_SHIFT)
-#define PAGE_MASK (~(PAGE_SIZE-1))
+#include <vdso/page.h>
#ifdef CONFIG_MMU
#define PAGE_OFFSET XCHAL_KSEG_CACHED_VADDR
diff --git a/include/vdso/page.h b/include/vdso/page.h
new file mode 100644
index 000000000000..4ada1ba6bd1f
--- /dev/null
+++ b/include/vdso/page.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __VDSO_PAGE_H
+#define __VDSO_PAGE_H
+
+#include <uapi/linux/const.h>
+
+/*
+ * PAGE_SHIFT determines the page size.
+ *
+ * Note: This definition is required because PAGE_SHIFT is used
+ * in several places throuout the codebase.
+ */
+#define PAGE_SHIFT CONFIG_PAGE_SHIFT
+
+#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
+
+#if defined(CONFIG_PHYS_ADDR_T_64BIT) && !defined(CONFIG_64BIT)
+/*
+ * Applies only to 32-bit architectures with a 64-bit phys_addr_t.
+ *
+ * Subtle: (1 << CONFIG_PAGE_SHIFT) is an int, not an unsigned long.
+ * So if we assign PAGE_MASK to a larger type it gets extended the
+ * way we want (i.e. with 1s in the high bits)
+ */
+#define PAGE_MASK (~((1 << CONFIG_PAGE_SHIFT) - 1))
+#else
+#define PAGE_MASK (~(PAGE_SIZE - 1))
+#endif
+
+#endif /* __VDSO_PAGE_H */
]
|
| 224/6 |
2026/09/09 17:19 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 35675
output: 32
thoughts: 1840
Thoughts: **Analyzing the x86_64 Kernel's PAGE_SIZE Comparison**
Okay, let's break this down systematically. I see the question centers around a comparison between a signed integer (`int num = -1;`) and `PAGE_SIZE` within the x86_64 Linux kernel. The recent commit, efe8419ae78d, modified the `PAGE_SIZE` definition, so let's check its definition: `PAGE_SIZE` is now defined as `(_AC(1,UL) << CONFIG_PAGE_SHIFT)` which expands to `(1UL << CONFIG_PAGE_SHIFT)`. On x86_64, `CONFIG_PAGE_SHIFT` is 12, so `PAGE_SIZE` ultimately is `4096UL` (an unsigned long).
Now, the core of the matter: `if (num < PAGE_SIZE)`. I need to rigorously apply the C standard's "Usual Arithmetic Conversions." First, I've got a signed `int` (`num = -1`) and an unsigned `long` (`PAGE_SIZE`). Integer promotions won't change them, so now comes the crucial part: the comparison. The C standard dictates that when comparing a signed integer and an unsigned integer, the signed operand is converted to the type of the unsigned operand, if the unsigned type has greater or equal rank. `unsigned long` has greater rank than `int` on x86_64 (LP64). Therefore, `num` (-1) gets *implicitly* converted to `unsigned long`. That's key!
Next, the conversion! When you convert -1 to an unsigned long (64 bits), the result, using two's complement, is `ULONG_MAX` which is `0xFFFFFFFFFFFFFFFFUL` or `18446744073709551615UL`. A massive value!
So, the comparison becomes: is `0xFFFFFFFFFFFFFFFFUL` (or `ULONG_MAX`) less than `4096UL`? Absolutely not. This comparison will evaluate to false (0).
This means the `if` statement's body will *not* be executed. It's a classic example of how signed-unsigned comparisons in C can trip you up. In fact, this pattern is a well-known source of potential kernel bugs, particularly when dealing with memory sizes and offsets. I need to be *extremely* careful here to make sure I've got the data types and the conversions correct, or I could introduce subtle, hard-to-find errors. I should double check all assumptions about the compiler, target architecture, and kernel configuration.
Let me confirm that I haven't overlooked any details specific to kernel development. Let's make sure the definition and expansion of `PAGE_SIZE` are what I expect, checking the `include/vdso/page.h`, `include/uapi/linux/const.h` and the architecture (x86_64) using the LP64 data model. I'll need to remember that this *is* a 64-bit architecture, which means `long` is 64 bits and `int` is 32 bits. Ok, yes, I confirm. `PAGE_SIZE` is, indeed, defined as described, and the implicit conversion to `unsigned long` on comparison holds. The answer is definitely `false`.
I should probably do a quick git log search for related issues or documentation on signed/unsigned integer comparisons with `PAGE_SIZE` in the kernel. This pattern is likely to have been the cause of bugs in the past, and there might be relevant warnings or best practices somewhere in the codebase.
|
| 225/6 |
2026/09/09 17:20 |
tool |
git-log |
0m
Args: map[Count:5 MessageRegexps:[PAGE_SIZE unsigned negative]]
Results: map[Output:0f5bb0cfb0b4 fs: use min() or umin() instead of min_t()
8f70caad82e9 powerpc/pseries/iommu: IOMMU incorrectly marks MMIO range in DDW
a79390f5d6a7 mm/mprotect: use long for page accountings and retval
7288ff6ec795 mptcp: fix fwd memory accounting on coalesce
722d94847de2 vfs: fs_context: fix up param length parsing in legacy_parse_param
]
|
| 226/6 |
2026/09/09 17:20 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 38501
output: 26
thoughts: 27
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm already deep in the weeds of this problem:
**Immediate Dive into a Specific Commit for Context**
Right, so this sounds like a familiar pattern. I've got a hunch about what's going on, but I need a concrete example to ground my thinking. Let's pull up commit `722d94847de2`. I'm going to look at that one specifically because it seems like it's a perfect match for the problem at hand. Grabbing a concrete example often quickly clarifies the situation in these sorts of cases! By looking at that commit, I expect to see the tell-tale signs that support my initial assumptions, or perhaps offer a helpful change in perspective as I dive in.
|
| 227/6 |
2026/09/09 17:20 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 722d94847de29310e8aa03fcbdb41fc92c521756
Author: Jamie Hill-Daniel <jamie@hill-daniel.co.uk>
Date: Tue Jan 18 08:06:04 2022 +0100
vfs: fs_context: fix up param length parsing in legacy_parse_param
The "PAGE_SIZE - 2 - size" calculation in legacy_parse_param() is an
unsigned type so a large value of "size" results in a high positive
value instead of a negative value as expected. Fix this by getting rid
of the subtraction.
Signed-off-by: Jamie Hill-Daniel <jamie@hill-daniel.co.uk>
Signed-off-by: William Liu <willsroot@protonmail.com>
Tested-by: Salvatore Bonaccorso <carnil@debian.org>
Tested-by: Thadeu Lima de Souza Cascardo <cascardo@canonical.com>
Acked-by: Dan Carpenter <dan.carpenter@oracle.com>
Acked-by: Al Viro <viro@zeniv.linux.org.uk>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
diff --git a/fs/fs_context.c b/fs/fs_context.c
index b7e43a780a62..24ce12f0db32 100644
--- a/fs/fs_context.c
+++ b/fs/fs_context.c
@@ -548,7 +548,7 @@ static int legacy_parse_param(struct fs_context *fc, struct fs_parameter *param)
param->key);
}
- if (len > PAGE_SIZE - 2 - size)
+ if (size + len + 2 > PAGE_SIZE)
return invalf(fc, "VFS: Legacy: Cumulative options too large");
if (strchr(param->key, ',') ||
(param->type == fs_value_is_string &&
]
|
| 228/6 |
2026/09/09 17:20 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 39290
output: 25
thoughts: 19
Thoughts: Here's a summary of my thinking, presented as if it were your own expert internal dialogue:
**Examining Commit 0f5bb0cfb0b4**
Alright, before diving too deep, I need to take a look at commit `0f5bb0cfb0b4`. It's crucial to understand the context and potential impact of that specific revision. Given my deep knowledge of the system, I know there's a reason to flag that commit for review, probably related to a recent bug report or change request, and a rapid assessment of what it changed is in order. Let's start with a diff and see what's what.
|
| 229/6 |
2026/09/09 17:20 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 0f5bb0cfb0b40a31d2fe146ecbef5727690fa547
Author: David Laight <david.laight.linux@gmail.com>
Date: Wed Nov 19 22:41:26 2025 +0000
fs: use min() or umin() instead of min_t()
min_t(unsigned int, a, b) casts an 'unsigned long' to 'unsigned int'.
Use min(a, b) instead as it promotes any 'unsigned int' to 'unsigned long'
and so cannot discard significant bits.
A couple of places need umin() because of loops like:
nfolios = DIV_ROUND_UP(ret + start, PAGE_SIZE);
for (i = 0; i < nfolios; i++) {
struct folio *folio = page_folio(pages[i]);
...
unsigned int len = umin(ret, PAGE_SIZE - start);
...
ret -= len;
...
}
where the compiler doesn't track things well enough to know that
'ret' is never negative.
The alternate loop:
for (i = 0; ret > 0; i++) {
struct folio *folio = page_folio(pages[i]);
...
unsigned int len = min(ret, PAGE_SIZE - start);
...
ret -= len;
...
}
would be equivalent and doesn't need 'nfolios'.
Most of the 'unsigned long' actually come from PAGE_SIZE.
Detected by an extra check added to min_t().
Signed-off-by: David Laight <david.laight.linux@gmail.com>
Link: https://patch.msgid.link/20251119224140.8616-31-david.laight.linux@gmail.com
Signed-off-by: Christian Brauner <brauner@kernel.org>
diff --git a/fs/buffer.c b/fs/buffer.c
index 838c0c571022..c6f4660f92df 100644
--- a/fs/buffer.c
+++ b/fs/buffer.c
@@ -2354,7 +2354,7 @@ bool block_is_partially_uptodate(struct folio *folio, size_t from, size_t count)
if (!head)
return false;
blocksize = head->b_size;
- to = min_t(unsigned, folio_size(folio) - from, count);
+ to = min(folio_size(folio) - from, count);
to = from + to;
if (from < blocksize && to > folio_size(folio) - blocksize)
return false;
diff --git a/fs/exec.c b/fs/exec.c
index 9d5ebc9d15b0..d0606e53376f 100644
--- a/fs/exec.c
+++ b/fs/exec.c
@@ -555,7 +555,7 @@ int copy_string_kernel(const char *arg, struct linux_binprm *bprm)
return -E2BIG;
while (len > 0) {
- unsigned int bytes_to_copy = min_t(unsigned int, len,
+ unsigned int bytes_to_copy = min(len,
min_not_zero(offset_in_page(pos), PAGE_SIZE));
struct page *page;
diff --git a/fs/ext4/mballoc.c b/fs/ext4/mballoc.c
index 56d50fd3310b..e817a758801d 100644
--- a/fs/ext4/mballoc.c
+++ b/fs/ext4/mballoc.c
@@ -4276,8 +4276,7 @@ void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
* get the corresponding group metadata to work with.
* For this we have goto again loop.
*/
- thisgrp_len = min_t(unsigned int, (unsigned int)len,
- EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
+ thisgrp_len = min(len, EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
clen = EXT4_NUM_B2C(sbi, thisgrp_len);
if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
diff --git a/fs/ext4/resize.c b/fs/ext4/resize.c
index 050f26168d97..76842f0957b5 100644
--- a/fs/ext4/resize.c
+++ b/fs/ext4/resize.c
@@ -1479,7 +1479,7 @@ static void ext4_update_super(struct super_block *sb,
/* Update the global fs size fields */
sbi->s_groups_count += flex_gd->count;
- sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
+ sbi->s_blockfile_groups = min(sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
/* Update the reserved block counts only once the new group is
diff --git a/fs/ext4/super.c b/fs/ext4/super.c
index 87205660c5d0..79762c3e0dff 100644
--- a/fs/ext4/super.c
+++ b/fs/ext4/super.c
@@ -4832,7 +4832,7 @@ static int ext4_check_geometry(struct super_block *sb,
return -EINVAL;
}
sbi->s_groups_count = blocks_count;
- sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
+ sbi->s_blockfile_groups = min(sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
if (((u64)sbi->s_groups_count * sbi->s_inodes_per_group) !=
le32_to_cpu(es->s_inodes_count)) {
diff --git a/fs/fat/dir.c b/fs/fat/dir.c
index 92b091783966..8375e7fbc1a5 100644
--- a/fs/fat/dir.c
+++ b/fs/fat/dir.c
@@ -1353,7 +1353,7 @@ int fat_add_entries(struct inode *dir, void *slots, int nr_slots,
/* Fill the long name slots. */
for (i = 0; i < long_bhs; i++) {
- int copy = min_t(int, sb->s_blocksize - offset, size);
+ int copy = umin(sb->s_blocksize - offset, size);
memcpy(bhs[i]->b_data + offset, slots, copy);
mark_buffer_dirty_inode(bhs[i], dir);
offset = 0;
@@ -1364,7 +1364,7 @@ int fat_add_entries(struct inode *dir, void *slots, int nr_slots,
err = fat_sync_bhs(bhs, long_bhs);
if (!err && i < nr_bhs) {
/* Fill the short name slot. */
- int copy = min_t(int, sb->s_blocksize - offset, size);
+ int copy = umin(sb->s_blocksize - offset, size);
memcpy(bhs[i]->b_data + offset, slots, copy);
mark_buffer_dirty_inode(bhs[i], dir);
if (IS_DIRSYNC(dir))
diff --git a/fs/fat/file.c b/fs/fat/file.c
index 4fc49a614fb8..f48435e586c7 100644
--- a/fs/fat/file.c
+++ b/fs/fat/file.c
@@ -140,8 +140,7 @@ static int fat_ioctl_fitrim(struct inode *inode, unsigned long arg)
if (copy_from_user(&range, user_range, sizeof(range)))
return -EFAULT;
- range.minlen = max_t(unsigned int, range.minlen,
- bdev_discard_granularity(sb->s_bdev));
+ range.minlen = max(range.minlen, bdev_discard_granularity(sb->s_bdev));
err = fat_trim_fs(inode, &range);
if (err < 0)
diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c
index 6d59cbc877c6..a30c8b57d478 100644
--- a/fs/fuse/dev.c
+++ b/fs/fuse/dev.c
@@ -1813,7 +1813,7 @@ static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
goto out_iput;
folio_offset = ((index - folio->index) << PAGE_SHIFT) + offset;
- nr_bytes = min_t(unsigned, num, folio_size(folio) - folio_offset);
+ nr_bytes = min(num, folio_size(folio) - folio_offset);
nr_pages = (offset + nr_bytes + PAGE_SIZE - 1) >> PAGE_SHIFT;
err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes, 0);
diff --git a/fs/fuse/file.c b/fs/fuse/file.c
index 01bc894e9c2b..4f71eb5a9bac 100644
--- a/fs/fuse/file.c
+++ b/fs/fuse/file.c
@@ -1323,10 +1323,8 @@ static ssize_t fuse_fill_write_pages(struct fuse_io_args *ia,
static inline unsigned int fuse_wr_pages(loff_t pos, size_t len,
unsigned int max_pages)
{
- return min_t(unsigned int,
- ((pos + len - 1) >> PAGE_SHIFT) -
- (pos >> PAGE_SHIFT) + 1,
- max_pages);
+ return min(((pos + len - 1) >> PAGE_SHIFT) - (pos >> PAGE_SHIFT) + 1,
+ max_pages);
}
static ssize_t fuse_perform_write(struct kiocb *iocb, struct iov_iter *ii)
@@ -1607,7 +1605,7 @@ static int fuse_get_user_pages(struct fuse_args_pages *ap, struct iov_iter *ii,
struct folio *folio = page_folio(pages[i]);
unsigned int offset = start +
(folio_page_idx(folio, pages[i]) << PAGE_SHIFT);
- unsigned int len = min_t(unsigned int, ret, PAGE_SIZE - start);
+ unsigned int len = umin(ret, PAGE_SIZE - start);
ap->descs[ap->num_folios].offset = offset;
ap->descs[ap->num_folios].length = len;
diff --git a/fs/splice.c b/fs/splice.c
index d338fe56b50b..5fb07c01936f 100644
--- a/fs/splice.c
+++ b/fs/splice.c
@@ -1467,7 +1467,7 @@ static ssize_t iter_to_pipe(struct iov_iter *from,
n = DIV_ROUND_UP(left + start, PAGE_SIZE);
for (i = 0; i < n; i++) {
- int size = min_t(int, left, PAGE_SIZE - start);
+ int size = umin(left, PAGE_SIZE - start);
buf.page = pages[i];
buf.offset = start;
]
|
| 230/6 |
2026/09/09 17:20 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 42762
output: 569
thoughts: 937
Thoughts: **Analyzing the x86_64 Kernel Code**
Okay, let's break this down meticulously. The question is straightforward: given `int num = -1;` in C within the x86_64 Linux kernel, what does `if (num < PAGE_SIZE)` evaluate to, and does type conversion occur?
My initial thought is that the condition will evaluate to false. Let's dig deeper:
1. **Evaluation Result:** The expression `num < PAGE_SIZE` definitely evaluates to `0` (false). No doubt about that.
2. **Type Conversion:** Yes, `num` undergoes an important type conversion. `PAGE_SIZE` is defined as `(_AC(1,UL) << CONFIG_PAGE_SHIFT)` which ultimately resolves to `4096UL`, an `unsigned long` on x86\_64 because `CONFIG_PAGE_SHIFT` is 12. Since we are in the LP64 data model, `num` is a 32-bit signed integer (`int`), and `PAGE_SIZE` is a 64-bit unsigned integer (`unsigned long`).
The C standard (specifically the Usual Arithmetic Conversions, C99/C11/C17 §6.3.1.8) dictates that when comparing a signed integer with an unsigned integer, the signed integer gets converted to the unsigned type if the unsigned type has greater or equal rank. Clearly, an `unsigned long` has a higher rank than an `int`. Thus, `-1` (an `int`) is converted to an `unsigned long`.
This conversion is the critical part. When you convert the signed integer `-1` to an `unsigned long`, it becomes the maximum value representable by an `unsigned long`. This is because of the bit representation: -1 is represented as all bits set, and in two's complement, that translates directly to the maximum value of the unsigned type.
Therefore, the conversion of `-1` to `unsigned long` gives us `ULONG_MAX` or `0xFFFFFFFFFFFFFFFFUL` which is the maximum value for a 64-bit unsigned integer, roughly 18 quintillion.
The comparison, therefore, becomes `ULONG_MAX < 4096UL`. Since `ULONG_MAX` is significantly larger than `4096UL`, this evaluates to false (`0`).
Just to be absolutely sure and avoid a bug, let's sanity-check the kernel headers. `PAGE_SIZE` in the kernel is defined in `<asm/page.h>`, included via `<asm/page_types.h>` and ultimately in `<vdso/page.h>`. Within `<vdso/page.h>` it is defined as we expect, with `_AC(1,UL)` expanding to `1UL`. This confirms the calculation and the types.
Given all of this, the final answer is crystal clear. I'm ready to `set-results`.
|
| 231/6 |
2026/09/09 17:20 |
tool |
set-results |
0m
Args: map[Answer:In the Linux kernel on x86_64, the condition `if (num < PAGE_SIZE)` evaluates to **false (0)**, and **yes, `num` gets converted to `unsigned long`**.
### Detailed Explanation:
1. **Definition and Type of `PAGE_SIZE`:**
In the Linux kernel (defined in `include/vdso/page.h` via `arch/x86/include/asm/page_types.h`), `PAGE_SIZE` is defined as:
```c
#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
```
- In C code, `_AC(1, UL)` expands to `1UL` (defined in `include/uapi/linux/const.h`).
- On x86_64, `CONFIG_PAGE_SHIFT` is `12` (4 KB pages).
- Therefore, `PAGE_SIZE` expands to `(1UL << 12)`, which equals `4096UL`. Its type is **`unsigned long`**.
2. **Usual Arithmetic Conversions in C:**
- On x86_64 (LP64 data model), `int` is a 32-bit signed integer and `unsigned long` is a 64-bit unsigned integer.
- When evaluating the binary `<` operator between `int` and `unsigned long`, C's Usual Arithmetic Conversions (C11 §6.3.1.8) apply:
> *"if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type."*
- Because `unsigned long` has greater integer conversion rank than `int`, `num` is converted to **`unsigned long`**.
3. **Value Evaluation:**
- Converting `int` with value `-1` to `unsigned long` produces `ULONG_MAX` (`0xFFFFFFFFFFFFFFFFUL` or `18,446,744,073,709,551,615`).
- The expression evaluates as:
```c
18446744073709551615UL < 4096UL
```
- This comparison is **false** (`0`), so the body of the `if` statement is not executed.]
Results: map[Answer:In the Linux kernel on x86_64, the condition `if (num < PAGE_SIZE)` evaluates to **false (0)**, and **yes, `num` gets converted to `unsigned long`**.
### Detailed Explanation:
1. **Definition and Type of `PAGE_SIZE`:**
In the Linux kernel (defined in `include/vdso/page.h` via `arch/x86/include/asm/page_types.h`), `PAGE_SIZE` is defined as:
```c
#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
```
- In C code, `_AC(1, UL)` expands to `1UL` (defined in `include/uapi/linux/const.h`).
- On x86_64, `CONFIG_PAGE_SHIFT` is `12` (4 KB pages).
- Therefore, `PAGE_SIZE` expands to `(1UL << 12)`, which equals `4096UL`. Its type is **`unsigned long`**.
2. **Usual Arithmetic Conversions in C:**
- On x86_64 (LP64 data model), `int` is a 32-bit signed integer and `unsigned long` is a 64-bit unsigned integer.
- When evaluating the binary `<` operator between `int` and `unsigned long`, C's Usual Arithmetic Conversions (C11 §6.3.1.8) apply:
> *"if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type."*
- Because `unsigned long` has greater integer conversion rank than `int`, `num` is converted to **`unsigned long`**.
3. **Value Evaluation:**
- Converting `int` with value `-1` to `unsigned long` produces `ULONG_MAX` (`0xFFFFFFFFFFFFFFFFUL` or `18,446,744,073,709,551,615`).
- The expression evaluates as:
```c
18446744073709551615UL < 4096UL
```
- This comparison is **false** (`0`), so the body of the `if` statement is not executed.]
|
| 232/4 |
2026/09/09 17:20 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 33927
output: 31
thoughts: 1397
Thoughts: **A Deep Dive into `scatter_elem_sz` and a Potential Kernel Vulnerability**
Okay, this is a critical issue I've uncovered. It seems the check `num < PAGE_SIZE` in the `sg_build_indirect` function is flawed, especially when `num` is negative. My first reaction is: this needs immediate attention. If `num` is, say, `-1`, the check evaluates to `FALSE` due to integer wrapping with an unsigned comparison. This means the subsequent logic in `sg_build_indirect` could be triggered with an unexpected value.
Looking at the code, `scatter_elem_sz` can be set at module load through module parameters. The `module_param_named` macro is the key. If a negative value is passed to `scatter_elem_sz` (e.g., `-1` on the command line or via sysfs), then `scatter_elem_sz < PAGE_SIZE` is incorrectly evaluated as `FALSE` in that context. The `sg_build_indirect` function is then invoked with `num` which equals `scatter_elem_sz` therefore it is negative and not correctly handled.
This causes a serious problem because `order = get_order(num)` is called. If `num` is negative, `(unsigned long)num` becomes a huge positive number. That messes up the following calculations involving `order`, `ret_sz`, and `rem_sz` and could potentially lead to memory corruption or out-of-bounds access. Even if `min_t(int, order, MAX_PAGE_ORDER)` is applied, we are in trouble.
My initial thoughts are, can we change the check to `if (num <= 0 || num < PAGE_SIZE)` or `if (num < (int)PAGE_SIZE)`? That should fix the issue for negative numbers and zero. The crucial question is, can we convert `scatter_elem_sz` to `uint`? If the module parameter is an `int`, sysfs accepts negative values! This is important for fixing the issue.
Let's look at how the module parameter is defined. It's declared as an `int`. Can user space or scripts pass negative values? Yes, because it is an `int`, it's possible. So, should we make it `uint`?
Before we change it, though, we need to consider if there's any existing code that *relies* on `scatter_elem_sz` being `int`. We should check the uses of `scatter_elem_sz` in `sg.c`, specifically `def_reserved_size` and `sg_allow_dio`, but the variable does not appear to be utilized there.
`SG_SCATTER_SZ` is defined as `8 * 4096`, which is 32768, that's important for the context of this issue.
Now, if we modify the check with `if (num < (int)PAGE_SIZE)`, if `num = -1`, then `-1 < 4096` evaluates to `TRUE`. If `num = 0`, then `0 < 4096` is also true. If `num = 4095`, then `4095 < 4096` is also correct.
Let's think about this: if we change the condition in `init_sg` to be `scatter_elem_sz < (int)PAGE_SIZE`, the kernel command line will handle negative numbers correctly (i.e., `sg.scatter_elem_sz=-1`). This fixes the problem completely.
Also, what if someone sets `scatter_elem_sz` to a really large value (e.g., a billion)? This also needs to be examined. After the `min_t` call, we need to know what `MAX_PAGE_ORDER` is in the running kernel so we understand the upper bound.
This is a critical vulnerability. We need to implement the change to `init_sg`, and the check in `sg_build_indirect`. And we must figure out the best approach to handling negative inputs in a controlled manner, and whether a `uint` is appropriate for `scatter_elem_sz`.
|
| 233/4 |
2026/09/09 17:20 |
tool |
grepper |
0m
Args: map[Expression:#define MAX_PAGE_ORDER\b PathPrefix:include/]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
]
|
| 234/4 |
2026/09/09 17:20 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 36385
output: 35
thoughts: 1908
Thoughts: **Deep Dive into `sg_build_indirect` and Page Order Calculations**
Okay, let's break this down. My initial thought process is centered around understanding how the `ret_sz` value is calculated within the `sg_build_indirect` function. It looks like `MAX_PAGE_ORDER` is typically 10, which leads me to deduce that `PAGE_SHIFT + order` will be at most `PAGE_SHIFT + MAX_PAGE_ORDER`. A concrete example, `12 + 10 = 22`. Given this, I'm calculating that `1 << 22` results in 4MB.
Now, I'm questioning the safety of this bit shift. Is `1 << (PAGE_SHIFT + order)` safe given the constraint `order <= MAX_PAGE_ORDER`? Let's assume that `PAGE_SHIFT` is at most 16, as seen on ARM64 or PPC for 64KB pages, and `MAX_PAGE_ORDER` is e.g. 10 or 11. Specifically, on a 64KB page size, `PAGE_SHIFT` is 16 and `MAX_PAGE_ORDER` can be 10, thus `16 + 10 = 26`, and `1 << 26` is 64MB. Since we're dealing with a 32-bit signed integer, `1 << 26` is a positive value and fits safely, as it's below the 30-bit limit without including the sign bit.
Next, I'm considering whether `PAGE_SHIFT + order` could reach 31, and what happens when `PAGE_SHIFT` is 16 and `MAX_PAGE_ORDER` is 15. The question prompts a reflection on alternative approaches, such as `1U << (PAGE_SHIFT + order)`, `(size_t)1 << ...`, or `PAGE_SIZE << order`. Noting that `PAGE_SIZE` is, fundamentally, `(1UL << PAGE_SHIFT)`, which means `PAGE_SIZE << order` is equivalent to `1UL << (PAGE_SHIFT + order)`.
Back to the `ret_sz` variable, which is an `int`. Now, I'm diving deeper into the `sg_build_indirect` function's source code, specifically the loop where `ret_sz` is used. I'm focusing on lines 1899-1904. It appears that `ret_sz`, calculated as `1 << (PAGE_SHIFT + order)`, is used to round up `scatter_elem_sz` in certain circumstances. For example, if `scatter_elem_sz` is 5000, then `order` becomes 1. Thus, `ret_sz` becomes 8192, and because `8192 > 5000`, the `scatter_elem_sz` gets rounded up to `ret_sz = 8192`. This aligns with the commit message, which mentions rounding up to the nearest power of two.
Now, let's explore a scenario where `scatter_elem_sz` is set to a large value, say, `1 << 25`. If `order > MAX_PAGE_ORDER`, the `min_t` constraint limits `order` to `MAX_PAGE_ORDER`. Consequently, `ret_sz` will be `1 << (PAGE_SHIFT + MAX_PAGE_ORDER)`. I am also examining the role of `scatter_elem_sz_prev`, thinking about the scenario where `num == scatter_elem_sz_prev`.
In the context of the `sg_build_indirect` function, if `scatter_elem_sz_prev` is 32MB and `blk_size` is 100MB, then `num` becomes 32MB. In this case, since `num == scatter_elem_sz_prev`, `ret_sz` would not be larger than `scatter_elem_sz_prev`, and the allocation size for the page element would align with `scatter_elem_sz_prev`. Therefore, we would see `alloc_pages(gfp_mask, order)` allocating 4MB per page element, and `rem_sz` decrementing by 4MB.
I'm now thinking about failure scenarios. When `alloc_pages` fails, and the function goes to `out:`, the code iterates back by decrementing the `order` and retries allocation at a lower order. The critical thing to note is that `ret_sz` is recalculated as `1 << (PAGE_SHIFT + order)`, effectively reducing the page size if the initial allocation failed, eventually leading to a retry with `
|
| 235/4 |
2026/09/09 17:20 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:25 LineCount:40]
Results: map[Contents: 25:
26: #include <linux/fs.h>
27: #include <linux/kernel.h>
28: #include <linux/sched.h>
29: #include <linux/string.h>
30: #include <linux/mm.h>
31: #include <linux/errno.h>
32: #include <linux/mtio.h>
33: #include <linux/ioctl.h>
34: #include <linux/major.h>
35: #include <linux/slab.h>
36: #include <linux/fcntl.h>
37: #include <linux/init.h>
38: #include <linux/poll.h>
39: #include <linux/moduleparam.h>
40: #include <linux/cdev.h>
41: #include <linux/idr.h>
42: #include <linux/seq_file.h>
43: #include <linux/blkdev.h>
44: #include <linux/delay.h>
45: #include <linux/blktrace_api.h>
46: #include <linux/mutex.h>
47: #include <linux/atomic.h>
48: #include <linux/ratelimit.h>
49: #include <linux/uio.h>
50: #include <linux/cred.h> /* for sg_check_file_access() */
51:
52: #include <scsi/scsi.h>
53: #include <scsi/scsi_cmnd.h>
54: #include <scsi/scsi_dbg.h>
55: #include <scsi/scsi_device.h>
56: #include <scsi/scsi_driver.h>
57: #include <scsi/scsi_eh.h>
58: #include <scsi/scsi_host.h>
59: #include <scsi/scsi_ioctl.h>
60: #include <scsi/scsi_tcq.h>
61: #include <scsi/sg.h>
62:
63: #include "scsi_logging.h"
64:
]
|
| 236/4 |
2026/09/09 17:20 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 39993
output: 30
thoughts: 70
Thoughts: **Investigating Potential `MAX_PAGE_ORDER` Usage in SCSI Drivers**
Okay, so I'm digging into this code, and it looks like `linux/mm.h` is being included on line 30. That's a good starting point. Knowing `mm.h` includes `mmzone.h`, or at least brings `MAX_PAGE_ORDER` in transitively, I immediately start thinking about how that might affect the SCSI drivers. My gut tells me that `MAX_PAGE_ORDER` could be relevant to how memory is managed, which is fundamental to I/O operations, particularly large block transfers which are common in SCSI. So, next step, I need to see if `MAX_PAGE_ORDER` actually shows up anywhere else in the `drivers/scsi/` directory. That'll be my primary focus. Time to check for its explicit or implicit use.
|
| 237/4 |
2026/09/09 17:21 |
tool |
grepper |
0m
Args: map[Expression:MAX_PAGE_ORDER PathPrefix:drivers/scsi/]
Results: map[Output:drivers/scsi/mpi3mr/mpi3mr_app.c=121=void mpi3mr_alloc_diag_bufs(struct mpi3mr_ioc *mrioc)
--
drivers/scsi/mpi3mr/mpi3mr_app.c-177- trace_size / 1024);
drivers/scsi/mpi3mr/mpi3mr_app.c:178: if ((!mrioc->seg_tb_support && (get_order(trace_size) > MAX_PAGE_ORDER)) ||
drivers/scsi/mpi3mr/mpi3mr_app.c-179- mpi3mr_alloc_trace_buffer(mrioc, trace_size)) {
--
drivers/scsi/mpi3mr/mpi3mr_app.c-197- if ((mrioc->facts.diag_fw_sz < fw_size) && (fw_size >= fw_min_size)) {
drivers/scsi/mpi3mr/mpi3mr_app.c:198: if (get_order(fw_size) <= MAX_PAGE_ORDER) {
drivers/scsi/mpi3mr/mpi3mr_app.c-199- diag_buffer->addr
]
|
| 238/4 |
2026/09/09 17:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 40597
output: 31
thoughts: 6949
Thoughts: **Analyzing SCSI Scatter/Gather Element Size and Potential Integer Overflow Vulnerabilities**
Okay, I'm diving into this `sg.c` code, specifically the `sg_build_indirect` function. It seems there's a potential issue with how we're handling `scatter_elem_sz`, which is used to define the size of scatter/gather elements. The primary concern revolves around the comparison `num < PAGE_SIZE` where `num` is a signed `int` and `PAGE_SIZE` is an `unsigned long`. This comparison can lead to unexpected behavior if `num` is negative, due to the implicit unsigned conversion in C. The code's behavior when a negative `scatter_elem_sz` is introduced is undefined, and results in incorrect `order` values, ultimately leading to potentially large allocations.
I'm seeing that the intended logic is that `scatter_elem_sz` should be the maximum of the provided size and `PAGE_SIZE`, always resulting in at least `PAGE_SIZE`. The code is supposed to round it up to the next power of 2.
The system's prompt highlights that similar coding mistakes are likely in other parts of the same file. So, I need to check for other instances of this signed/unsigned comparison issue, specifically, `scatter_elem_sz < PAGE_SIZE`.
I've examined the code and there are other similar places. The vulnerability exists at the `init_sg` initialization function too.
My proposed fix would be to consistently use a signed comparison in both `sg_build_indirect` and `init_sg`. Specifically, change `num < PAGE_SIZE` to `num < (int)PAGE_SIZE` in both functions. Additionally, in `sg_build_indirect`, I need to update `num` to `PAGE_SIZE` if the check returns true (before the `order` is calculated). I'll also clamp the `order` to `MAX_PAGE_ORDER`.
The goal is to ensure that negative values or values less than `PAGE_SIZE` are correctly handled during initialization and subsequent operations, which means setting `scatter_elem_sz` to a valid power of 2, preventing integer overflow during the calculation of allocation sizes, and ensuring the driver allocates memory within reasonable limits. This change is crucial for robustness and to prevent potential denial-of-service or memory corruption bugs.
|
| 239/4 |
2026/09/09 17:21 |
tool |
grepper |
0m
Args: map[Expression:\(int\)\s*PAGE_SIZE PathPrefix:drivers/]
Results: map[Output:drivers/infiniband/sw/siw/siw_qp_rx.c=29=static int siw_rx_umem(struct siw_rx_stream *srx, struct siw_umem *umem,
--
drivers/infiniband/sw/siw/siw_qp_rx.c-51- pg_off = dest_addr & ~PAGE_MASK;
drivers/infiniband/sw/siw/siw_qp_rx.c:52: bytes = min(len, (int)PAGE_SIZE - pg_off);
drivers/infiniband/sw/siw/siw_qp_rx.c-53-
--
drivers/infiniband/sw/siw/siw_qp_tx.c=437=static noinline_for_stack int siw_tx_hdt(struct siw_iwarp_tx *c_tx,
--
drivers/infiniband/sw/siw/siw_qp_tx.c-498- while (sge_len) {
drivers/infiniband/sw/siw/siw_qp_tx.c:499: size_t plen = min((int)PAGE_SIZE - fp_off, sge_len);
drivers/infiniband/sw/siw/siw_qp_tx.c-500- void *kaddr;
--
drivers/md/md-bitmap.c=558=static int read_file_page(struct file *file, unsigned long index,
--
drivers/md/md-bitmap.c-566-
drivers/md/md-bitmap.c:567: pr_debug("read bitmap file (%dB @ %llu)\n", (int)PAGE_SIZE,
drivers/md/md-bitmap.c-568- (unsigned long long)index << PAGE_SHIFT);
--
drivers/md/md-bitmap.c-613- pr_err("md: bitmap read error: (%dB @ %llu): %d\n",
drivers/md/md-bitmap.c:614: (int)PAGE_SIZE,
drivers/md/md-bitmap.c-615- (unsigned long long)index << PAGE_SHIFT,
]
|
| 240/4 |
2026/09/09 17:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 48640
output: 37
thoughts: 1659
Thoughts: **Analyzing Scatter Gather Element Size in `drivers/scsi/sg.c`**
Okay, let's revisit this area of the code. I need to be absolutely sure we haven't missed anything regarding `scatter_elem_sz` in `drivers/scsi/sg.c`. First, I see the declaration and initialization of `scatter_elem_sz` and `scatter_elem_sz_prev`, both set to `SG_SCATTER_SZ`. Then, I spot the `module_param_named` macro making it a module parameter, with a description indicating the default is `max(SG_SCATTER_SZ, PAGE_SIZE)`.
I quickly check the initialization logic: If `scatter_elem_sz` is less than `PAGE_SIZE`, it's forced to `PAGE_SIZE`, which seems correct and intended to prevent allocating overly small scatter gather elements.
Now, looking deeper, particularly around line 1876, I realize I need to consider what happens if `num` is negative after the update. Since `scatter_elem_sz` is an `int`, the comparison `num < (int)PAGE_SIZE` performs a *signed* comparison. A negative value for `num` would pass this check, which means it would be reset to `PAGE_SIZE`. This is the intended behavior and the code explicitly handles this.
Then, the thought hits me: should we consider making `scatter_elem_sz` an `unsigned int`? But no, a change to `uint` would mean that a user-provided value of -1 via sysfs would now result in an error, which could be an ABI break and possibly unexpected behavior. Stick with the current `int` and the safe handling of potential negative numbers.
Next, I need to check the potential for `order` to be negative. Let's look at `get_order(num)`. Since `num` is now at least `PAGE_SIZE`, I calculate `get_order(PAGE_SIZE)`. Given `PAGE_SIZE` is `1 << PAGE_SHIFT`, the math results in 0, so the returned `order` can't be negative. Then `min_t` will keep `order` between 0 and `MAX_PAGE_ORDER`. With the current values of `PAGE_SHIFT` and `MAX_PAGE_ORDER` (12 and 10 on x86), `PAGE_SHIFT + order` will range between 12 and 22, and the `ret_sz` calculation is safe and avoids overflow, so there is no issue here.
In the `for` loop, `alloc_pages` is called, and a retry mechanism is present if `alloc_pages` fails. The code decrements `order` (which is at least 0) and jumps back to the `retry` label if the allocation failed for the current order. This means a smaller order is tried until the order becomes -1. The function then correctly returns -ENOMEM.
Finally, I remember a past potential bug and want to confirm the free operation. The comment mentions a change from `__free_pages(schp->pages[k], order)` to `__free_pages(schp->pages[i], order)` - I must ensure that `__free_pages` is currently freeing the correct pages. I'll need to check the current line 1923 in the source code to confirm the correct index is used to free the allocated pages.
|
| 241/4 |
2026/09/09 17:21 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1921 LineCount:10]
Results: map[Contents:1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
]
|
| 242/4 |
2026/09/09 17:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 51206
output: 37
thoughts: 69
Thoughts: **Checking the `__free_pages` Fix**
Okay, so I remember that fix... `__free_pages(schp->pages[i], order);` was definitely the right move. Using `i` instead of `k` was a crucial bug squashing in an earlier commit. Always good to catch those pesky indexing errors!
Just to be absolutely certain and to see if there are any related issues, I'm going to run a `git log -S __free_pages` search within the `drivers/scsi/sg.c` directory. This should highlight all instances where `__free_pages` was touched, potentially revealing other related bugs or optimizations we might have missed or that got addressed. A quick scan of that log will give me a good picture of the history of this particular function in this driver and any potential gotchas. I like to be thorough, especially when dealing with memory management. It's too easy to miss something that causes a subtle, hard-to-debug problem later on.
|
| 243/4 |
2026/09/09 17:21 |
tool |
git-log |
0m
Args: map[CodeRegexp:__free_pages.*order PathPrefix:drivers/scsi/sg.c]
Results: map[Output:e71044ee2efa [SCSI] sg: fix oops in the error path in sg_build_indirect()
10db10d144c0 sg: convert the indirect IO path to use the block layer
d6b10348f939 [SCSI] convert sg to scsi_execute_async
]
|
| 244/4 |
2026/09/09 17:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 51618
output: 24
thoughts: 16
Thoughts: Okay, I'm ready to dive into that commit. Let's see what e71044ee2efa is all about.
**Analyzing Commit e71044ee2efa**
Alright, my expert eyes are on this commit. First, I need to understand the context. What problem was it trying to solve? What was the previous state of the code? Given the commit message and the files modified, my initial instinct is that this commit likely touches [briefly explain the likely area, e.g., the data access layer, a specific optimization, a security vulnerability, etc.]. I'm already formulating some hypotheses... is this refactoring, a bug fix, a feature addition, or something more fundamental?
Now, let's drill down. I'll need to examine the diffs methodically. I'm looking for the "meat" of the changes. Are there any significant algorithmic modifications? Any risky dependencies introduced? Any obvious performance bottlenecks? I'll pay close attention to the lines that were added and removed, comparing the before-and-after states to determine the intent and impact. I'll need to look for any hidden gotchas, potential regressions, or subtle side effects that may have been missed.
I'm checking for unit tests here. Are there tests to cover the new functionality or fixes? Hopefully, they are comprehensive and cover edge cases. I'll mentally run the tests myself and, if necessary, I'll locally build and test this.
Furthermore, I have to consider the overall architecture and how this change fits in. Does it align with the established design principles? Does it introduce any architectural debt? Are there any potential integration issues with other modules or services? I'm assessing the maintainability, scalability, and security implications.
Essentially, I'm checking if this commit adheres to best practices and the standards I expect for this system. And after all this, I am now in a position to give a precise evaluation of the change, and provide a constructive suggestion if need be.
|
| 245/4 |
2026/09/09 17:21 |
tool |
git-show |
0m
Args:
Results: map[Output:commit e71044ee2efa4792e21d243b03d49006db66aec9
Author: Michal Schmidt <mschmidt@redhat.com>
Date: Thu Sep 3 14:27:08 2009 +0200
[SCSI] sg: fix oops in the error path in sg_build_indirect()
When the allocation fails in sg_build_indirect(), an oops happens in
the error path. It's caused by an obvious typo.
Signed-off-by: Michal Schmidt <mschmidt@redhat.com>
Reported-by: Bob Tracy <rct@gherkin.frus.com>
Acked-by: Douglas Gilbert <dgilbert@interlog.com>
Cc: Stable Tree <stable@kernel.org>
Signed-off-by: James Bottomley <James.Bottomley@suse.de>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 9230402c45af..4968c4ced385 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1811,7 +1811,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
return 0;
out:
for (i = 0; i < k; i++)
- __free_pages(schp->pages[k], order);
+ __free_pages(schp->pages[i], order);
if (--order >= 0)
goto retry;
]
|
| 246/4 |
2026/09/09 17:21 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 52526
output: 23
thoughts: 3020
Thoughts: **Analyzing Scatterlist Element Size in `sg.c`**
Alright, let's dive back into `drivers/scsi/sg.c`, specifically around line 1876. I'm focusing on the logic that determines the size of scatterlist elements, `scatter_elem_sz`. My initial thought is to trace the flow, especially how `num` (which is assigned `scatter_elem_sz`) is handled. I noticed there's a check: `if (unlikely(num != scatter_elem_sz_prev))`, and a potential adjustment if `num` is less than `PAGE_SIZE`. The central question in my mind is: what happens if `num` is *already* a valid value, but the less-than-PAGE_SIZE check isn't triggered?
I'm starting to suspect there could be some subtle issues related to the unsigned nature of `PAGE_SIZE` and potential signed integer overflows or unexpected behavior, especially if a user-supplied value is negative or small.
In the original code, if `num` is zero, we trigger the conditional block. Here the value of `num` is not updated before the `get_order()` function, which will cause undefined behavior. The `ret_sz` value would be undefined, and a shift-out-of-bounds error is likely, with potential security implications. Adding `num = PAGE_SIZE;` fixes the undefined behavior, because the `order` is now properly computed using the page size.
It is particularly important to investigate what happens when `scatter_elem_sz` gets a negative value, and I see how it could cause a bug, where the `if (num < PAGE_SIZE)` would not trigger properly with signed/unsigned comparisons. The original code could have an unexpected behavior if `scatter_elem_sz` is initialized to -1. The fix ensures that such values are correctly handled, leading to allocation of pages of size `PAGE_SIZE` (order 0).
Now, what if a value between 0 and PAGE_SIZE is written? It gets correctly handled in both cases, which is good. What about values larger than `PAGE_SIZE << MAX_PAGE_ORDER`? The code correctly handles large values by applying `min_t` to limit the order to `MAX_PAGE_ORDER`, which is 4MB on x86_64. No overflow. All good.
I'm now focusing on `scatter_elem_sz_prev`. Is it capped too, or only `num`? In the loop, `num` is used for logging purposes. Does this matter for the overall behaviour? Also, there is a check `num == scatter_elem_sz_prev` to update `scatter_elem_sz`.
The proposed fix introduces `num = PAGE_SIZE;` inside the conditional block and another cap for the order: `order = min_t(int, order, MAX_PAGE_ORDER);`. This ensures the proper handling of small values. However, I want to clarify some details. Should we use the explicit cast to `(int)PAGE_SIZE`?
I also consider scenarios where `num` can be a negative number and how the code should handle them. `num` being signed becomes critical here. For example, if `num = -1`, the `num < PAGE_SIZE` check can behave unexpectedly, and it's essential that the code clamps it appropriately to avoid issues. If the `if` statement is `num < PAGE_SIZE` then `-1` will *not* trigger the `if` block, because of the unsigned vs signed comparison.
The other check is `if (num <= 0 || num < PAGE_SIZE)`. This is equivalent to comparing with `(int)PAGE_SIZE` because when num is positive, it performs a positive vs positive comparison. But I would like to check if it's the more readable choice.
My next step is to examine the compiler flags in the kernel to see if we're using `-Wsign-compare` to help catch potential issues with signed/unsigned comparisons. Let's grep for `(int)PAGE_SIZE` throughout the kernel and see if there are other similar instances to investigate.
|
| 247/4 |
2026/09/09 17:22 |
tool |
grepper |
0m
Args: map[Expression:\(int\)\s*PAGE_SIZE]
Results: map[Output:drivers/infiniband/sw/siw/siw_qp_rx.c=29=static int siw_rx_umem(struct siw_rx_stream *srx, struct siw_umem *umem,
--
drivers/infiniband/sw/siw/siw_qp_rx.c-51- pg_off = dest_addr & ~PAGE_MASK;
drivers/infiniband/sw/siw/siw_qp_rx.c:52: bytes = min(len, (int)PAGE_SIZE - pg_off);
drivers/infiniband/sw/siw/siw_qp_rx.c-53-
--
drivers/infiniband/sw/siw/siw_qp_tx.c=437=static noinline_for_stack int siw_tx_hdt(struct siw_iwarp_tx *c_tx,
--
drivers/infiniband/sw/siw/siw_qp_tx.c-498- while (sge_len) {
drivers/infiniband/sw/siw/siw_qp_tx.c:499: size_t plen = min((int)PAGE_SIZE - fp_off, sge_len);
drivers/infiniband/sw/siw/siw_qp_tx.c-500- void *kaddr;
--
drivers/md/md-bitmap.c=558=static int read_file_page(struct file *file, unsigned long index,
--
drivers/md/md-bitmap.c-566-
drivers/md/md-bitmap.c:567: pr_debug("read bitmap file (%dB @ %llu)\n", (int)PAGE_SIZE,
drivers/md/md-bitmap.c-568- (unsigned long long)index << PAGE_SHIFT);
--
drivers/md/md-bitmap.c-613- pr_err("md: bitmap read error: (%dB @ %llu): %d\n",
drivers/md/md-bitmap.c:614: (int)PAGE_SIZE,
drivers/md/md-bitmap.c-615- (unsigned long long)index << PAGE_SHIFT,
--
fs/hfs/bnode.c=467=struct hfs_bnode *hfs_bnode_create(struct hfs_btree *tree, u32 num)
--
fs/hfs/bnode.c-490- memzero_page(*pagep, node->page_offset,
fs/hfs/bnode.c:491: min((int)PAGE_SIZE, (int)tree->node_size));
fs/hfs/bnode.c-492- set_page_dirty(*pagep);
--
include/net/sock.h=1618=static inline void sk_mem_reclaim(struct sock *sk)
--
include/net/sock.h-1626-
include/net/sock.h:1627: if (reclaimable >= (int)PAGE_SIZE)
include/net/sock.h-1628- __sk_mem_reclaim(sk, reclaimable);
--
kernel/power/swap.c=946=int swsusp_write(unsigned int flags)
--
kernel/power/swap.c-968- error = snapshot_read_next(&snapshot);
kernel/power/swap.c:969: if (error < (int)PAGE_SIZE) {
kernel/power/swap.c-970- if (error >= 0)
--
kernel/power/swap.c=1530=int swsusp_read(unsigned int *flags_p)
--
kernel/power/swap.c-1538- error = snapshot_write_next(&snapshot);
kernel/power/swap.c:1539: if (error < (int)PAGE_SIZE)
kernel/power/swap.c-1540- return error < 0 ? error : -EFAULT;
--
lib/test_bitmap.c=571=static void __init test_bitmap_printlist(void)
--
lib/test_bitmap.c-587- time = ktime_get();
lib/test_bitmap.c:588: ret = scnprintf(buf, PAGE_SIZE, "%*pbl", (int)PAGE_SIZE * 8, bmap);
lib/test_bitmap.c-589- time = ktime_get() - time;
--
net/ceph/messenger_v1.c=523=static int write_partial_skip(struct ceph_connection *con)
--
net/ceph/messenger_v1.c-528- while (con->v1.out_skip > 0) {
net/ceph/messenger_v1.c:529: size_t size = min(con->v1.out_skip, (int)PAGE_SIZE);
net/ceph/messenger_v1.c-530-
--
net/ceph/messenger_v2.c=284=static void set_out_bvec_zero(struct ceph_connection *con)
--
net/ceph/messenger_v2.c-289- bvec_set_page(&con->v2.out_bvec, ceph_zero_page,
net/ceph/messenger_v2.c:290: min(con->v2.out_zero, (int)PAGE_SIZE), 0);
net/ceph/messenger_v2.c-291- con->v2.out_iter_sendpage = true;
--
net/ceph/messenger_v2.c=951=static void init_sgs_pages(struct scatterlist **sg, struct page **pages,
--
net/ceph/messenger_v2.c-958- do {
net/ceph/messenger_v2.c:959: int len = min(resid, (int)PAGE_SIZE - off);
net/ceph/messenger_v2.c-960-
--
net/ceph/messenger_v2.c=2049=static void prepare_read_enc_page(struct ceph_connection *con)
--
net/ceph/messenger_v2.c-2057- bvec_set_page(&bv, con->v2.in_enc_pages[con->v2.in_enc_i],
net/ceph/messenger_v2.c:2058: min(con->v2.in_enc_resid, (int)PAGE_SIZE), 0);
net/ceph/messenger_v2.c-2059-
--
net/ceph/messenger_v2.c=3211=static void queue_enc_page(struct ceph_connection *con)
--
net/ceph/messenger_v2.c-3219- bvec_set_page(&bv, con->v2.out_enc_pages[con->v2.out_enc_i],
net/ceph/messenger_v2.c:3220: min(con->v2.out_enc_resid, (int)PAGE_SIZE), 0);
net/ceph/messenger_v2.c-3221-
--
net/ceph/messenger_v2.c=3429=static u32 crc32c_zeros(u32 crc, int zero_len)
--
net/ceph/messenger_v2.c-3433- while (zero_len) {
net/ceph/messenger_v2.c:3434: len = min(zero_len, (int)PAGE_SIZE);
net/ceph/messenger_v2.c-3435- crc = crc32c(crc, page_address(ceph_zero_page), len);
--
net/ceph/pagevec.c=72=void ceph_zero_page_vector_range(int off, int len, struct page **pages)
--
net/ceph/pagevec.c-81- if (off) {
net/ceph/pagevec.c:82: int end = min((int)PAGE_SIZE, off + len);
net/ceph/pagevec.c-83- dout("zeroing %d %p head from %d\n", i, pages[i],
]
|
| 248/4 |
2026/09/09 17:22 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 58531
output: 37
thoughts: 1053
Thoughts: **Analyzing Potential Integer Overflow in SCSI Scatter-Gather Lists**
Okay, let's break this down. First, I noticed the use of `(int)PAGE_SIZE` in `kernel/power/swap.c` when comparing an `int` variable to `PAGE_SIZE`. The purpose of casting `PAGE_SIZE` to an `int` before comparison is to prevent an unsigned conversion if the `int` could be negative, which is a classic and easy-to-miss bug.
This made me think of `drivers/scsi/sg.c` around line 1876 and the `sg_build_indirect` function. I saw a similar comparison: `if (num < (int)PAGE_SIZE)`. This looks like a prime candidate for the same bug. The goal here seems to clamp `num` to at least `PAGE_SIZE`. Then there is `init_sg()`: where `scatter_elem_sz` is initialized. If `scatter_elem_sz` is given a negative value as a module parameter, the `if (scatter_elem_sz < (int)PAGE_SIZE)` condition ensures it's correctly clamped to `PAGE_SIZE` during initialization. Now, previously, it was `scatter_elem_sz < PAGE_SIZE`. With the old code, `-1 < PAGE_SIZE` would be false, because the `-1` would be converted to an unsigned long and become a huge positive number. But with `(int)PAGE_SIZE`, the comparison becomes correct. This is good, and it's a perfect example of why the prompt instructs to check for and fix similar cases within the same file.
Fixing `init_sg()` by casting `(int)PAGE_SIZE` is a good example of this! I should also check `sg_build_indirect()` for similar issues, where `if (num < (int)PAGE_SIZE)` is present.
Now, let's step back and think a bit more broadly. What happens if `num` *is* negative? I need to analyze `sg_build_indirect` in full. In the code, if `num < (int)PAGE_SIZE`, `num` is immediately set to `PAGE_SIZE`. So, *in practice* the only condition the code deals with is where `num` is `>= PAGE_SIZE`. Since `PAGE_SIZE` is at least 4096, `num` is always positive after that initial check. The code then uses `get_order(num)` and constrains `order` with `min_t(int, order, MAX_PAGE_ORDER)`.
Therefore `num` is ALWAYS `>= PAGE_SIZE > 0`.
So, `get_order(num)` is called with a positive value >= `PAGE_SIZE`. For `PAGE_SIZE`, `order` is 0, for any value > `PAGE_SIZE`, `order` is > 0. Then `order = min_t(int, order, MAX_PAGE_ORDER);` bounds `order` to `[0, MAX_PAGE_ORDER]`. So `ret_sz = 1 << (PAGE_SHIFT + order);` will *never* shift out of bounds, and will never overflow `int`! And `alloc_pages(gfp_mask, order)` will *never* trigger `WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER)`.
Let's carefully re-examine the whole `sg_build_indirect` function to be sure I haven't missed anything. I've got to make sure this clamping logic works as intended and doesn't introduce other issues, like an integer overflow that could lead to memory corruption or out-of-bounds access later down the line. I must check the logic surrounding this clamping to verify that no subtle issues exist.
|
| 249/4 |
2026/09/09 17:22 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1850 LineCount:85]
Results: map[Contents:1850: return tablesize; /* number of scat_gath elements allocated */
1851: }
1852:
1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
1931: static void
1932: sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
1933: {
1934: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
]
|
| 250/4 |
2026/09/09 17:22 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 61883
output: 33
thoughts: 42
Thoughts: Okay, let's dive into this. I need to take a look at `def_reserved_size` and see what's going on.
**Checking `def_reserved_size`**
My immediate concern is whether we're potentially encountering the same type of problem with `def_reserved_size` as we've seen elsewhere. I need to determine if there's any similar vulnerability or unexpected behavior associated with it. The next logical step is to trace its usage. I'll need to meticulously analyze all instances where `def_reserved_size` is referenced and employed. This should give me a good handle on its impact and where any potential issues might manifest.
|
| 251/4 |
2026/09/09 17:22 |
tool |
grepper |
0m
Args: map[Expression:def_reserved_size PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=69=static int sg_proc_init(void);
--
drivers/scsi/sg.c-84-/* N.B. This variable is readable and writeable via
drivers/scsi/sg.c:85: * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
drivers/scsi/sg.c-86- * of this size (or less if there is not enough memory) will be reserved
--
drivers/scsi/sg.c-90-/* picks up init parameter */
drivers/scsi/sg.c:91:static int def_reserved_size = SG_DEF_RESERVED_SIZE;
drivers/scsi/sg.c-92-static int sg_allow_dio = SG_ALLOW_DIO_DEF;
--
drivers/scsi/sg.c=1625=module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1626-
drivers/scsi/sg.c:1627:static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
drivers/scsi/sg.c-1628-{
--
drivers/scsi/sg.c-1641-
drivers/scsi/sg.c:1642: def_reserved_size = size;
drivers/scsi/sg.c-1643- return 0;
--
drivers/scsi/sg.c-1645-
drivers/scsi/sg.c:1646:static const struct kernel_param_ops def_reserved_size_ops = {
drivers/scsi/sg.c:1647: .set = def_reserved_size_set,
drivers/scsi/sg.c-1648- .get = param_get_int,
--
drivers/scsi/sg.c-1650-
drivers/scsi/sg.c:1651:module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
drivers/scsi/sg.c-1652- S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1660=MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
drivers/scsi/sg.c:1662:MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
drivers/scsi/sg.c-1663-MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
--
drivers/scsi/sg.c=2143=sg_add_sfp(Sg_device * sdp)
--
drivers/scsi/sg.c-2174-
drivers/scsi/sg.c:2175: bufflen = min_t(int, def_reserved_size,
drivers/scsi/sg.c-2176- max_sectors_bytes(sdp->device->request_queue));
--
drivers/scsi/sg.c=2355=sg_proc_init(void)
--
drivers/scsi/sg.c-2364- proc_create_seq("debug", S_IRUGO, p, &debug_seq_ops);
drivers/scsi/sg.c:2365: proc_create("def_reserved_size", S_IRUGO | S_IWUSR, p, &dressz_proc_ops);
drivers/scsi/sg.c-2366- proc_create_single("device_hdr", S_IRUGO, p, sg_proc_seq_show_devhdr);
--
drivers/scsi/sg.c=2401=static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)
drivers/scsi/sg.c-2402-{
drivers/scsi/sg.c:2403: return single_open(file, sg_proc_seq_show_int, &def_reserved_size);
drivers/scsi/sg.c-2404-}
--
drivers/scsi/sg.c=2407=sg_proc_write_dressz(struct file *filp, const char __user *buffer,
--
drivers/scsi/sg.c-2419- if (k <= 1048576) { /* limit "big buff" to 1 MB */
drivers/scsi/sg.c:2420: def_reserved_size = k;
drivers/scsi/sg.c-2421- return count;
--
drivers/scsi/sg.c=2585=static int sg_proc_seq_show_debug(struct seq_file *s, void *v)
--
drivers/scsi/sg.c-2591- if (it && (0 == it->index))
drivers/scsi/sg.c:2592: seq_printf(s, "max_active_device=%d def_reserved_size=%d\n",
drivers/scsi/sg.c:2593: (int)it->max, def_reserved_size);
drivers/scsi/sg.c-2594-
]
|
| 252/4 |
2026/09/09 17:22 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 63487
output: 37
thoughts: 28
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing the `def_reserved_size_set` Function**
Alright, let's dive into this `def_reserved_size_set`. My immediate thought is, what's its purpose? Given the name, I'm guessing it deals with setting reserved sizes, likely related to memory allocation or perhaps some resource management. I'm going to look at the implementation and break down what `def_reserved_size_set` is doing. I'm focusing on understanding its behavior and potential implications within the context of the larger system. Time to dig in.
|
| 253/4 |
2026/09/09 17:22 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1627 LineCount:20]
Results: map[Contents:1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
]
|
| 254/4 |
2026/09/09 17:22 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 63962
output: 31
thoughts: 3359
Thoughts: **Analysis of scatter_elem_sz Validation and Allocation in SCSI Scatter-Gather Driver**
Okay, so I've been diving into the scatter-gather code, specifically looking at how `scatter_elem_sz` is handled. It seems that while `def_reserved_size` has a callback for validation, `scatter_elem_sz` doesn't, and it's bound directly using `module_param_named`. I was initially wondering if we should add a setter for it, or validate in `sg_build_indirect`, but that initial concern seems to be somewhat answered.
The thing is, `scatter_elem_sz` is adjusted dynamically within `sg_build_indirect()` since 2006, specifically to clamp to `PAGE_SIZE` if a smaller value is set, and to bump up to a larger value if that's what's actually needed for the current allocation size. The driver documentation explicitly states this is intended. This is happening both in `init_sg` and `sg_build_indirect`. So, adding a setter *could* introduce a breaking change if we don't handle the established behavior.
Looking at how the code already does this, `init_sg` and `sg_build_indirect` ensure the value is at least `PAGE_SIZE`. Then, there's a cap on the `order` using `min_t` to `MAX_PAGE_ORDER`. There was a concern about setting a huge `scatter_elem_sz`, and while the `order` is capped, the code *should* be fine since `alloc_pages()` is what's actually doing the allocations, and it's limited by `MAX_PAGE_ORDER`. I realized, even if `scatter_elem_sz_prev` is larger than `PAGE_SIZE << MAX_PAGE_ORDER`, and it uses `ret_sz`, `ret_sz` is limited to what `alloc_pages()` can actually allocate. This code path is designed to work with allocation failures and will retry allocations down to 4KB (page order 0).
Looking at the code, it seems the code will round up `scatter_elem_sz` to the power of two allocated with `ret_sz`.
The core of the issue seems to be ensuring `scatter_elem_sz` is clamped to at least `PAGE_SIZE` initially and correctly handling all cases, especially since `scatter_elem_sz` is a module parameter that can be set by the user (or, I suppose, *mis*set). Also, the proposed fix, specifically the use of `num` is very elegant in order to be robust and concise.
Then, there's a really important detail: The comparisons, when `PAGE_SIZE` is unsigned and `num` is signed, which could be an issue if the comparison isn't type-safe. Using `(int)PAGE_SIZE` in the comparison ensures proper signed integer comparisons, which is *crucial* when `scatter_elem_sz` might be negative or zero. Without this cast, a negative value would bypass the check, leading to potentially incorrect behavior. This fixes a real, signed comparison bug. And finally, let's make sure there aren't any other places where this issue is present in the `drivers/scsi/sg.c` file!
|
| 255/4 |
2026/09/09 17:22 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SIZE PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=1660=MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c:1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
drivers/scsi/sg.c-1662-MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c-1672- scatter_elem_sz_prev = scatter_elem_sz;
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1877- if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1878: if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
--
drivers/scsi/sg.c=1988=sg_build_reserve(Sg_fd * sfp, int req_size)
--
drivers/scsi/sg.c-1994- do {
drivers/scsi/sg.c:1995: if (req_size < PAGE_SIZE)
drivers/scsi/sg.c:1996: req_size = PAGE_SIZE;
drivers/scsi/sg.c-1997- if (0 == sg_build_indirect(schp, sfp, req_size))
--
drivers/scsi/sg.c-2001- req_size >>= 1; /* divide by 2 */
drivers/scsi/sg.c:2002: } while (req_size > (PAGE_SIZE / 2));
drivers/scsi/sg.c-2003-}
]
|
| 256/4 |
2026/09/09 17:22 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 68699
output: 43
thoughts: 339
Thoughts: **Analyzing the `sg_build_reserve` Function**
Okay, let's dive in. Line 1995… there it is, `sg_build_reserve`. Hmm, what's this `req_size` variable all about? It looks important, so let's understand its purpose within this function. The logic looks like it is trying to allocate a buffer that is at least PAGE_SIZE, and it reduces the size in half until the requested size is less than half a page. I have a hunch it deals with some kind of SCSI scatter-gather buffer preallocation or reservation, given the naming conventions and context.
Now, where does this `req_size` actually *come* from? Let me trace its origins. Let's look at `sg_add_sfp`, that seems like a likely place, or at least its callers. Aha! In `sg_add_sfp`, I see:
```c
bufflen = min_t(int, def_reserved_size,
max_sectors_bytes(sdp->device->request_queue));
sg_build_reserve(sfp, bufflen);
```
So `req_size` is initialized as `bufflen` which is the smaller of `def_reserved_size` and `max_sectors_bytes`. It is good that the code ensures this value is set to the minimum.
I will also quickly check `sg_ioctl_common` just to make sure. Okay, I think I have a good handle on where `req_size` originates and how it influences the buffer allocation within `sg_build_reserve`.
|
| 257/4 |
2026/09/09 17:22 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/scsi/sg.c IncludeSnippetLines:5 Name:sg_build_reserve]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:sg_add_sfp SourceFile:drivers/scsi/sg.c SourceLine:2177 SourceSnippet:2172: SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
2173: "sg_add_sfp: sfp=0x%p\n", sfp));
2174:
2175: bufflen = min_t(int, def_reserved_size,
2176: max_sectors_bytes(sdp->device->request_queue));
2177: sg_build_reserve(sfp, bufflen);
2178: SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
2179: "sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
2180: sfp->reserve.bufflen,
2181: sfp->reserve.k_use_sg));
2182:
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:sg_ioctl_common SourceFile:drivers/scsi/sg.c SourceLine:1036 SourceSnippet:1031: mutex_unlock(&sfp->f_mutex);
1032: return -EBUSY;
1033: }
1034:
1035: sg_remove_scat(sfp, &sfp->reserve);
1036: sg_build_reserve(sfp, val);
1037: }
1038: mutex_unlock(&sfp->f_mutex);
1039: return 0;
1040: case SG_GET_RESERVED_SIZE:
1041: val = min_t(int, sfp->reserve.bufflen,
]] TruncatedOutput:false]
|
| 258/4 |
2026/09/09 17:22 |
llm |
patch-generator-compressor |
0m
Model:
Reply: ### Summary of Execution History
#### 1. Approaches Tried and Results
- **Crash Inspection**:
- UBSAN report showed `shift exponent 64 is too large for 32-bit type 'int'` at `drivers/scsi/sg.c:1887:13` in `sg_build_indirect()`.
- Triggered via syzkaller writing `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`, then opening `/dev/sg0`.
- **Code Inspection of `drivers/scsi/sg.c`**:
- Inspected `sg_build_indirect()` (lines 1854–1930):
- `num = scatter_elem_sz;`
- When `num != scatter_elem_sz_prev`, if `num < PAGE_SIZE`, it set `scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = PAGE_SIZE;`, but missed updating `num = PAGE_SIZE;`.
- `num` remained `0`, calling `order = get_order(0);`.
- `get_order(0)` underflows `size--` to `~0UL`, returning `order = 52` (on x86_64).
- `ret_sz = 1 << (PAGE_SHIFT + order)` evaluated to `1 << (12 + 52) = 1 << 64`, resulting in the UBSAN shift-out-of-bounds crash.
- Inspected git history for `scatter_elem_sz`:
- Commit `6460e75a104d` introduced `scatter_elem_sz` sysfs/module parameter and the adjustment check logic.
- Commit `10db10d144c0` converted indirect IO to block layer and replaced `sg_page_malloc()` with direct calls to `get_order(num)` and `alloc_pages()`, introducing the omission of `num = PAGE_SIZE;`.
- **Signed/Unsigned Comparison Bug Analysis**:
- `scatter_elem_sz` and `scatter_elem_sz_prev` are defined as signed `int`.
- `PAGE_SIZE` is `(_AC(1, UL) << CONFIG_PAGE_SHIFT)` which is of type `unsigned long`.
- Tested C integer promotion rules via `codeexpert`:
- `num < PAGE_SIZE` compares `int` against `unsigned long`.
- C usual arithmetic conversions promote `int` to `unsigned long`.
- For negative values (e.g. user writes `-1` to `/sys/module/sg/parameters/scatter_elem_sz` or sets boot param `sg.scatter_elem_sz=-1`), `(unsigned long)-1` becomes `0xFFFFFFFFFFFFFFFFUL`.
- Thus `num < PAGE_SIZE` evaluates to **false**, failing to clamp negative numbers to `PAGE_SIZE`.
- `init_sg()` has the exact same coding mistake: `if (scatter_elem_sz < PAGE_SIZE)` at line 1670.
#### 2. Current Hypotheses and Proposed Solution
- Two related bugs exist in `drivers/scsi/sg.c`:
1. `sg_build_indirect()` fails to update `num = PAGE_SIZE;` when `num` is adjusted.
2. `num < PAGE_SIZE` and `scatter_elem_sz < PAGE_SIZE` in both `sg_build_indirect()` and `init_sg()` fail on negative inputs due to promotion to `unsigned long`. Casting `(int)PAGE_SIZE` ensures signed comparison, correctly clamping both `< 0` and `< PAGE_SIZE` values.
3. `order` can exceed `MAX_PAGE_ORDER` if a very large value is set in `scatter_elem_sz` (e.g. `2000000000` -> `order = 19`, `1 << 31` overflow and `WARN_ON_ONCE_GFP` in `alloc_pages()`). Capping `order = min_t(int, order, MAX_PAGE_ORDER);` prevents this.
#### 3. Specific File Paths, Code Locations, and Snippets
- **File**: `drivers/scsi/sg.c`
- **Location 1**: `init_sg()` (around line 1670)
```c
static int __init
init_sg(void)
{
int rc;
if (scatter_elem_sz < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
```
- **Location 2**: `sg_build_indirect()` (around lines 1876–1887)
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
num = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
- **Includes**: `<linux/mm.h>` is already included in `drivers/scsi/sg.c`, providing `MAX_PAGE_ORDER`.
#### 4. Watch-Outs and Potential Traps
- Do NOT change `module_param_named(scatter_elem_sz, ...)` type from `int` to `uint` as it could alter user-space sysfs ABI error behavior.
- Ensure `(int)PAGE_SIZE` cast is applied in both `init_sg()` and `sg_build_indirect()` to handle negative values properly.
- Verify modifications with `patch-diff` after applying with `codeeditor`.
Tokens:
input: 55121
output: 1386
thoughts: 0
|
| 259/4 |
2026/09/09 17:22 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 27712
output: 37
thoughts: 285
Thoughts: **Analyzing the `sg_build_reserve` Function**
Okay, let's dissect this `sg_build_reserve` function. I'm focusing on how it handles the requested size, `req_size`. The code initializes a `Sg_scatter_hold` pointer. I see a `SCSI_LOG_TIMEOUT` call, which I'd expect to see in a SCSI driver, especially for debugging. It's logging the requested size, that's helpful.
The main logic is in the `do...while` loop. If `req_size` is less than a page size, it sets `req_size` to `PAGE_SIZE`. Then, it calls `sg_build_indirect`, and if that fails, `sg_remove_scat`. The critical part is the division of `req_size` by two in each iteration, stopping when it's less than half a page. Standard behavior, so far so good.
Now, a crucial question pops up. What if `req_size` is negative? This function doesn't seem to explicitly check for it. I need to trace where `req_size` comes from. Where is this function called? What could possibly lead to a negative value? Let me scroll up the file and find the calls... Aha! I'll look at the `SG_SET_RESERVED_SIZE` ioctl in `sg_ioctl_common` around line 1030. That's probably where the input to `req_size` is coming from, and that's where I need to focus to see if such a case could happen and lead to issues.
|
| 260/4 |
2026/09/09 17:23 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1020 LineCount:25]
Results: map[Contents:1020: result = get_user(val, ip);
1021: if (result)
1022: return result;
1023: if (val < 0)
1024: return -EINVAL;
1025: val = min_t(int, val,
1026: max_sectors_bytes(sdp->device->request_queue));
1027: mutex_lock(&sfp->f_mutex);
1028: if (val != sfp->reserve.bufflen) {
1029: if (sfp->mmap_called ||
1030: sfp->res_in_use) {
1031: mutex_unlock(&sfp->f_mutex);
1032: return -EBUSY;
1033: }
1034:
1035: sg_remove_scat(sfp, &sfp->reserve);
1036: sg_build_reserve(sfp, val);
1037: }
1038: mutex_unlock(&sfp->f_mutex);
1039: return 0;
1040: case SG_GET_RESERVED_SIZE:
1041: val = min_t(int, sfp->reserve.bufflen,
1042: max_sectors_bytes(sdp->device->request_queue));
1043: return put_user(val, ip);
1044: case SG_SET_COMMAND_Q:
]
|
| 261/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 28796
output: 37
thoughts: 96
Thoughts: Here's my analysis of these code snippets, focusing on potential issues related to size validation, just as you'd expect:
**My Line of Reasoning on Reserved Size Checks**
Okay, so I'm digging into these code snippets related to size validation, and a pattern is emerging. First, I see a check for `val < 0` within `SG_SET_RESERVED_SIZE`. That's the baseline, guarding against negative values which clearly wouldn't make sense for a size parameter.
Then, moving on, in `def_reserved_size_set`, there's another check for `size < 0`, reinforcing the protection against negative values. But it gets more interesting: this function also includes a *range check* `size > 1048576`, returning `-ERANGE` if the size is outside of 0 to 1048576. This suggests there's a defined upper bound, which is critical. I'd want to understand the reasoning behind this limit; is it hardware-imposed, memory-related, or a software design choice to limit resource allocation? That's a point to explore further.
Finally, I'm checking `sg_proc_write_dressz`. This implies that this might also be related to size. I'll need to go through the related code carefully and determine if the same checks are present to maintain consistency and prevent vulnerabilities. Overall, the presence of these checks shows a solid foundation for guarding against invalid size parameters, and that's exactly what I'd expect to see to ensure stability and prevent potential memory corruption or resource exhaustion issues.
|
| 262/4 |
2026/09/09 17:23 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:2405 LineCount:25]
Results: map[Contents:2405:
2406: static ssize_t
2407: sg_proc_write_dressz(struct file *filp, const char __user *buffer,
2408: size_t count, loff_t *off)
2409: {
2410: int err;
2411: unsigned long k = ULONG_MAX;
2412:
2413: if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2414: return -EACCES;
2415:
2416: err = kstrtoul_from_user(buffer, count, 0, &k);
2417: if (err)
2418: return err;
2419: if (k <= 1048576) { /* limit "big buff" to 1 MB */
2420: def_reserved_size = k;
2421: return count;
2422: }
2423: return -ERANGE;
2424: }
2425:
2426: static int sg_proc_seq_show_version(struct seq_file *s, void *v)
2427: {
2428: seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR,
2429: sg_version_date);
]
|
| 263/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 29674
output: 33
thoughts: 64
Thoughts: **Analyzing Potential Negative Values and Tracking a Variable**
Alright, the first thing that jumps out at me is that `def_reserved_size` definitely can't be negative. That's a fundamental constraint we need to ensure is upheld. Now, let's circle back to `scatter_elem_sz`. I have a feeling something isn't quite right there, and I need to solidify my understanding.
Where exactly is `scatter_elem_sz` being used? I need to track down all the references to it within the codebase to fully understand its impact. Right, let's pull up the source code for `drivers/scsi/sg.c`. That seems like the logical place to start, given its relevance to the SCSI subsystem and scatter-gather operations. I'll search that file for all instances of `scatter_elem_sz` and analyze its role in that context. This is going to be key to resolving the current issue.
|
| 264/4 |
2026/09/09 17:23 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 265/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 30993
output: 37
thoughts: 1141
Thoughts: **Analyzing `scatter_elem_sz` in the SCSI Generic Driver**
Okay, I need to get to the bottom of this. It looks like the `scatter_elem_sz` and `scatter_elem_sz_prev` variables are only used in a couple of key places within the `drivers/scsi/sg.c` file. I'm going to start with lines 1670, and then lines 1876-1887.
In the `init_sg` function, there's a check. If `scatter_elem_sz` is less than `PAGE_SIZE`, which would mean less than 4096 bytes, it's set to `PAGE_SIZE`, and `scatter_elem_sz_prev` is updated, too. Seems sensible, making sure it's at least a page.
Now, let's look at `sg_build_indirect`. Here, things get a bit more interesting. `num` is assigned the value of `scatter_elem_sz`. There's an `unlikely` check to see if `num` is different from the previous value of `scatter_elem_sz_prev`. If it is, and if `num` is still less than `PAGE_SIZE`, then `scatter_elem_sz` is updated to `PAGE_SIZE` and `scatter_elem_sz_prev` is also updated to `PAGE_SIZE` and `num` is also set to `PAGE_SIZE`. Then, `order` is determined with `get_order` based on `num`, clamped to `MAX_PAGE_ORDER`. Finally, the returned size, `ret_sz`, is calculated as `1 << (PAGE_SHIFT + order)`. I think the check here is to make sure we set a reasonable size, and that we set the size correctly if someone changed it at runtime (e.g. from `/sys/module/sg/parameters/scatter_elem_sz`).
The core of the matter is, what if someone provides strange values for this parameter?
Let's start by considering writing `0` to `/sys/module/sg/parameters/scatter_elem_sz`. This means `scatter_elem_sz` will become 0. When `/dev/sg0` is opened, it passes through `sg_open`, `sg_add_sfp`, then `sg_build_reserve`, and finally `sg_build_indirect`. Inside `sg_build_indirect`, `num` becomes 0. The check `(0 != scatter_elem_sz_prev)` is true. Then, `0 < PAGE_SIZE` is also true. Then, the variables are set to `PAGE_SIZE` and `num` gets set to `PAGE_SIZE`. The order becomes 0, and the size calculation is 4096. It looks like it handles it correctly and there's no crash, meaning that it is handled by the `PAGE_SIZE` clamp.
Okay, what about a negative number, like "-1"? `scatter_elem_sz` becomes -1. `num` is -1. The `unlikely` check is true, and then, due to the casting to integer, `-1 < PAGE_SIZE` is true, and the variable is reset to `PAGE_SIZE`. It works without a problem as well.
Now, what about a huge number, like "2000000000" or `INT_MAX`? `num` becomes 2000000000. The `unlikely` check is true. `num < PAGE_SIZE` is false. `scatter_elem_sz_prev` is set to this big number. Then, `get_order(2000000000)` would return 19. That's clamped to `MAX_PAGE_ORDER`, which is 10. `ret_sz` becomes `1 << (12 + 10)`, which is `1 << 22`, or 4MB. There's no shift-out-of-bounds, no signed overflow of `1 << 31` and no `WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER)`.
And finally, what if the user boots the kernel with `sg.scatter_elem_sz=-1`? In `init_sg()`, the check is performed. The code checks `-1 < PAGE_SIZE`, which is true, and then correctly clamps the value at boot to `PAGE_SIZE`.
It seems robust. There's no obvious vulnerability there. Let me quickly double-check the other lines around this code, just to be completely sure. I'll check lines 16
|
| 266/4 |
2026/09/09 17:23 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1665 LineCount:20]
Results: map[Contents:1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
1675: rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1676: SG_MAX_DEVS, "sg");
1677: if (rc)
1678: return rc;
1679: rc = class_register(&sg_sysfs_class);
1680: if (rc)
1681: goto err_out;
1682: sg_sysfs_valid = 1;
1683: rc = scsi_register_interface(&sg_interface);
1684: if (0 == rc) {
]
|
| 267/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 33495
output: 37
thoughts: 17
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and presented as if it were my own internal monologue:
**Diving into the Details: Line-by-Line Scrutiny**
Alright, time to get granular. Lines 1870 through 1895... Let's isolate that section. I need to re-examine the specific arguments being presented within that block. My initial read-through was likely more focused on the macro implications, but now I need to meticulously verify the technical underpinnings. I want to scrutinize the assumptions they're making, the methodology used (if any), and the conclusions drawn in that precise range. Are the cited references appropriate and correctly applied? Are there any logical fallacies creeping in? Does the mathematical rigor hold up to my standards? Basically, I need to get down in the weeds and make sure there are no subtle, yet crucial, flaws that could undermine the entire structure of the argument. This could mean verifying every variable, calculation, and assertion within that section to make sure that the argument is solid and defensible. I am doing the diligence needed to maintain my expertise.
|
| 268/4 |
2026/09/09 17:23 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1870 LineCount:25]
Results: map[Contents:1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
]
|
| 269/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 34207
output: 128
thoughts: 31
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, and delivered as a first-person summary:
**The Landscape is Pristine - Let's Get to Work**
Right, everything's remarkably lucid at the moment. No fuzziness, no extraneous noise – just pure signal. This clarity allows for a laser-like focus. Time to leverage that advantage and get something concrete done. I'm thinking we can efficiently address this by employing `codeeditor`. It's the most appropriate tool for this type of surgical intervention, and its capabilities should give us precise control. The target: `drivers/scsi/sg.c`. No time to waste; let's apply the changes and keep that momentum going.
|
| 270/4 |
2026/09/09 17:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode: if (scatter_elem_sz < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
} NewCode: if (scatter_elem_sz < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
} SourceFile:drivers/scsi/sg.c]
Results:
|
| 271/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 34528
output: 256
thoughts: 15
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience and presented in the first person:
**Applying the Edit to `sg_build_indirect`**
Right, let's get down to brass tacks. We've got this `sg_build_indirect` function, and we need to integrate a specific edit we've been working on. No more abstract theorizing, time to get practical. The core of this is understanding *exactly* how this edit interacts with the existing indirect buffer construction process within this specific function. I'm going to need to carefully review the affected code sections, identify where the edit logic needs to be inserted – and, importantly, *how* it will impact performance and potential bottlenecks. Is this a straightforward insertion, or will it require more intricate control flow modifications? What are the implications for memory alignment and potential cache line issues? I'll be looking for any edge cases that might expose vulnerabilities or introduce unexpected behavior with specific hardware configurations. Gotta think about potential interactions with other parts of the system too, like resource management and other indirect draw calls. This is where the real work begins.
|
| 272/4 |
2026/09/09 17:23 |
tool |
codeeditor |
0m
Args: map[CurrentCode: num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
retry: NewCode: num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
num = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
order = min_t(int, order, MAX_PAGE_ORDER);
retry: SourceFile:drivers/scsi/sg.c]
Results:
|
| 273/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 35042
output: 10
thoughts: 13
Thoughts: Okay, here's my attempt at summarizing the thought process, as requested, in the first person and assuming an expert audience:
**Patch Verification - The Next Logical Step**
Right, let's get down to brass tacks. We've got our patch, meticulously crafted and hopefully addressing the identified issue. Now, I'm thinking, before we even *consider* integrating this into the main branch or pushing it upstream, we need absolute confidence in its integrity and functionality. We're not going to be sloppy here. So, the next logical step, the *essential* step, is to rigorously verify this patch. And that means reaching for the established, trusted tool in the kit: `patch-diff`. This isn't just a cursory glance; this is about deep, meaningful, and unambiguous verification. Let's see what `patch-diff` can tell us. This needs to be checked thoroughly before continuing.
|
| 274/4 |
2026/09/09 17:23 |
tool |
patch-diff |
0m
Error:
|
| 275/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 35275
output: 23
thoughts: 23
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Considering Filepath Handling**
Okay, so I'm looking at how we're handling filepaths here. The core question is: what are we passing to this function? Is it an empty string, i.e., `File: ""`, or a full, specific path, like `File: "drivers/scsi/sg.c"`? That's the crux of it. The way we interpret that input will fundamentally change how the function operates, and potentially expose different parts of the system. I need to understand that logic precisely to assess its behavior. Any misinterpretation here could cause major issues. Let's see how that path gets passed, because a subtle difference will cause different functionality.
|
| 276/4 |
2026/09/09 17:23 |
tool |
patch-diff |
0m
Args: map[File:drivers/scsi/sg.c]
Results: map[Output:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..24d29a150 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1660,35 +1660,35 @@ MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
"size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
static int __init
init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
if (rc)
return rc;
rc = class_register(&sg_sysfs_class);
if (rc)
goto err_out;
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
return 0;
}
class_unregister(&sg_sysfs_class);
err_out:
unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
return rc;
}
@@ -1854,76 +1854,78 @@ static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
int blk_size = buff_size, order;
gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
if (blk_size < 0)
return -EFAULT;
if (0 == blk_size)
++blk_size; /* don't know why */
/* round request up to next highest SG_SECTOR_SZ byte boundary */
blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: buff_size=%d, blk_size=%d\n",
buff_size, blk_size));
/* N.B. ret_sz carried into this block ... */
mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
+ if (num < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
+ num = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
k, rem_sz));
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
return 0;
out:
for (i = 0; i < k; i++)
__free_pages(schp->pages[i], order);
if (--order >= 0)
goto retry;
return -ENOMEM;
}
]
|
| 277/4 |
2026/09/09 17:23 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 37060
output: 798
thoughts: 438
Thoughts: **My Analysis of the Proposed Patch**
Okay, after reviewing this patch, I'm satisfied. It's clean, concise, and effectively addresses the identified bug. More importantly, it tackles the issue head-on without unnecessary complexity. I appreciate the focus on minimalism here; it directly fixes the problem and the proposed solution is straightforward to understand.
Now, let's break down my thoughts on the rationale and the approach. First, the root cause is crystal clear: setting `scatter_elem_sz` to zero via sysfs caused the local `num` variable in `sg_build_indirect()` to also become zero. Although `scatter_elem_sz` was immediately updated to `PAGE_SIZE`, the local `num` variable wasn't updated, so we get undefined behavior when `get_order(0)` is called which returns 52 on x86_64. This led to a subsequent shift-out-of-bounds error. It's a classic case of missed state synchronization.
Secondly, the signed comparison issue is something I flagged immediately upon seeing the code. We have signed `int`s (`scatter_elem_sz` and `num`) being compared against an unsigned `PAGE_SIZE`. The implicit promotion to `unsigned long` created a potential trap, allowing negative values to bypass the size check. Casting `PAGE_SIZE` to `(int)` in the comparison is the correct fix here. It guarantees proper clamping of negative values in both `sg_build_indirect()` and `init_sg()`.
Finally, the added bound on the allocation order is a smart touch. A large `scatter_elem_sz` could lead to an `order` value exceeding `MAX_PAGE_ORDER`. This integer overflow in the shift operation is subtle but can cause significant problems further down the line. Bounding `order` with `min_t(int, order, MAX_PAGE_ORDER)` provides a safe and robust solution, preventing potential allocator warnings and ensuring that we stay within defined limits. This sort of defensive programming is what I look for.
|
| 278/3 |
2026/09/09 17:24 |
action |
test-patch |
24m
Results: map[PatchDiff:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..24d29a150 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1667,7 +1667,7 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
@@ -1875,14 +1875,16 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
+ if (num < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
+ num = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
TestError:]
|
| 279/3 |
2026/09/09 17:48 |
action |
If |
18m
Args:
|
| 280/4 |
2026/09/09 17:48 |
agent |
patch-reviewer |
18m
Model:
Results: map[ReviewApproved:false ReviewComments:[Boundary validation vs. data-path band-aid: The patch attempts to sanitize invalid module parameter values inside the I/O fast path (sg_build_indirect()) rather than rejecting them at the sysfs boundary. Allowing userspace to write invalid values (0, negative values, or values exceeding max page order) into /sys/module/sg/parameters/scatter_elem_sz and having sg_build_indirect() silently mutate global state violates caller/callee responsibility and invariant hygiene. Subsystem idiom alignment: Follow the exact precedent recently established in drivers/scsi/sg.c by commit d06a310b45e1 ("scsi: sg: Resolve soft lockup issue when opening /dev/sgX") for def_reserved_size. Use module_param_cb() with a custom .set callback (or param_set_uint_minmax()) to validate that scatter_elem_sz is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER] at configuration time, returning -EINVAL or -ERANGE on invalid input. Concurrency and global state mutation: Mutating global variables (scatter_elem_sz and scatter_elem_sz_prev) without locks inside sg_build_indirect() introduces data races between concurrent opens and requests. Validating and updating scatter_elem_sz at the sysfs/module parameter entry point eliminates uncoordinated runtime mutations of global state. Typing and state divergence: Casting PAGE_SIZE to (int)PAGE_SIZE to work around signed/unsigned comparison is an anti-pattern. Furthermore, clamping order with min_t(int, order, MAX_PAGE_ORDER) in sg_build_indirect() leaves scatter_elem_sz set to an out-of-range value (e.g. INT_MAX), causing permanent divergence between the sysfs parameter and actual driver allocation behavior.]]
Instruction: You are an experienced Linux kernel maintainer reviewing a proposed patch that compiles and passes reproducer tests.
Evaluate the patch diff against the crash report, root cause, and the architectural design guidelines below.
Scope Constraint (Single-Patch Submissions):
We only generate single, standalone patches (not patch series). If a comprehensive architectural redesign would require a multi-patch series touching many files, accept a localized single-patch fix as long as it correctly fixes the bug, does not introduce new issues, and avoids sentinel band-aids within its local scope.
Evaluation:
- Set ReviewApproved=true (and leave ReviewComments empty) if the patch is acceptable for upstream submission as a single-patch fix.
- Set ReviewApproved=false and list concise, actionable feedback in ReviewComments if the patch contains fixable "Kernel Architectural Design & Maintainer Taste" violations.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
---
# Kernel Architectural Design & Maintainer Taste
Evaluate kernel patches and fix proposals beyond binary bug presence. Enforce **maintainer taste**, **lifecycle symmetry**, **typestate soundness**, and **topological graph simplicity**.
---
## 1. Core Philosophy: Band-Aid vs. Architectural Design
Naive patches often introduce **defensive sentinel guards** (e.g., ad-hoc `if (!ptr) return;` checks, status flags, or suppressed warnings) directly at the point of failure. While locally avoiding crashes, they degrade subsystem architecture by leaving uninitialized states reachable.
Maintainer "good taste" solves the root cause by **shifting invariants** (making invalid states unrepresentable) and moving dynamic runtime checks into static typestate guarantees.
```
HACKY BAND-AID FIX (Monolithic Cleanup) ARCHITECTURAL DESIGN (Scoped RAII / Invariant Shift)
─────────────────────────────────────── ────────────────────────────────────────────────────
[ Init / Entry ] [ Init / Entry ]
│ │
(Register Global Cleanup) (Allocate Resource A)
│ │
[ Init Sub-B ] ──fail──┐ [ Init Sub-B ] ──fail──┐
│ (success) │ │ (success) │
▼ │ ▼ ▼
[ Setup Complete ] │ (Arm B Cleanup / RAII) (Unwind A Only:
│ │ │ B never armed)
(Deferred Teardown) │ ▼ │
│ │ [ Setup Complete ] ▼
▼ ▼ │ [ Error Exit ]
[ release_all ] ◄───────┘ (LIFO Scope Teardown)
│ │
(if (!ctx->b) return;) <-- Defensive guard! ▼
│ [ Clean Destruction ]
[ Unsafe State ] (Zero sentinel checks needed)
```
```c
// ANTI-PATTERN (Defensive Sentinel Guard): Teardown called on partial init -> callee needs guard
void driver_cleanup(struct ctx *ctx) {
if (!ctx->buf) return; // <-- Sentinel band-aid
free_buffer(ctx->buf);
}
// CANONICAL SHIFT (Granular Scoped Action): Registered only upon complete initialization
ctx->buf = alloc_buffer();
if (!ctx->buf) return -ENOMEM;
devm_add_action_or_reset(dev, free_buffer_action, ctx->buf);
```
---
## 2. Maintainer Taste as Graph Topology & Structural Simplicity
Software design quality maps directly to graph-theoretic properties across the Control-Flow Graph (CFG), Data-Flow Graph (DFG), and Object Lifecycle DAG:
### A. Control-Flow Graph (CFG) Simplification
* **Branch Minimization & Path Explosion (McCabe 1976):** Every defensive check added to a compound destructor or callback (`if (!ctx->buffer) return;`) adds a predicate node ($\pi$), increases cyclomatic complexity $v(G) = |E| - |V| + 2$, causes exponential path explosion ($O(2^k)$ paths), and enlarges explicit state spaces ($|S| = \prod |D_i|$). Good taste eliminates the branch by guaranteeing destructors are invoked only on initialized typestates. *(Note: Standard idempotent leaf deallocators like `kfree(NULL)` and public API input sanitizers are exempt).*
* **Single-Entry Single-Exit (SESE) Symmetry (Ferrante 1987, Johnson 1994, Dijkstra 1972):** Resource acquisition and release must form strict **nested dominator trees**. If resource $R_i$ is acquired at node $A$, the set of release actions $\{B_1, \dots, B_m\}$ must form a strict **post-dominating cut** relative to $A$ across all maximal exit paths.
* **Pointer Uniformity (Linus's "Good Taste" Rule):** Eliminate special-case conditional branches by operating on address indirection (e.g., indirect pointers `**curr` in linked list unlinking) to unify edge and interior cases into a branchless invariant.
* **Lexical Scope Invariants & Affine Lifecycles (Wadler 1990, RAII):** Enforce SESE symmetry and "consumed exactly once" affine invariants using compiler-backed scoped cleanup (`<linux/cleanup.h>` `guard()`, `scoped_guard()`, `__free()`).
### B. Ownership & Lifetime DAGs
* **Acyclic Lifecycles & Topological Teardown (Tarjan 1972, Kahn 1962):** Resource ownership must form a strict Directed Acyclic Graph (DAG) $G = (R, E)$. Teardown order must strictly follow reverse topological sort $\text{toposort}(G)^R$. Mixing conflicting lifetime paradigms (e.g., embedding a dynamic refcounted `kref`/socket struct inside a device-managed `devres` buffer or parent container) violates DAG acyclicity, creating synchronous blocking hacks (`wait_for_completion`), circular pins, and Use-After-Free hazards.
* **Three-Phase Concurrent Quiescence:** Multi-threaded and asynchronous teardown (networking, block layer, RCU) must strictly sequence: (1) **Deactivation/Delisting** (make unreachable) -> (2) **Quiescence & Draining** (`synchronize_rcu()`, `cancel_work_sync()`, `napi_disable()`) -> (3) **Physical Reclamation** (`kfree()`, `kmem_cache_destroy()`).
* **Typestate Validity (Strom & Yemini 1986, Aldrich et al. 2009):** A struct with $N$ fields should not use runtime boolean flags (`ctx->is_initialized`) to model incomplete typestates. Sub-resources must transition as a deterministic typestate automaton ($S_{uninit} \xrightarrow{\text{alloc}} S_{init} \xrightarrow{\text{publish}} S_{registered}$), and registration functions must accept only fully initialized typestates.
---
## 3. Deterministic Decision Trigger Matrix
| Code Symptom / Trigger (When you see X) | Anti-Pattern Band-Aid (DO NOT DO Z) | Canonical Invariant Shift (DO Y) |
| :--- | :--- | :--- |
| **Null deref in compound destructor / cleanup callback** | Add `if (!priv->buf) return;` in composite cleanup handler | Register granular cleanup immediately upon allocation via `devm_add_action_or_reset()`, `<linux/cleanup.h>` `__free()`, or discrete reverse LIFO labels |
| **UAF on dynamic object after container unbind** | Allocate with `devm_kzalloc()` and block on `wait_for_completion()` | Allocate with `kzalloc()`, manage lifetime via `kref_get()`/`kref_put()`, call unbind/delist on unbind, free in `kref` release callback |
| **Goto ladder lock leaks on early error exit** | Sprinkle manual `mutex_unlock()` across error returns | Use `guard(mutex)(&lock)` or `scoped_guard(spinlock, &lock)` from `<linux/cleanup.h>` |
| **Callback / IRQ / timer fires before full init** | Add `if (!priv->ready)` check inside IRQ/timer handler | Move `request_irq()`, `timer_setup()`, or `napi_enable()` strictly to the end of setup after all state structures are fully initialized |
| **Multi-step setup failure leaks resources** | Route all errors to a single `err:` label calling a monolithic `cleanup(priv)` with NULL checks | Use `cleanup.h` RAII, granular `devm` actions, or a strict reverse LIFO goto ladder (`err_free_b:` -> `err_free_a:`) |
| **Mixed ownership / asymmetric refcount drops** | Conditionally call `kref_put()` in caller based on error code | Enforce unconditional callee-cleans or caller-cleans ownership convention across all paths |
| **Ad-hoc state flag polling during teardown** | Add `priv->stopping = true` and spin/poll in callbacks | Use atomic typestate transitions and synchronous flush/drain APIs (`cancel_work_sync()`, `drain_workqueue()`) |
---
## 4. The Architectural Review Checklist
Before finalizing any kernel fix or review, audit against the following four criteria:
1. **The Sentinel Test (Caller vs. Callee Responsibility):**
* *Smell:* Adding a defensive guard (`if (!ptr)` or `if (flags & INITIALIZED)`) inside a compound teardown callback or destructor to mask partial initialization.
* *Invariant:* If a destructor executes on uninitialized data, the defect is at the **caller's registration/invocation point**, not the callee.
* *Note:* Standard C allocator no-ops (`kfree(NULL)`) and public API parameter validators (`if (WARN_ON(!ptr)) return -EINVAL;`) are exempt; this rule targets *internal subsystem lifecycle pipelines and teardown paths*.
* *Action:* Move registration to the point of complete initialization (`devm_add_action_or_reset()`, RAII/`__free()`, or discrete caller unwinding).
2. **LIFO Stack Unwinding Symmetry:**
* *Smell:* Releasing resources in arbitrary order or invoking destructors for partially initialized subsystems.
* *Invariant:* Resource release must strictly mirror acquisition order in reverse (LIFO) without monolithic cleanup guards.
* *Action:* Verify that partial setup/initialization failures (e.g., `probe()`, `mount()`, `open()`, `alloc_pool()`) unwind only already-allocated resources in reverse order via strict LIFO labels or `cleanup.h` scope exit.
3. **Ownership Decoupling:**
* *Smell:* Embedding dynamically refcounted objects (`kref`, `struct sock`, `struct inode`, `struct file`) directly inside hardware device-bound allocations (`devres`) or parent containers (`super_block`, `net_device`).
* *Invariant:* Dynamic consumer references must outlive parent unregistration without use-after-free, circular pins, or blocking hacks.
* *Action:* Decouple the refcounted core object from the container binding; container teardown must unbind/delist the object, but memory is freed exclusively by the final `kref_put()`.
4. **Codebase Idiom Alignment:**
* *Smell:* Using legacy custom rollback ladders, ad-hoc state flags, or manual lock unlocking on error paths.
* *Invariant:* Prefer standard, modern kernel abstractions with compiler-enforced safety guarantees.
* *Action (Modern >= 6.6):* Replace manual boilerplate with `cleanup.h` (`guard()`, `scoped_guard()`, `__free()`), `devm_add_action_or_reset()`, `refcount_t`, and standard `kref` helpers.
* *Action (Legacy / LTS / No-RAII Subsystems):* Enforce clean, branchless reverse LIFO goto ladders (`err_free_b:` -> `err_free_a:`).
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:
Bug title:
UBSAN: shift-out-of-bounds in sg_build_indirect
The crash report:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
The root cause explanation:
An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
The proposed patch diff:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..24d29a150 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1667,7 +1667,7 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
@@ -1875,14 +1875,16 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
+ if (num < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
+ num = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
Review this patch diff against the crash report, root cause explanation, and kernel architectural design guidelines.
|
| 281/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 9509
output: 37
thoughts: 598
Thoughts: **Analyzing the Proposed SCSI Driver Patch**
Okay, let's break this down. First, the user reported a UBSAN shift-out-of-bounds error in `sg_build_indirect`, specifically related to line 1887 in `drivers/scsi/sg.c`. The error indicates an excessively large shift exponent (64) for a 32-bit integer. That's a classic sign of an integer overflow, which needs immediate attention because that can lead to all sorts of issues.
Now, looking at the patch itself, the main concern is obviously near that reported line. There appear to be fixes near lines 1667 and 1875. I see the main change seems to involve some type casting and clamping of `scatter_elem_sz` and `num` to `PAGE_SIZE` when they are smaller than `PAGE_SIZE`, and in the second chunk, clamping the `order` variable with `MAX_PAGE_ORDER`.
The user's code suggests an issue where some value, possibly derived from `scatter_elem_sz` or `num` is being used in a bit-shift operation, and the patch is attempting to correct the conditions that lead to `num` becoming too large. The previous logic had a check for the size, but there was a potential flaw where an issue existed with the comparison to `PAGE_SIZE`. The original code assumed values could be less than `PAGE_SIZE` but the issue was triggered when the resulting number of pages for allocation was too large.
The addition of the cast to `(int)PAGE_SIZE` and the usage of `min_t` to clamp the value suggests an attempt to prevent the integer from overflowing. We'll need to examine the context around `scatter_elem_sz` and `num` in the source code to fully understand how the value can get manipulated into too large of a value, but this seems like a reasonable fix.
I'll need to use the tools to dive deeper into those lines and surrounding code to confirm this completely solves the problem.
|
| 282/5 |
2026/09/09 17:48 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1860 LineCount:45]
Results: map[Contents:1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
]
|
| 283/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 11346
output: 33
thoughts: 25
Thoughts: Here's a summary of my thought process, as requested:
**Diving into `scatter_elem_sz` in `drivers/scsi/sg.c`**
Okay, time to dig into this. I need to understand how `scatter_elem_sz` is defined and, more importantly, *how* it's actually used within `drivers/scsi/sg.c`. I'm going to pull up that file and start tracing its occurrences. My focus will be on the implications of the size definition in the context of the SCSI generic (sg) driver. What's the context? How is it being used? Is this related to addressing, data transfer size calculations, or something else entirely? The goal is a deep understanding of its role in scatter-gather operations within the SCSI subsystem. I need to figure out what nuances are in play.
|
| 284/5 |
2026/09/09 17:48 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 285/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 12608
output: 36
thoughts: 263
Thoughts: **My Immediate Thoughts on Parameter Validation**
Okay, first things first, I need to take a look at this `module_param_named` macro: `scatter_elem_sz` here. My first thought is: how is this parameter actually validated? Is there a built-in `param_set` handler or some other standard kernel mechanism that I'm missing? Or is there some custom validation logic that I should know about?
Wait, hold on, I just noticed that `scatter_elem_sz` is *actually* validated *within* `sg_build_indirect()`. That seems a bit... off, doesn't it? Surely, we'd want to validate it *before* the function gets called?
Right, okay, let's step back and remember how module parameters typically function in the Linux kernel: `module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);` This suggests that when a user writes a value to `/sys/module/sg/parameters/scatter_elem_sz`, it's going to use `param_set_int`.
And that's the kicker, right? `param_set_int` *parses the integer* and then directly writes it to `scatter_elem_sz`! So, if the integer is out of a sensible range... it gets written anyway!
Hmm, maybe there's a way to use `kernel_param_ops` or custom `param_ops` to validate things, but is that even standard practice with `module_param_named`?
Alright, before I dive into potentially refactoring, I need to check the upstream code. Time to dig into the git log for `drivers/scsi/sg.c` and search for any commits touching `scatter_elem_sz` or `sg_build_indirect`. See what the original intent was, and if anyone else has wrestled with this issue before.
|
| 286/5 |
2026/09/09 17:48 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 287/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 13389
output: 27
thoughts: 19
Thoughts: Okay, here's my attempt at summarizing my internal thought process as a subject matter expert, starting with a bolded header:
**Diving into Commit 6460e75a104d**
Alright, let's take a look at this commit hash, `6460e75a104d`. Right off the bat, I know I need context. A simple hash like this is useless without knowing the repository, the branch, and ideally, some surrounding commits. My first thought is: *Where did this originate?* Is it from the main development branch, a feature branch, a bugfix branch? What's the surrounding commit history looking like? I need to get a feel for the scope of this change.
I'm mentally preparing for a deep dive. I'm expecting to encounter code, configuration changes, documentation updates, maybe even test modifications. Based on the hash alone, I don't have any reason to believe a specific type of change, but it could range from a minor tweak to a substantial refactor. This implies I need to consider various likely scenarios.
My mental checklist starts: first, a quick scan of the diff to grasp the core modifications. Then, I need to evaluate its impact on the existing codebase. Are there any dependencies involved? Does this change touch areas that I am familiar with, or is this new territory? I'll be looking for potential conflicts, performance implications, and security vulnerabilities, as appropriate for the project domain. This is going to involve reading the actual changes and tracing execution paths, cross-referencing this hash with the bigger picture of the project.
Ultimately, I will be assessing this commit's merit and integrating it into the codebase, if appropriate. I will look for any potential regressions introduced by this commit, any performance, security, and stability concerns. Before I can do anything else, I need to know *what* `6460e75a104d` is actually *doing*.
|
| 288/5 |
2026/09/09 17:48 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 289/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 18262
output: 26
thoughts: 59
Thoughts: **Analyzing Recent Code Changes**
Okay, let's dive into this specific area of the codebase. My initial focus is on commit `6460e75a104d`. I recall that one as the introduction of `scatter_elem_sz` and `scatter_elem_sz_prev`. Those two additions immediately caught my attention when they were introduced, as their purpose in the larger scheme of things was not immediately clear.
But, before I get too deep in, let's take a quick look at `10db10d144c0` too. I have a hunch it might have introduced something that is relevant here. It's always beneficial to get the full picture, and avoid getting tunnel-vision on one commit.
|
| 290/5 |
2026/09/09 17:48 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 291/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 28154
output: 26
thoughts: 297
Thoughts: **Analyzing the sg_build_indirect() Function**
Okay, let's break this down. I'm looking at the `sg_build_indirect()` function and trying to understand its behavior, specifically focusing on how it handles `scatter_elem_sz`. It seems like we've got a potential issue if `scatter_elem_sz` ends up being zero, which, as I see it, is possible via sysfs.
Alright, so the first few lines are straightforward: `num` gets assigned the value of `scatter_elem_sz`. Then, the code checks if `num` is different from the previous value of `scatter_elem_sz`, which is `scatter_elem_sz_prev`. Now, here's where it gets interesting, let's say the `scatter_elem_sz` gets set to zero via sysfs. `num` becomes zero.
The check `num != scatter_elem_sz_prev` becomes true, assuming `scatter_elem_sz_prev` holds a reasonable size (like 32768, for instance). Since `num` is currently zero, and zero is less than `PAGE_SIZE`, the code goes into that conditional block. `scatter_elem_sz` and `scatter_elem_sz_prev` are both set to `PAGE_SIZE`, which is 4096.
However, crucially, `num` is *still* zero! That value hasn't changed. Then, the function calls `get_order(num)`. This means we are now calling `get_order(0)`. I can already see where this is going... The result is going to be `order = get_order(0)`. I'd better double-check the `get_order()` definition in the kernel, and how it handles a zero argument.
|
| 292/5 |
2026/09/09 17:48 |
tool |
grepper |
0m
Args: map[Expression:get_order\( PathPrefix:include/]
Results: map[Output:include/asm-generic/getorder.h-28- */
include/asm-generic/getorder.h:29:static __always_inline __attribute_const__ int get_order(unsigned long size)
include/asm-generic/getorder.h-30-{
--
include/linux/dma-map-ops.h=143=static inline void dma_free_contiguous(struct device *dev, struct page *page,
--
include/linux/dma-map-ops.h-145-{
include/linux/dma-map-ops.h:146: __free_pages(page, get_order(size));
include/linux/dma-map-ops.h-147-}
--
include/linux/mm.h=1784=static inline unsigned int compound_order(const struct page *page)
--
include/linux/mm.h-1796- *
include/linux/mm.h:1797: * A folio is composed of 2^order pages. See get_order() for the definition
include/linux/mm.h-1798- * of order.
--
include/linux/mm_types_task.h=36=struct page_frag {
--
include/linux/mm_types_task.h-47-#define PAGE_FRAG_CACHE_MAX_SIZE __ALIGN_MASK(32768, ~PAGE_MASK)
include/linux/mm_types_task.h:48:#define PAGE_FRAG_CACHE_MAX_ORDER get_order(PAGE_FRAG_CACHE_MAX_SIZE)
include/linux/mm_types_task.h-49-struct page_frag_cache {
--
include/linux/pagemap.h=707=typedef unsigned int __bitwise fgf_t;
--
include/linux/pagemap.h-721-
include/linux/pagemap.h:722:static inline unsigned int filemap_get_order(size_t size)
include/linux/pagemap.h-723-{
--
include/linux/pagemap.h=743=static inline fgf_t fgf_set_order(size_t size)
include/linux/pagemap.h-744-{
include/linux/pagemap.h:745: unsigned int order = filemap_get_order(size);
include/linux/pagemap.h-746-
--
include/linux/xarray.h=1557=void xas_create_range(struct xa_state *);
--
include/linux/xarray.h-1559-#ifdef CONFIG_XARRAY_MULTI
include/linux/xarray.h:1560:int xa_get_order(struct xarray *, unsigned long index);
include/linux/xarray.h:1561:int xas_get_order(struct xa_state *xas);
include/linux/xarray.h-1562-void xas_split(struct xa_state *, void *entry, unsigned int order);
--
include/linux/xarray.h=1565=unsigned int xas_try_split_min_order(unsigned int order);
include/linux/xarray.h-1566-#else
include/linux/xarray.h:1567:static inline int xa_get_order(struct xarray *xa, unsigned long index)
include/linux/xarray.h-1568-{
--
include/linux/xarray.h-1571-
include/linux/xarray.h:1572:static inline int xas_get_order(struct xa_state *xas)
include/linux/xarray.h-1573-{
--
include/net/sock.h=3089=extern __u32 sysctl_rmem_default;
include/net/sock.h-3090-
include/net/sock.h:3091:#define SKB_FRAG_PAGE_ORDER get_order(32768)
include/net/sock.h-3092-DECLARE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
]
|
| 293/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 29891
output: 36
thoughts: 16
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into the Kernel's Page Allocation Machinery**
Okay, time to get my hands dirty and delve into the low-level memory management of the kernel. Let's start by examining `include/asm-generic/getorder.h`. I'm specifically interested in understanding how the kernel translates a request for a certain number of pages into a power-of-two order for allocation. This header likely contains the core logic for that translation, which is crucial for efficient buddy system allocation. I'll be looking for any clever bit manipulation tricks or precomputed tables used to optimize this fundamental operation. I'll need to pay close attention to the definition of the `get_order()` macro, how it handles the nuances of different page sizes (if any), and any potential limitations or trade-offs in its design. This is where the rubber meets the road in terms of memory allocation performance, so understanding this macro's inner workings is paramount. Any architecture-specific optimizations (though this is the generic header, I'll be looking for the intention to provide architecture-specific versions) or edge-case handling will also be of interest.
|
| 294/5 |
2026/09/09 17:48 |
tool |
read-file |
0m
Args: map[File:include/asm-generic/getorder.h FirstLine:1 LineCount:45]
Results: map[Contents: 1: /* SPDX-License-Identifier: GPL-2.0 */
2: #ifndef __ASM_GENERIC_GETORDER_H
3: #define __ASM_GENERIC_GETORDER_H
4:
5: #ifndef __ASSEMBLER__
6:
7: #include <linux/compiler.h>
8: #include <linux/log2.h>
9:
10: /**
11: * get_order - Determine the allocation order of a memory size
12: * @size: The size for which to get the order
13: *
14: * Determine the allocation order of a particular sized block of memory. This
15: * is on a logarithmic scale, where:
16: *
17: * 0 -> 2^0 * PAGE_SIZE and below
18: * 1 -> 2^1 * PAGE_SIZE to 2^0 * PAGE_SIZE + 1
19: * 2 -> 2^2 * PAGE_SIZE to 2^1 * PAGE_SIZE + 1
20: * 3 -> 2^3 * PAGE_SIZE to 2^2 * PAGE_SIZE + 1
21: * 4 -> 2^4 * PAGE_SIZE to 2^3 * PAGE_SIZE + 1
22: * ...
23: *
24: * The order returned is used to find the smallest allocation granule required
25: * to hold an object of the specified size.
26: *
27: * The result is undefined if the size is 0.
28: */
29: static __always_inline __attribute_const__ int get_order(unsigned long size)
30: {
31: if (__builtin_constant_p(size)) {
32: if (!size)
33: return BITS_PER_LONG - PAGE_SHIFT;
34:
35: if (size < (1UL << PAGE_SHIFT))
36: return 0;
37:
38: return ilog2((size) - 1) - PAGE_SHIFT + 1;
39: }
40:
41: size--;
42: size >>= PAGE_SHIFT;
43: #if BITS_PER_LONG == 32
44: return fls(size);
45: #else
]
|
| 295/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 30848
output: 37
thoughts: 9
Thoughts: Okay, I'm ready. Please provide the text you'd like me to summarize. I will analyze it as if it were my own thought process, speaking from the first-person perspective, assuming you are an expert who understands the nuances of the topic. I will include lines 45-55 verbatim within the summary.
|
| 296/5 |
2026/09/09 17:48 |
tool |
read-file |
0m
Args: map[File:include/asm-generic/getorder.h FirstLine:45 LineCount:15]
Results: map[Contents: 45: #else
46: return fls64(size);
47: #endif
48: }
49:
50: #endif /* __ASSEMBLER__ */
51:
52: #endif /* __ASM_GENERIC_GETORDER_H */
]
|
| 297/5 |
2026/09/09 17:48 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 31063
output: 27
thoughts: 382
Thoughts: **My Immediate Thoughts on the Analysis**
Okay, so I'm diving into this function, `get_order(0)`. Right off the bat, `size--` results in a wraparound to `ULONG_MAX`. That's a huge unsigned long! Then, a right bit shift by `PAGE_SHIFT` gets us `0x000f_ffff_ffff_ffff`. Applying `fls64()` gives us 52. Consequently, `order` becomes 52. Now we have `ret_sz = 1 << (PAGE_SHIFT + order)`. That's `1 << (12 + 52) = 1 << 64`! And there's the problem - a shift by 64 bits with an *int*? That's triggering UBSAN because the shift count is too large for a 32-bit `int`. This whole thing could be a recipe for disaster.
Hold on a second... what if `scatter_elem_sz` is negative, like -1? Let's see... looking at `drivers/scsi/sg.c`, `scatter_elem_sz` is defined as an `int`. This is interesting because if someone gives us a negative value, or one less than `PAGE_SIZE`, the conditional `if (scatter_elem_sz < (int)PAGE_SIZE)` comes into play. Wait... hold on... `PAGE_SIZE` is *unsigned long*! The comparison becomes problematic here because we have an `int` against an `unsigned long`. That's a potential type mismatch and comparison issue. What's the *actual* type of `PAGE_SIZE`? Time to double check that.
|
| 298/5 |
2026/09/09 17:49 |
tool |
grepper |
0m
Args: map[Expression:#define PAGE_SIZE PathPrefix:arch/]
Results: map[Output:arch/arc/include/uapi/asm/page.h-26-#define PAGE_SHIFT 13
arch/arc/include/uapi/asm/page.h:27:#define PAGE_SIZE _BITUL(PAGE_SHIFT) /* Default 8K */
arch/arc/include/uapi/asm/page.h-28-#define PAGE_MASK (~(PAGE_SIZE-1))
--
arch/hexagon/kernel/vmlinux.lds.S=21=See asm-generic/sections.h for seemingly required labels.
--
arch/hexagon/kernel/vmlinux.lds.S-23-
arch/hexagon/kernel/vmlinux.lds.S:24:#define PAGE_SIZE _PAGE_SIZE
arch/hexagon/kernel/vmlinux.lds.S-25-
--
arch/loongarch/kernel/vmlinux.lds.S-6-
arch/loongarch/kernel/vmlinux.lds.S:7:#define PAGE_SIZE _PAGE_SIZE
arch/loongarch/kernel/vmlinux.lds.S-8-#define RO_EXCEPTION_TABLE_ALIGN 4
--
arch/mips/kernel/vmlinux.lds.S-4-
arch/mips/kernel/vmlinux.lds.S:5:#define PAGE_SIZE _PAGE_SIZE
arch/mips/kernel/vmlinux.lds.S-6-
--
arch/powerpc/boot/page.h-16-#define PAGE_SHIFT 12
arch/powerpc/boot/page.h:17:#define PAGE_SIZE (ASM_CONST(1) << PAGE_SHIFT)
arch/powerpc/boot/page.h-18-#define PAGE_MASK (~(PAGE_SIZE-1))
--
arch/powerpc/include/asm/spu.h=442=struct spu_priv1 {
--
arch/powerpc/include/asm/spu.h-543- u64 smm_hid; /* 0x580 */
arch/powerpc/include/asm/spu.h:544:#define PAGE_SIZE_MASK 0xf000000000000000ull
arch/powerpc/include/asm/spu.h:545:#define PAGE_SIZE_16MB_64KB 0x2000000000000000ull
arch/powerpc/include/asm/spu.h-546- u8 pad_0x588_0x600[0x600 - 0x588]; /* 0x588 */
--
arch/sparc/lib/copy_page.S-30-#if (PAGE_SHIFT == 13)
arch/sparc/lib/copy_page.S:31:#define PAGE_SIZE_REM 0x80
arch/sparc/lib/copy_page.S-32-#elif (PAGE_SHIFT == 16)
arch/sparc/lib/copy_page.S:33:#define PAGE_SIZE_REM 0x100
arch/sparc/lib/copy_page.S-34-#else
]
|
| 299/5 |
2026/09/09 17:49 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 32626
output: 33
thoughts: 39
Thoughts: Here's my take:
**Investigating PAGE_SIZE Definition**
Okay, so I need to track down the definition of `PAGE_SIZE`. My initial hunch is that it's going to be in one of the standard kernel include files. Given its fundamental nature, it's likely defined in `include/asm-generic/page.h`. However, architecture-specific definitions can sometimes override the generic ones. Thus, I'll also glance at `arch/x86/include/asm/page_types.h` in the x86 case as it could be defined there, or it could be defined to use `PAGE_SIZE` within the x86 headers. I will investigate both files in order.
|
| 300/5 |
2026/09/09 17:49 |
tool |
grepper |
0m
Error:
Args: map[Expression:#define PAGE_SIZE PathPrefix:arch/x86/include/]
Results:
|
| 301/5 |
2026/09/09 17:49 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 32865
output: 38
thoughts: 27
Thoughts: Here's a summary of my immediate thought process, keeping in mind my expertise:
**Checking `PAGE_SHIFT` on x86**
Okay, time to get down to brass tacks. I need to understand the page size used by the kernel in this x86 architecture. The most direct way to get that is to look at the `PAGE_SHIFT` macro definition. I know it's probably defined within the architecture-specific include files, so I'll navigate to `arch/x86/include/asm/page_types.h`. This file will tell me the bit-shift value that, when applied to a physical address, determines the page number. Knowing this is fundamental for understanding how the kernel manages memory on this platform. This is critical for memory management, the virtual memory system, and understanding how the kernel structures data on a page-by-page basis. Time to check!
|
| 302/5 |
2026/09/09 17:49 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SHIFT PathPrefix:arch/x86/include/asm/page_types.h]
Results: map[Output:arch/x86/include/asm/page_types.h-19-
arch/x86/include/asm/page_types.h:20:#define HPAGE_SHIFT PMD_SHIFT
arch/x86/include/asm/page_types.h:21:#define HPAGE_SIZE (_AC(1,UL) << HPAGE_SHIFT)
arch/x86/include/asm/page_types.h-22-#define HPAGE_MASK (~(HPAGE_SIZE - 1))
arch/x86/include/asm/page_types.h:23:#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
arch/x86/include/asm/page_types.h-24-
--
arch/x86/include/asm/page_types.h=58=static inline phys_addr_t get_max_mapped(void)
arch/x86/include/asm/page_types.h-59-{
arch/x86/include/asm/page_types.h:60: return (phys_addr_t)max_pfn_mapped << PAGE_SHIFT;
arch/x86/include/asm/page_types.h-61-}
]
|
| 303/5 |
2026/09/09 17:49 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 33433
output: 32
thoughts: 15
Thoughts: Here's my thought process, summarized as you requested:
**Finding PAGE_SIZE Definition for x86**
Okay, so I need to track down the definition of `PAGE_SIZE` specifically for the x86 architecture. I know this is a fundamental concept, but I'm being precise. It's often defined within the operating system's kernel headers, or potentially by the compiler or the C standard library implementation, so I'll need to know which to look for. Is it a compile-time constant? If so, it might be in an architecture-specific header. I'll need to figure out where the standard header files are located on this system. Then, I will start by searching common system header paths, and then perhaps delve into architecture-specific header files if the initial search is unfruitful. Once I know the include file, I can search for `PAGE_SIZE` directly. I need to keep in mind the potential for conditional compilation or macros that might define it. I should also check if `getpagesize()` or similar system calls are relevant for this task. The specific method used might depend on whether I'm working with a kernel, a user-space application, or some other system component.
|
| 304/5 |
2026/09/09 17:49 |
tool |
grepper |
0m
Error:
Args: map[Expression:define PAGE_SIZE PathPrefix:arch/x86/include/]
Results:
|
| 305/5 |
2026/09/09 17:49 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 33751
output: 29
thoughts: 18
Thoughts: Here's my thought process, as it went:
**Finding the PAGE_SIZE Definition**
Okay, so I need to track down where `PAGE_SIZE` is defined. My first instinct, given the context of dealing with kernel internals or system calls, is to check the standard include directories. I'll start with the obvious places: `include/vdso` and `include/uapi`. `vdso` is a good starting point because it is specific to the vDSO, but `uapi` contains the user-space API headers, so the definition is likely there. It is common to find the fundamental system definitions there. Let me start there first.
|
| 306/5 |
2026/09/09 17:49 |
tool |
grepper |
0m
Args: map[Expression:#define PAGE_SIZE\b PathPrefix:include/]
Results: map[Output:include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
]
|
| 307/5 |
2026/09/09 17:49 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 34009
output: 27
thoughts: 875
Thoughts: **Unraveling a Potential Integer Overflow Vulnerability**
Okay, so I've been digging into this `PAGE_SIZE` constant and how it interacts with signed integers in this code. It seems like the core issue lies in the comparison between `scatter_elem_sz`, which is an `int`, and `PAGE_SIZE`, which is an `unsigned long`. Bingo! That's it! I know this stuff cold. I've seen it before.
My thoughts are: I'm seeing a potential integer overflow situation here. When `scatter_elem_sz` is negative, the comparison `scatter_elem_sz < PAGE_SIZE` evaluates to *false* because the signed `int` is implicitly converted to an `unsigned long`. Specifically, `-1` becomes a huge positive number, resulting in the comparison being always *false*!
I see it in `init_sg()`:
```c
if (scatter_elem_sz < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
```
If `scatter_elem_sz` was negative, e.g. `-1`:
`scatter_elem_sz < PAGE_SIZE` is FALSE because `scatter_elem_sz` gets converted to `(unsigned long)-1`!
And in `sg_build_indirect`:
`num = scatter_elem_sz;`
`if (num < PAGE_SIZE)` is FALSE if `num < 0`!
This explains the patch that does `if (scatter_elem_sz < (int)PAGE_SIZE)`. I think I understand it.
But... `(int)PAGE_SIZE` feels a bit kludgy. I have to think: is this a good fix, is the approach flawed, is this right or wrong? I need to go deeper to understand the *why* here. I have to check the history, see how module parameters work in this context, how `scatter_elem_sz` is used elsewhere, and most importantly, check what upstream has done on this!
I need to see if this has been addressed upstream! I'm going to leverage my git-fu. I'm going to search upstream git logs and commits that touch `sg_build_indirect` or `scatter_elem_sz`. That should give me the answer.
|
| 308/5 |
2026/09/09 17:49 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:sg_build_indirect Count:10]
Results:
|
| 309/5 |
2026/09/09 17:59 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 35460
output: 38
thoughts: 13
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Adding Path Prefix for SCSI Drivers**
Okay, so I'm looking at organizing this driver structure, and it seems like the most logical step is to integrate a `PathPrefix` for the SCSI drivers. This isn't just a cosmetic change; it's about maintaining a clear, maintainable, and scalable directory structure.
By adding `PathPrefix="drivers/scsi/"`, I'm creating a specific, well-defined location for everything related to the Small Computer System Interface. This instantly improves readability – when someone is browsing the project, they'll know exactly where to find anything SCSI-related. More importantly, it helps prevent naming conflicts and unexpected behavior as the codebase grows. It will reduce the possibility of conflicts when the codebase grows.
This also supports easier modularization. If we ever need to move or isolate specific SCSI driver components (perhaps for a kernel-level optimization or a device-specific build), having everything under a single, well-defined prefix makes that process significantly less complex. It provides a logical organizational structure for our codebase. It makes debugging easier as well.
It's a small change, but it's a critical one for long-term maintainability. I'm thinking of it as laying the groundwork for more advanced features like dynamic driver loading or advanced module management in the future. I want to make sure we do it right the first time.
|
| 310/5 |
2026/09/09 17:59 |
tool |
git-log |
0m
Args: map[CodeRegexp:sg_build_indirect Count:10 PathPrefix:drivers/scsi/]
Results: map[Output:95e159d6dd80 scsi: Implement sg_printk()
626710c9d665 sg: incorporate sg_build_direct into sg_start_req
7ca63cb470f2 [SCSI] sg: fix incorrect last scatg length
d6b10348f939 [SCSI] convert sg to scsi_execute_async
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 311/5 |
2026/09/09 18:00 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 35945
output: 22
thoughts: 22
Thoughts: Here's my thought process, summarized as you requested:
**Investigating Memory Management Techniques in Recent Commits**
Okay, so I need to dive into some recent code changes. My goal is to understand how we're currently handling memory management, particularly around scatter-gather lists and indirect buffers. I'm going to start by leveraging our existing commit history. Specifically, I'm thinking I should search for commit messages containing keywords related to the techniques I'm interested in. I'll focus on two key terms: "scatter\_elem\_sz" and "sg\_build\_indirect." Those should give me a good starting point. The first likely relates to the size of individual scatter-gather elements. The latter is a specific function that suggests build an indirect buffer. This search should quickly filter down to the most relevant changes, giving me a starting point for my deeper analysis of our memory management implementation. This should get me going and I can determine from there if any further keyword searches are required.
|
| 312/5 |
2026/09/09 18:00 |
tool |
git-log |
0m
Args: map[MessageRegexps:[scatter_elem_sz]]
Results: map[Output:4d2de3a50ce1 [SCSI] fix BUG when sum(scatterlist) > bufflen
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 313/5 |
2026/09/09 18:00 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 36259
output: 25
thoughts: 17
Thoughts: Okay, here's my interpretation of what's going through my mind, acting as an expert reviewing that commit, and starting with a bolded header:
**Diving into Commit 4d2de3a50ce1**
Alright, let's pull up that commit, 4d2de3a50ce1. I need to get a clear picture of what's been changed here and, more importantly, *why*. My initial scan will be for any obvious red flags: large diffs, seemingly unrelated code touching the same files, or potentially disruptive changes to core systems. I'm already formulating hypotheses about the likely intent based on the commit message (which I will read *very* carefully), the author, and perhaps the branch this came from. Now, let's see what we're actually working with, and I'll start with a methodical diff analysis, mentally noting any sections that demand deeper scrutiny.
|
| 314/5 |
2026/09/09 18:00 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 4d2de3a50ce19af2008a90636436a1bf5b3b697b
Author: Tony Battersby <tonyb@cybernetics.com>
Date: Tue Feb 5 10:36:10 2008 -0500
[SCSI] fix BUG when sum(scatterlist) > bufflen
When sending a SCSI command to a tape drive via the SCSI Generic (sg)
driver, if the command has a data transfer length more than
scatter_elem_sz (32 KB default) and not a multiple of 512, then I either
hit BUG_ON(!valid_dma_direction(direction)) in dma_unmap_sg() or else
the command never completes (depending on the LLDD).
When constructing scatterlists, the sg driver rounds up the scatterlist
element sizes to be a multiple of 512. This can result in
sum(scatterlist lengths) > bufflen. In this case, scsi_req_map_sg()
incorrectly sets bio->bi_size to sum(scatterlist lengths) rather than to
bufflen. When the command completes, req_bio_endio() detects that
bio->bi_size != 0, and so it doesn't call bio_endio(). This causes the
command to be resubmitted, resulting in BUG_ON or the command never
completing.
This patch makes scsi_req_map_sg() set bio->bi_size to bufflen rather
than to sum(scatterlist lengths), which fixes the problem.
Signed-off-by: Tony Battersby <tonyb@cybernetics.com>
Acked-by: Mike Christie <michaelc@cs.wisc.edu>
Signed-off-by: James Bottomley <James.Bottomley@HansenPartnership.com>
diff --git a/drivers/scsi/scsi_lib.c b/drivers/scsi/scsi_lib.c
index f243fc30c908..135c1d054701 100644
--- a/drivers/scsi/scsi_lib.c
+++ b/drivers/scsi/scsi_lib.c
@@ -301,7 +301,6 @@ static int scsi_req_map_sg(struct request *rq, struct scatterlist *sgl,
page = sg_page(sg);
off = sg->offset;
len = sg->length;
- data_len += len;
while (len > 0 && data_len > 0) {
/*
]
|
| 315/5 |
2026/09/09 18:00 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 37163
output: 31
thoughts: 1009
Thoughts: **Analyzing a Potential Bug in `sg.c`**
Okay, so this bug hasn't been addressed yet in this tree. I need to dive into `drivers/scsi/sg.c` and take a closer look at `scatter_elem_sz`. First, I'll need to figure out where it's defined and how it's used. Let's see... lines 94-95 define `scatter_elem_sz` and `scatter_elem_sz_prev`, both initialized to `SG_SCATTER_SZ`.
Then, line 1624 shows that `scatter_elem_sz` is exposed as a module parameter using `module_param_named`. Interesting. And line 1667 initializes this, ensuring that `scatter_elem_sz` is at least `PAGE_SIZE`. Moving on to line 1876, I see `scatter_elem_sz` being used to determine the size of scatter gather elements. I see the code adjusts `scatter_elem_sz` and `scatter_elem_sz_prev` based on comparisons. Crucially, lines 1900-1903 show this adjustment based on `ret_sz`.
Wait! I need to be careful here, there's a possible bug at line 1912: `__free_pages(schp->pages[k], order);` where it should be `schp->pages[i]` based on the context! That's another bug in existing code (though not our focus, let's notice it).
Now, let's zoom out a bit. I need to understand how module parameters are designed in the Linux kernel in general. Specifically, how do module parameters with validation work? I'll probably need to look up `module_param_cb` to find out. Let's start with a kernel tree search!
|
| 316/5 |
2026/09/09 18:00 |
tool |
grepper |
0m
Args: map[Expression:module_param_cb\( PathPrefix:drivers/scsi/]
Results: map[Output:drivers/scsi/sg.c=1646=static const struct kernel_param_ops def_reserved_size_ops = {
--
drivers/scsi/sg.c-1650-
drivers/scsi/sg.c:1651:module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
drivers/scsi/sg.c-1652- S_IRUGO | S_IWUSR);
]
|
| 317/5 |
2026/09/09 18:00 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 38738
output: 37
thoughts: 52
Thoughts: Okay, here's my interpretation of those directives, structured as a first-person account from the perspective of an expert:
**Diving Deep into `drivers/scsi/sg.c`**
Alright, let's get down to brass tacks. I need to zero in on a specific area within the `sg.c` file, specifically the SCSI Generic (sg) driver. The instructions point me to lines 1646-1652, but I'm going to take a slightly broader look at the surrounding code, let's say lines 1620-1660, just for context. From experience, details in this area suggest that these lines likely deal with input/output operations. This likely involves handling commands sent to the SCSI device. I'm guessing that this is related to how the sg driver communicates these commands to the underlying SCSI host adapter and how it interprets the responses. Time to dig in and see what nuances are contained within this section of code.
|
| 318/5 |
2026/09/09 18:01 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1620 LineCount:40]
Results: map[Contents:1620:
1621: kref_put(&sdp->d_ref, sg_device_destroy);
1622: }
1623:
1624: module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
1655: MODULE_DESCRIPTION("SCSI generic (sg) driver");
1656: MODULE_LICENSE("GPL");
1657: MODULE_VERSION(SG_VERSION_STR);
1658: MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
1659:
]
|
| 319/5 |
2026/09/09 18:01 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 39646
output: 38
thoughts: 259
Thoughts: **Analyzing the 'def_reserved_size_set' Function**
Okay, let's dive in. *Look at that!* I see this `def_reserved_size_set` function defined here (lines 1627-1652). Seems like it's a callback function, part of the kernel parameter mechanism. I'm immediately drawn to it because it's directly setting a value, `def_reserved_size`, from a string input. Let's break this down.
First, it checks for a null input value (`val`). If it's null, we bail out with `-EINVAL`. Makes sense, we need something to work with. Then, it uses `kstrtoint` to convert the string `val` into an integer `size`. Standard practice. And we handle potential errors in the conversion (`ret`). Crucially, there's a size check to ensure the value is within reasonable bounds: it must be between 0 and 1 MB (1048576). That's a good sanity check; we don't want someone passing some arbitrarily huge number. Finally, if all is well, the global `def_reserved_size` is assigned the converted integer value and we return 0 for success.
So, this is the function responsible for setting the default reserved size, probably in memory, by the module parameter system. The related `def_reserved_size_ops` structure likely defines the operations, *set* and *get*, to allow modification and retrieval of this parameter. And the `module_param_cb` macro, confirms this function is registered as a callback so that value is accessed.
Now, let me see which commit introduced it. I need to track down the history to understand the rationale behind this and what problem it was designed to solve.
|
| 320/5 |
2026/09/09 18:01 |
tool |
git-log |
0m
Args: map[CodeRegexp:def_reserved_size_set PathPrefix:drivers/scsi/sg.c]
Results: map[Output:d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
]
|
| 321/5 |
2026/09/09 18:01 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 40374
output: 27
thoughts: 18
Thoughts: Okay, here's my attempt at summarizing the thought process, as requested, in the first person and assuming an expert audience:
**Analyzing Commit d06a310b45e1**
Alright, let's dive into commit d06a310b45e1. My initial assessment is usually to look at the immediate context: What's the surrounding code? What's the general direction of the branch this commit belongs to? Then, I will immediately be looking for the obvious - are there any quick wins, easy to spot mistakes that were quickly patched, or are we looking at something more comprehensive?
Next I'll focus on the commit message. Is it clear and concise? Does it articulate the "why" behind the change, not just the "what"? A good message provides instant value, and bad messages raise flags immediately. Then, I will try to correlate the message with the changes - do they match? Any deviation will spark further investigation.
From there, I'll go methodically through the diff. I am looking for specific indicators of potential issues that are likely to happen within my area of expertise. Is it a performance bottleneck? Is it a security vulnerability? Is it a potential regression? Is it a refactor that, while cleaner, potentially introduces new complexities?
I'm particularly interested in any code that deviates from established patterns or introduces new dependencies. I'll meticulously review those parts to understand the rationale and ensure it aligns with the project's overall architecture and design principles. Any non-standard approach would require further scrutiny.
I'll check for the unit tests and integration tests. Are they comprehensive? Do they cover the changes adequately? Do they employ proper testing practices? Insufficient testing or poorly designed tests are a red flag, suggesting potential future problems. I will consider if these tests will have implications for the maintenance of the project.
Finally, I'll consider the broader implications. How does this commit affect the system's scalability, maintainability, and security posture? Does it introduce any breaking changes or require any downstream adjustments? I'll probably be making a quick mental map of any possible downstream impact to make sure nothing has been overlooked. And I'm always thinking about the potential for future edge cases that might arise. This is where experience and intuition really come into play.
|
| 322/5 |
2026/09/09 18:01 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 323/5 |
2026/09/09 18:01 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 42219
output: 28
thoughts: 174
Thoughts: **Digging into a Familiar Fix**
Okay, let's take a look at this issue... aha! Commit `d06a310b45e1`... That's interesting. It looks like this commit addressed the *exact* same problem, and it was related to `def_reserved_size`! I'm starting to get a good feeling about this.
Hang on... Was this part of a patch series? I should check the commit message. Ah, there it is: `Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com`. Right, so this is part of patch series `3034148`. I see a `-3`... so there must have been a `-1` and a `-2`. Worth tracking that down, just to get the full context of the fix and what led up to it.
Alright, time to get the lay of the land - I should scan the surrounding commits to get a clearer picture.
|
| 324/5 |
2026/09/09 18:01 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
]
|
| 325/5 |
2026/09/09 18:01 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 42812
output: 23
thoughts: 1206
Thoughts: **Analyzing the `sg.c` Patch: A Deep Dive into Concurrent Data Structures**
Okay, let's break this down. First, the `def_reserved_size` issue with `module_param_cb` is resolved, good. Now, `scatter_elem_sz`. It's a module parameter, defined right there, `module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);`. This patch, let's look at the diff...
Right, so the core of the patch involves adding `(int)` casts to `PAGE_SIZE` in a few places: `init_sg()` and within `sg_build_indirect()`. Why? Aha, because `scatter_elem_sz` is a signed int, and `PAGE_SIZE` is unsigned long. Without the cast, a negative `scatter_elem_sz` would, due to signed-to-unsigned conversion, appear as a massive positive number, which circumvents the intended check.
Now, let's step back. Is this just a quick fix? Or is it addressing a deeper issue? Why is `sg_build_indirect` even checking `scatter_elem_sz` at all? And, why was this `unlikely(num != scatter_elem_sz_prev)` logic introduced in the first place? Time to dig through the commit history.
Ah, commit 6460e75a104d from Douglas Gilbert in 2006. It appears he added the check because `module_param_named` allowed changing `scatter_elem_sz` via sysfs at runtime. Back then, `module_param_cb` might not have existed, or perhaps he just opted for the dynamic check during indirect buffer building.
Wait a second... and here comes the big question. Is modifying `scatter_elem_sz` and `scatter_elem_sz_prev` within `sg_build_indirect` *thread-safe*? Can multiple threads call this function simultaneously? YES! Multiple processes can open and use `/dev/sg0`, `/dev/sg1`, and so on concurrently! What are `scatter_elem_sz` and `scatter_elem_sz_prev`? They're GLOBAL static variables! There's no lock protecting them within `sg_build_indirect`! Oh boy. I need to check how `sg_build_indirect` is called, to confirm if there are any locks held. Looks like there aren't. This is a potential concurrency bug!
|
| 326/5 |
2026/09/09 18:01 |
tool |
codesearch-find-references |
0m
Args: map[Name:sg_build_indirect]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:sg_build_reserve SourceFile:drivers/scsi/sg.c SourceLine:1997] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:sg_start_req SourceFile:drivers/scsi/sg.c SourceLine:1783]] TruncatedOutput:false]
|
| 327/5 |
2026/09/09 18:01 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 44722
output: 29
thoughts: 5744
Thoughts: **Analyzing the scatter_elem_sz Vulnerability: A Deep Dive**
Okay, here's the situation: I'm looking at this potential data race in `sg_build_indirect`, where `scatter_elem_sz` gets modified without any global lock. The initial problem seems straightforward: a user can write "0" to `/sys/module/sg/parameters/scatter_elem_sz`, and this is where it all begins.
The core issue appears to be invalid input acceptance. Why does the system even *allow* this? It's time to delve into the code. Looking at `def_reserved_size`, I see a proper validation function (`def_reserved_size_set`) tied to `module_param_cb`. This is key. The question is, should `scatter_elem_sz` *also* be validated this way? Or is the current approach sufficient?
Let's understand `scatter_elem_sz` better. The documentation says it defaults to `max(SG_SCATTER_SZ, PAGE_SIZE)`. Crucially, it must be a power of 2. I need to grasp the intended use and constraints. It's meant to define the largest size of a scatter-gather list element. The driver dynamically adjusts this, rounding it up to a power of two if necessary.
Now, I'm examining Douglas Gilbert's original code. It's clear he anticipated `scatter_elem_sz` being modifiable. He included a check: `if (unlikely(num != scatter_elem_sz_prev))`. If the value changed, he clamped it to `PAGE_SIZE` if it was less than that. But he made a mistake! He forgot to update `num` after clamping, leading to a potential `get_order(num)` call with `num` equal to zero! This could result in a shift-out-of-bounds error!
The core problem boils down to type conversions and unsigned comparisons. When `scatter_elem_sz` is set to a negative value, the comparison `num < PAGE_SIZE` in `sg_build_indirect` becomes fundamentally flawed due to type conversion (int to unsigned long), causing the clamp to be bypassed. This makes the code vulnerable to a shift out of bounds error.
I'm checking if `scatter_elem_sz` can also be modified at module load, and indeed, it can via the kernel command line. This reinforces the need for robust input validation. Looking at how other code, like in the parameter validation the author added to the patch, it seems like the input sanitization should happen via module parameter callbacks.
What about the patch's `if (num < (int)PAGE_SIZE)` and `order = min_t(int, order, MAX_PAGE_ORDER);`? Is that an architectural solution, or a bandage?
Let me review the guidelines. The goal is to avoid "sentinel band-aids." We need to ensure that invalid states are unrepresentable to avoid runtime checks, making the design sounder. Is the proposed fix an architectural violation? Should `scatter_elem_sz` also be validated using `module_param_cb` like `def_reserved_size` was, in commit d06a310b45e1?
Let's review the code once again, carefully examining the patch diff! The added `order = min_t(int, order, MAX_PAGE_ORDER);` is of great concern! And also this addition, `num = PAGE_SIZE;`!
It looks like the proposed patch does the correct thing by ensuring `num` has the right value. However, the last line of the new addition, `order = min_t(int, order, MAX_PAGE_ORDER);` could still be an issue. Let's calculate: what is `PAGE_SHIFT + order` when `order == MAX_PAGE_ORDER`? This is critical!
|
| 328/5 |
2026/09/09 18:01 |
tool |
grepper |
0m
Args: map[Expression:#define MAX_PAGE_ORDER PathPrefix:include/]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
]
|
| 329/5 |
2026/09/09 18:01 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 51448
output: 27
thoughts: 63
Thoughts: **Page Allocation Sanity Check**
Okay, so I'm thinking about page allocation, specifically the `MAX_PAGE_ORDER`. Typically, I'd expect it to be around 10, right? But then, a red flag popped up in my head. Hold on... is calling `alloc_pages(gfp_mask, MAX_PAGE_ORDER)` even *valid* in this context? I'm getting a little fuzzy on the maximum order allowed within `alloc_pages`. Time to dive into the kernel's page allocator code and verify those order checks! Gotta make sure I'm not doing something boneheaded here.
|
| 330/5 |
2026/09/09 18:01 |
tool |
grepper |
0m
Args: map[Expression:MAX_PAGE_ORDER PathPrefix:mm/]
Results: map[Output:mm/Kconfig=319=config SHUFFLE_PAGE_ALLOCATOR
--
mm/Kconfig-329- allocations to compliment SLAB_FREELIST_RANDOM, but the
mm/Kconfig:330: default granularity of shuffling on the MAX_PAGE_ORDER i.e, 10th
mm/Kconfig-331- order of pages is selected based on cache utilization benefits
--
mm/Kconfig=697=config HUGETLB_PAGE_SIZE_VARIABLE
--
mm/Kconfig-703-
mm/Kconfig:704: Note that the pageblock_order cannot exceed MAX_PAGE_ORDER and will be
mm/Kconfig:705: clamped down to MAX_PAGE_ORDER.
mm/Kconfig-706-
--
mm/Kconfig=1100=config ARCH_FORCE_MAX_ORDER
--
mm/Kconfig-1104-# When ARCH_FORCE_MAX_ORDER is not defined,
mm/Kconfig:1105:# the default page block order is MAX_PAGE_ORDER (10) as per
mm/Kconfig-1106-# include/linux/mmzone.h.
--
mm/Kconfig=1108=config PAGE_BLOCK_MAX_ORDER
--
mm/Kconfig-1117- them. The maximum size of the page block order is at least limited by
mm/Kconfig:1118: ARCH_FORCE_MAX_ORDER/MAX_PAGE_ORDER.
mm/Kconfig-1119-
--
mm/Kconfig-1121- order when the page block order is required to be smaller than
mm/Kconfig:1122: ARCH_FORCE_MAX_ORDER/MAX_PAGE_ORDER or other limits
mm/Kconfig-1123- (see include/linux/pageblock-flags.h for details).
--
mm/compaction.c=575=static unsigned long isolate_freepages_block(struct compact_control *cc,
--
mm/compaction.c-619-
mm/compaction.c:620: if ((order <= MAX_PAGE_ORDER) &&
mm/compaction.c-621- (blockpfn + (1UL << order) <= end_pfn)) {
--
mm/compaction.c=855=isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
--
mm/compaction.c-976-
mm/compaction.c:977: if (order <= MAX_PAGE_ORDER) {
mm/compaction.c-978- low_pfn += (1UL << order) - 1;
--
mm/compaction.c-1035- */
mm/compaction.c:1036: if (freepage_order > 0 && freepage_order <= MAX_PAGE_ORDER) {
mm/compaction.c-1037- low_pfn += (1UL << freepage_order) - 1;
--
mm/compaction.c-1055- if (skip_isolation_on_order(order, cc->order)) {
mm/compaction.c:1056: if (order <= MAX_PAGE_ORDER) {
mm/compaction.c-1057- low_pfn += (1UL << order) - 1;
--
mm/debug_page_alloc.c=21=static int __init debug_guardpage_minorder_setup(char *buf)
--
mm/debug_page_alloc.c-24-
mm/debug_page_alloc.c:25: if (!buf || kstrtouint(buf, 10, &res) < 0 || res > MAX_PAGE_ORDER / 2) {
mm/debug_page_alloc.c-26- pr_err("Bad debug_guardpage_minorder value: %s\n", buf ?: "(missing)");
--
mm/debug_vm_pgtable.c=1046=debug_vm_pgtable_alloc_huge_page(struct pgtable_debug_args *args, int order)
--
mm/debug_vm_pgtable.c-1050-#ifdef CONFIG_CONTIG_ALLOC
mm/debug_vm_pgtable.c:1051: if (order > MAX_PAGE_ORDER) {
mm/debug_vm_pgtable.c-1052- page = alloc_contig_pages((1 << order), GFP_KERNEL,
--
mm/debug_vm_pgtable.c-1060-
mm/debug_vm_pgtable.c:1061: if (order <= MAX_PAGE_ORDER)
mm/debug_vm_pgtable.c-1062- page = alloc_pages(GFP_KERNEL, order);
--
mm/huge_memory.c=1051=static int __init hugepage_init(void)
--
mm/huge_memory.c-1063- */
mm/huge_memory.c:1064: MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER > MAX_PAGE_ORDER);
mm/huge_memory.c-1065-
--
mm/hugetlb.c=2746=int replace_free_hugepage_folios(unsigned long start_pfn, unsigned long end_pfn)
--
mm/hugetlb.c-2799-
mm/hugetlb.c:2800: if (order <= MAX_PAGE_ORDER)
mm/hugetlb.c-2801- nr = 1UL << order;
--
mm/hugetlb.c=3235=static void __init prep_and_add_bootmem_folios(struct hstate *h,
--
mm/hugetlb.c-3266- * Put bootmem huge pages into the standard lists after mem_map is up.
mm/hugetlb.c:3267: * Note: This only applies to gigantic (order > MAX_PAGE_ORDER) pages.
mm/hugetlb.c-3268- */
--
mm/hugetlb.c=4418=static int __init default_hugepagesz_setup(char *s)
--
mm/hugetlb.c-4450- * then default_hstate_max_huge_pages is set. If the default huge
mm/hugetlb.c:4451: * page size is gigantic (> MAX_PAGE_ORDER), then the pages must be
mm/hugetlb.c-4452- * allocated here from bootmem allocator.
--
mm/hugetlb_cma.c=211=void __init hugetlb_cma_reserve(void)
--
mm/hugetlb_cma.c-259- */
mm/hugetlb_cma.c:260: VM_WARN_ON(order <= MAX_PAGE_ORDER);
mm/hugetlb_cma.c-261- gigantic_page_size = PAGE_SIZE << order;
--
mm/kmsan/init.c=144=static struct smallstack collect = {
mm/kmsan/init.c-145- .index = 0,
mm/kmsan/init.c:146: .order = MAX_PAGE_ORDER,
mm/kmsan/init.c-147-};
--
mm/kmsan/init.c=203=static void kmsan_memblock_discard(void)
--
mm/kmsan/init.c-215- */
mm/kmsan/init.c:216: collect.order = MAX_PAGE_ORDER;
mm/kmsan/init.c:217: for (int i = MAX_PAGE_ORDER; i >= 0; i--) {
mm/kmsan/init.c-218- if (held_back[i].shadow)
--
mm/memblock.c=2329=static void __init __free_pages_memory(unsigned long start, unsigned long end)
--
mm/memblock.c-2337- * __ffs() behaviour is undefined for 0. start == 0 is
mm/memblock.c:2338: * MAX_PAGE_ORDER-aligned, set order to MAX_PAGE_ORDER for
mm/memblock.c-2339- * the case.
--
mm/memblock.c-2341- if (start)
mm/memblock.c:2342: order = min_t(int, MAX_PAGE_ORDER, __ffs(start));
mm/memblock.c-2343- else
mm/memblock.c:2344: order = MAX_PAGE_ORDER;
mm/memblock.c-2345-
--
mm/memory_hotplug.c=654=static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
--
mm/memory_hotplug.c-659- /*
mm/memory_hotplug.c:660: * Online the pages in MAX_PAGE_ORDER aligned chunks. The callback might
mm/memory_hotplug.c-661- * decide to not expose all pages to the buddy (e.g., expose them
--
mm/memory_hotplug.c-675- * __ffs() behaviour is undefined for 0. start == 0 is
mm/memory_hotplug.c:676: * MAX_PAGE_ORDER-aligned, Set order to MAX_PAGE_ORDER for
mm/memory_hotplug.c-677- * the case.
--
mm/memory_hotplug.c-679- if (pfn)
mm/memory_hotplug.c:680: order = min_t(int, MAX_PAGE_ORDER, __ffs(pfn));
mm/memory_hotplug.c-681- else
mm/memory_hotplug.c:682: order = MAX_PAGE_ORDER;
mm/memory_hotplug.c-683-
--
mm/mm_init.c=1586=static void __init alloc_node_mem_map(struct pglist_data *pgdat)
--
mm/mm_init.c-1597- /*
mm/mm_init.c:1598: * The zone's endpoints aren't required to be MAX_PAGE_ORDER
mm/mm_init.c-1599- * aligned but the node_mem_map endpoints must be in order
--
mm/mm_init.c=1915=static void __init deferred_free_pages(unsigned long pfn,
--
mm/mm_init.c-1929- if (nr_pages == MAX_ORDER_NR_PAGES && IS_MAX_ORDER_ALIGNED(pfn)) {
mm/mm_init.c:1930: __free_pages_core(page, MAX_PAGE_ORDER, MEMINIT_EARLY);
mm/mm_init.c-1931- return;
--
mm/mm_init.c-1933-
mm/mm_init.c:1934: /* Accept chunks smaller than MAX_PAGE_ORDER upfront */
mm/mm_init.c-1935- accept_memory(PFN_PHYS(pfn), nr_pages * PAGE_SIZE);
--
mm/mm_init.c=2307=void *__init alloc_large_system_hash(const char *tablename,
--
mm/mm_init.c-2377- SMP_CACHE_BYTES);
mm/mm_init.c:2378: } else if (get_order(size) > MAX_PAGE_ORDER || hashdist) {
mm/mm_init.c-2379- table = vmalloc_huge(size, gfp_flags);
--
mm/mm_init.c=2643=void __init mm_core_init(void)
--
mm/mm_init.c-2654- * page_ext requires contiguous pages,
mm/mm_init.c:2655: * bigger than MAX_PAGE_ORDER unless SPARSEMEM.
mm/mm_init.c-2656- */
--
mm/page_alloc.c=889=buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
--
mm/page_alloc.c-894-
mm/page_alloc.c:895: if (order >= MAX_PAGE_ORDER - 1)
mm/page_alloc.c-896- return false;
--
mm/page_alloc.c=940=static inline void __free_one_page(struct page *page,
--
mm/page_alloc.c-959-
mm/page_alloc.c:960: while (order < MAX_PAGE_ORDER) {
mm/page_alloc.c-961- int buddy_mt = migratetype;
--
mm/page_alloc.c=1600=void __meminit __free_pages_core(struct page *page, unsigned int order,
--
mm/page_alloc.c-1634- if (page_contains_unaccepted(page, order)) {
mm/page_alloc.c:1635: if (order == MAX_PAGE_ORDER && __free_unaccepted(page))
mm/page_alloc.c-1636- return;
--
mm/page_alloc.c-1664- * which contains a memory hole (i.e. there is no physical memory for a subset
mm/page_alloc.c:1665: * of the pfn range). For example, if the pageblock order is MAX_PAGE_ORDER, which
mm/page_alloc.c-1666- * will fall into 2 sub-sections, and the end pfn of the pageblock may be hole
--
mm/page_alloc.c=2055=static unsigned long find_large_buddy(unsigned long start_pfn)
--
mm/page_alloc.c-2062- */
mm/page_alloc.c:2063: int order = start_pfn ? __ffs(start_pfn) : MAX_PAGE_ORDER;
mm/page_alloc.c-2064- struct page *page;
--
mm/page_alloc.c-2068- /* Nothing found */
mm/page_alloc.c:2069: if (++order > MAX_PAGE_ORDER)
mm/page_alloc.c-2070- return start_pfn;
--
mm/page_alloc.c=2111=static bool __move_freepages_block_isolate(struct zone *zone,
--
mm/page_alloc.c-2128- /* No splits needed if buddies can't span multiple blocks */
mm/page_alloc.c:2129: if (pageblock_order == MAX_PAGE_ORDER)
mm/page_alloc.c-2130- goto move;
--
mm/page_alloc.c=2373=__rmqueue_claim(struct zone *zone, int order, int start_migratetype,
--
mm/page_alloc.c-2394- */
mm/page_alloc.c:2395: for (current_order = MAX_PAGE_ORDER; current_order >= min_order;
mm/page_alloc.c-2396- --current_order) {
--
mm/page_alloc.c=5330=static inline bool alloc_order_allowed(gfp_t gfp, unsigned int order,
--
mm/page_alloc.c-5339- */
mm/page_alloc.c:5340: return !(WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp));
mm/page_alloc.c-5341-}
--
mm/page_alloc.c=5599=static void *make_alloc_exact(unsigned long addr, unsigned int order,
--
mm/page_alloc.c-5626- *
mm/page_alloc.c:5627: * This function is also limited by MAX_PAGE_ORDER.
mm/page_alloc.c-5628- *
--
mm/page_alloc.c=6432=EXPORT_SYMBOL(adjust_managed_page_count);
--
mm/page_alloc.c-6442- * @page must be naturally aligned to the order and the order must not
mm/page_alloc.c:6443: * exceed MAX_PAGE_ORDER. All pages must be reserved.
mm/page_alloc.c-6444- */
mm/page_alloc.c=6445=void free_reserved_pages(struct page *page, unsigned int order)
--
mm/page_alloc.c-6450- VM_WARN_ON_ONCE(!IS_ALIGNED(page_to_pfn(page), nr_pages));
mm/page_alloc.c:6451: VM_WARN_ON_ONCE(order > MAX_PAGE_ORDER);
mm/page_alloc.c-6452-
--
mm/page_alloc.c=7021=static void free_prepared_contig_range(struct page *page,
--
mm/page_alloc.c-7029- /* We are limited by the largest buddy order. */
mm/page_alloc.c:7030: order = pfn ? __ffs(pfn) : MAX_PAGE_ORDER;
mm/page_alloc.c-7031- /* Don't exceed the number of pages to free. */
mm/page_alloc.c-7032- order = min_t(unsigned int, order, ilog2(nr_pages));
mm/page_alloc.c:7033: order = min_t(unsigned int, order, MAX_PAGE_ORDER);
mm/page_alloc.c-7034-
--
mm/page_alloc.c=7283=int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end,
--
mm/page_alloc.c-7305- * In contrast to the buddy, we allow for orders here that exceed
mm/page_alloc.c:7306: * MAX_PAGE_ORDER, so we must manually make sure that we are not
mm/page_alloc.c-7307- * exceeding the maximum folio order.
--
mm/page_alloc.c=7769=bool is_free_buddy_page(const struct page *page)
--
mm/page_alloc.c-7781-
mm/page_alloc.c:7782: return order <= MAX_PAGE_ORDER;
mm/page_alloc.c-7783-}
--
mm/page_alloc.c=7915=static void __accept_page(struct zone *zone, unsigned long *flags,
--
mm/page_alloc.c-7923-
mm/page_alloc.c:7924: accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
mm/page_alloc.c-7925-
mm/page_alloc.c:7926: __free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL);
mm/page_alloc.c-7927-}
--
mm/page_alloc.h=138=static inline bool page_is_buddy(struct page *page, struct page *buddy,
--
mm/page_alloc.h-173- *
mm/page_alloc.h:174: * Assumption: *_mem_map is contiguous at least up to MAX_PAGE_ORDER
mm/page_alloc.h-175- */
--
mm/page_isolation.c=223=static void unset_migratetype_isolate(struct page *page)
--
mm/page_isolation.c-244- order = buddy_order(page);
mm/page_isolation.c:245: if (order >= pageblock_order && order < MAX_PAGE_ORDER) {
mm/page_isolation.c-246- buddy = find_buddy_page_pfn(page, page_to_pfn(page),
--
mm/page_isolation.c=284=__first_valid_page(unsigned long pfn, unsigned long nr_pages)
--
mm/page_isolation.c-307- *
mm/page_isolation.c:308: * Free and in-use pages can be as big as MAX_PAGE_ORDER and contain more than one
mm/page_isolation.c-309- * pageblock. When not all pageblocks within a page are isolated at the same
mm/page_isolation.c-310- * time, free page accounting can go wrong. For example, in the case of
mm/page_isolation.c:311: * MAX_PAGE_ORDER = pageblock_order + 1, a MAX_PAGE_ORDER page has two
mm/page_isolation.c-312- * pageblocks.
mm/page_isolation.c:313: * [ MAX_PAGE_ORDER ]
mm/page_isolation.c-314- * [ pageblock0 | pageblock1 ]
--
mm/page_isolation.c=605=int test_pages_isolated(unsigned long start_pfn, unsigned long end_pfn,
--
mm/page_isolation.c-623- /*
mm/page_isolation.c:624: * Note: pageblock_nr_pages != MAX_PAGE_ORDER. Then, chunks of free
mm/page_isolation.c-625- * pages are not aligned to pageblock_nr_pages.
--
mm/page_owner.c=458=static inline bool skip_buddy_pages(unsigned long *pfn, struct page *page)
--
mm/page_owner.c-465- order = buddy_order_unsafe(page);
mm/page_owner.c:466: if (order <= MAX_PAGE_ORDER) {
mm/page_owner.c-467- unsigned long new_pfn = *pfn + (1UL << order);
--
mm/page_reporting.c=18=static int page_order_update_notify(const char *val, const struct kernel_param *kp)
--
mm/page_reporting.c-23- */
mm/page_reporting.c:24: return param_set_uint_minmax(val, kp, 0, MAX_PAGE_ORDER);
mm/page_reporting.c-25-}
--
mm/page_reporting.c=360=int page_reporting_register(struct page_reporting_dev_info *prdev)
--
mm/page_reporting.c-381- if (prdev->order != PAGE_REPORTING_ORDER_UNSPECIFIED &&
mm/page_reporting.c:382: prdev->order <= MAX_PAGE_ORDER)
mm/page_reporting.c-383- page_reporting_order = prdev->order;
--
mm/shuffle.h-8-
mm/shuffle.h:9:#define SHUFFLE_ORDER MAX_PAGE_ORDER
mm/shuffle.h-10-
--
mm/slub.c=7608=static inline int calculate_order(unsigned int size)
--
mm/slub.c-7665- order = get_order(size);
mm/slub.c:7666: if (order <= MAX_PAGE_ORDER)
mm/slub.c-7667- return order;
--
mm/slub.c=8248=static int __init setup_slub_max_order(const char *str, const struct kernel_param *kp)
--
mm/slub.c-8255-
mm/slub.c:8256: slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
mm/slub.c-8257-
--
mm/vmalloc.c=3668=vm_area_alloc_pages(gfp_t gfp, int nid,
--
mm/vmalloc.c-3672- unsigned long nr_remaining = nr_pages;
mm/vmalloc.c:3673: unsigned int max_attempt_order = MAX_PAGE_ORDER;
mm/vmalloc.c-3674- struct page *page;
--
mm/vmscan.c=6769=unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
--
mm/vmscan.c-6788- */
mm/vmscan.c:6789: BUILD_BUG_ON(MAX_PAGE_ORDER >= S8_MAX);
mm/vmscan.c-6790- BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
--
mm/vmstat.c=1114=static int __fragmentation_index(unsigned int order, struct contig_page_info *info)
--
mm/vmstat.c-1117-
mm/vmstat.c:1118: if (WARN_ON_ONCE(order > MAX_PAGE_ORDER))
mm/vmstat.c-1119- return 0;
]
|
| 331/5 |
2026/09/09 18:01 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 57986
output: 30
thoughts: 3656
Thoughts: **Analyzing the SCSI SG Driver Patch: A Deep Dive**
Okay, so I'm looking at this patch and my initial reaction is that it's addressing an issue, but is it the right solution? I see it's limiting the order passed to `alloc_pages()` with `MAX_PAGE_ORDER`, which is typical and safe – usually, that limit is around 4MB. The core issue seems to stem from a user-controlled value, `scatter_elem_sz`, being written to `/sys/module/sg/parameters/scatter_elem_sz`. This parameter's behavior is the problem and that value can be set to *anything*.
First, I see the patch adds a check: `if (scatter_elem_sz < (int)PAGE_SIZE)`. Why are they casting `PAGE_SIZE` to an `int`? It seems odd. This is used in two places. And then the patch clamps order with `min_t(int, order, MAX_PAGE_ORDER)`. I think I see what they're doing: the patch is trying to prevent extremely small or extremely large values of `scatter_elem_sz` from causing problems when allocating pages. This is probably to address a UBSAN shift-out-of-bounds error and potentially other issues. I'm trying to figure out if it fixes the *root* cause or is just a band-aid.
The *true* fix is to *validate* the `scatter_elem_sz` value at the sysfs boundary. This is exactly what was done for a similar vulnerability in `def_reserved_size` in the past. This is the Architectural Design Guidelines' "invariant" solution – make invalid states unrepresentable. I'm recalling the commit fixing `def_reserved_size` and how it used `module_param_cb` to handle the problem. That's the correct approach.
Now, let's examine the existing code. There's already a check that seems to try and make sure `scatter_elem_sz` is at least `PAGE_SIZE`, so why is this patch needed at all? It seems that, in the past, `scatter_elem_sz` was *deliberately* updated to the requested size. It seems that the earlier code aimed to round up `scatter_elem_sz` to a power of two size for efficient allocation. This could explain the existing logic.
Okay, let's consider: if the `order` is clamped, the *next* size might be different, right? And I think that is an issue that the author of the patch did not account for. If the value written to `/sys/module/sg/parameters/scatter_elem_sz` is very large then `scatter_elem_sz_prev` will always be very large. Even worse, if the user provides `INT_MIN`, it becomes a valid value!
It's very odd that `scatter_elem_sz` is an `int`, not `unsigned int` or `size_t`. This is making things unnecessarily complex.
So, I'm thinking the correct approach is to use `module_param_cb` or a similar function, like `param_set_uint_minmax` with limits to handle the problem in `scatter_elem_sz`. This solves the *root cause*: validating the input *before* it is used in calculations.
|
| 332/5 |
2026/09/09 18:02 |
tool |
grepper |
0m
Args: map[Expression:param_set_uint_minmax PathPrefix:kernel/]
Results: map[Output:kernel/params.c=242=STANDARD_PARAM_DEF(hexint, unsigned int, "%#08x", kstrtouint);
kernel/params.c-243-
kernel/params.c:244:int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
kernel/params.c-245- unsigned int min, unsigned int max)
--
kernel/params.c-259-}
kernel/params.c:260:EXPORT_SYMBOL_GPL(param_set_uint_minmax);
kernel/params.c-261-
--
kernel/sched/ext/ext.c=227=static int set_slice_us(const char *val, const struct kernel_param *kp)
kernel/sched/ext/ext.c-228-{
kernel/sched/ext/ext.c:229: return param_set_uint_minmax(val, kp, 100, 100 * USEC_PER_MSEC);
kernel/sched/ext/ext.c-230-}
--
kernel/sched/ext/ext.c=237=static int set_bypass_lb_intv_us(const char *val, const struct kernel_param *kp)
kernel/sched/ext/ext.c-238-{
kernel/sched/ext/ext.c:239: return param_set_uint_minmax(val, kp, 0, 10 * USEC_PER_SEC);
kernel/sched/ext/ext.c-240-}
]
|
| 333/5 |
2026/09/09 18:02 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 62796
output: 29
thoughts: 9460
Thoughts: **Review of Proposed Patch for sg.c**
Alright, let's break this down. It seems the issue revolves around handling the `scatter_elem_sz` module parameter in the SCSI generic driver, specifically within the `sg_build_indirect()` function. The core problem is that if `scatter_elem_sz` is set to an invalid value (zero, negative, or a large number) by a user via sysfs, this can lead to unexpected behavior, including integer overflow and out-of-bounds memory access during scatter-gather list building. The current patch attempts to address a specific crash scenario identified in the bug report.
The suggested approach, which includes casts to `(int)PAGE_SIZE`, the addition of `num = PAGE_SIZE`, and clamping `order` with `min_t`, directly addresses a bug in `sg_build_indirect()` by correcting the missing local variable update and preventing out-of-bounds allocation sizes. These problems stem from code written in 2006 by Douglas Gilbert.
However, the real "maintainer taste" issue is the location of the fix. The current patch is essentially a bandage applied to a pre-existing design flaw. Instead of validating `scatter_elem_sz` at the point of *use* (inside `sg_build_indirect()`), the validation should happen at the point of *set* (when the module parameter is set). Implementing a `.set` callback, such as `module_param_cb()`, or using `param_set_uint_minmax` to validate `scatter_elem_sz` with an appropriate range check (from `PAGE_SIZE` up to `PAGE_SIZE << MAX_PAGE_ORDER`), would shift the responsibility of ensuring the validity of `scatter_elem_sz` from the I/O path to the module parameter handling logic. This prevents ever allowing invalid values to be used by the driver at all, and thus it makes the code much cleaner and robust.
In its current state, the patch is fixing a bug but *also* perpetuates a suboptimal design that validates in the I/O data path rather than at the parameter setting. The fix, while technically correct in the sense that it solves a specific crash, is still a "band-aid" because it fails to address the root architectural issue. The code by Douglas Gilbert would have been cleaner with the validation on parameter set (which was a valid fix for 2006, when module parameters were not fully baked).
Therefore, because this patch fixes the crash using a band-aid style approach, I will not approve it for upstream submission.
**ReviewApproved=false**
**ReviewComments: While the patch does fix the reported crash, the fix is applied in the wrong layer. The preferred approach is to validate the `scatter_elem_sz` module parameter in the `.set` callback function (e.g., using `module_param_cb` or `param_set_uint_minmax`) during module parameter setting, thus preventing the invalid state from ever being created and preventing the necessity of validation within `sg_build_indirect`. Additionally, the code needs to be cleaned of signed-unsigned comparisons, because it makes the code less robust and maintainable.**
|
| 334/5 |
2026/09/09 18:02 |
tool |
grepper |
0m
Error:
Args: map[Expression:int param_set_int\( PathPrefix:kernel/]
Results:
|
| 335/5 |
2026/09/09 18:02 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 72977
output: 30
thoughts: 20
Thoughts: Here's my thought process, as if I were working through this:
**Locating `param_set_int`**
Okay, so I need to track down the definition of `param_set_int`. Given that it's clearly a kernel function dealing with parameters, my first instinct is to look within the kernel's parameter handling code. That likely means digging into `kernel/params.c`. It's a pretty standard location for that kind of functionality, and a good starting point. I'll get that file open and start looking for the declaration.
|
| 336/5 |
2026/09/09 18:02 |
tool |
grepper |
0m
Error:
Args: map[Expression:param_set_int PathPrefix:kernel/params.c]
Results:
|
| 337/5 |
2026/09/09 18:02 |
llm |
patch-reviewer-compressor |
0m
Model:
Reply: ### 1. Approaches Tried and Their Results
* **Evaluated the Crash Report and Root Cause:**
* Crash: UBSAN shift-out-of-bounds in `sg_build_indirect()` (`drivers/scsi/sg.c:1887:13`), shift exponent 64 is too large for 32-bit `int`.
* Trigger: writing `"0"` to sysfs node `/sys/module/sg/parameters/scatter_elem_sz`.
* In `sg_build_indirect()`:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
When `scatter_elem_sz == 0`, `num` is 0. The `if (num < PAGE_SIZE)` executes and updates `scatter_elem_sz` and `scatter_elem_sz_prev`, but fails to update local variable `num`.
* `get_order(0)`: `size--` underflows to `~0UL`, shifted right by `PAGE_SHIFT` (12) gives `0x000fffffffffffff`, `fls64()` yields 52. `order = 52`.
* `PAGE_SHIFT + order = 12 + 52 = 64`. Evaluating `1 << 64` on 32-bit literal `1` triggers UBSAN shift-out-of-bounds.
* Signed vs. Unsigned bug: `PAGE_SIZE` is `(_AC(1,UL) << CONFIG_PAGE_SHIFT)` (`unsigned long`). In `if (scatter_elem_sz < PAGE_SIZE)` and `if (num < PAGE_SIZE)`, if `scatter_elem_sz` or `num` is negative (e.g. `-1`), C integer promotion promotes `-1` to `(unsigned long)-1` (`0xffffffffffffffffUL`), causing `num < PAGE_SIZE` to evaluate to `false`, bypassing the clamp completely and passing negative/huge values to `get_order()`.
* **Historical Git Analysis of `drivers/scsi/sg.c`:**
* Commit `6460e75a104d` ("*[SCSI] sg: fixes for large page_size*", 2006): introduced `scatter_elem_sz`, `scatter_elem_sz_prev`, and the inline check in `sg_build_indirect()`.
* Commit `10db10d144c0` ("*sg: convert the indirect IO path to use the block layer*", 2008): updated indirect IO path to use page arrays and `get_order()`.
* Commit `d06a310b45e1` ("*scsi: sg: Resolve soft lockup issue when opening /dev/sgX*", 2026): solved an identical parameter issue with `def_reserved_size` (`echo -1 > /sys/module/sg/parameters/def_reserved_size`). The fix used `module_param_cb` with a custom `def_reserved_size_set()` validator rejecting negative and out-of-range values at the sysfs boundary (`-EINVAL`/`-ERANGE`), reviewed by Bart Van Assche and signed off by Martin K. Petersen.
* **Analysis of Proposed Patch Diff:**
```diff
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..24d29a150 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1667,7 +1667,7 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
@@ -1875,14 +1875,16 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
+ if (num < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
+ num = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
### 2. Current Hypotheses and Architectural Evaluation
* **Maintainer Taste / Invariant Shift vs. Band-Aid:**
* **Input Validation at Boundary:** Permitting invalid values (`0`, negative values, or values exceeding max page allocation) into `/sys/module/sg/parameters/scatter_elem_sz` and then checking/patching them dynamically inside the I/O fast path `sg_build_indirect()` is an anti-pattern.
* In `sg.c`, `def_reserved_size` was fixed via `module_param_cb` (`def_reserved_size_set`) in commit `d06a310b45e1`. `scatter_elem_sz` should ideally follow the exact same subsystem pattern: validating and clamping/rejecting in a `scatter_elem_sz_ops` callback at the sysfs parameter boundary.
* However, `sg_build_indirect()` already has legacy logic dating back to 2006 to handle runtime updates to `scatter_elem_sz`.
* In the proposed patch:
1. It fixes the local omission `num = PAGE_SIZE;`.
2. It casts `(int)PAGE_SIZE` to fix signed comparison against `unsigned long PAGE_SIZE`.
3. It caps `order` using `order = min_t(int, order, MAX_PAGE_ORDER);`.
* **Critical Issues to Evaluate on the Proposed Patch:**
* Casting `(int)PAGE_SIZE` across both functions: is type casting `PAGE_SIZE` idiomatic kernel C, or should `scatter_elem_sz` be `unsigned int` or validated with `kstrtouint` / `min_t` / `module_param_cb`?
* Does `order = min_t(int, order, MAX_PAGE_ORDER);` prevent overflow? If `order == MAX_PAGE_ORDER` (10) and `PAGE_SHIFT == 12`, `PAGE_SHIFT + order = 22`. `1 << 22` is 4MB, which fits well within 32-bit `int`.
* Is validating in `sg_build_indirect` a violation of "The Sentinel Test (Caller vs. Callee Responsibility)" and "Deterministic Decision Trigger Matrix"?
The parameter setting interface is the ingress/entry point. Allowing sysfs to store `0` or negative values and then having the leaf function perform defensive normalization violates the principle: "moving dynamic runtime checks into static typestate guarantees" and "reject at the boundary".
* Data Race Hazard: modifying `scatter_elem_sz` and `scatter_elem_sz_prev` in `sg_build_indirect()` is unprotected by locks across concurrent `open` and I/O calls.
### 3. Key Files, Functions, and Structs
* `drivers/scsi/sg.c`:
* `scatter_elem_sz` and `scatter_elem_sz_prev` (lines 94-95):
```c
static int scatter_elem_sz = SG_SCATTER_SZ;
static int scatter_elem_sz_prev = SG_SCATTER_SZ;
```
* `def_reserved_size_set` & `def_reserved_size_ops` (lines 1627-1652):
Standard idiom established in `sg.c` for validating module parameters via `module_param_cb`.
* `init_sg()` (lines 1666-1675):
Initializes module; currently checks `if (scatter_elem_sz < PAGE_SIZE)`.
* `sg_build_indirect()` (lines 1854-1918):
Allocates pages for indirect scatter-gather buffer based on `scatter_elem_sz`.
* `include/asm-generic/getorder.h`:
* `get_order(unsigned long size)`: undefined behavior when `size == 0`.
* `include/linux/mmzone.h`:
* `MAX_PAGE_ORDER`: default 10. `alloc_pages()` triggers `WARN_ON_ONCE` if `order > MAX_PAGE_ORDER`.
### 4. Watch for Loops & Next Actions
* No tool call loops occurred.
* Determine whether the patch should be approved under the single-patch constraint or rejected with feedback requiring a `module_param_cb` parameter validator (following `def_reserved_size` design in `d06a310b45e1`) and/or proper typing, versus approving the localized fix in `sg_build_indirect()`.
Tokens:
input: 62335
output: 2281
thoughts: 0
|
| 338/5 |
2026/09/09 18:02 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 26977
output: 33
thoughts: 26
Thoughts: Here's my thought process, as if I were considering this myself:
**Tracing Down Parameter Definitions in the Kernel**
Okay, so I need to figure out where `STANDARD_PARAM_DEF` or `param_ops_int` are defined in the kernel source, specifically `kernel/params.c`. That's the obvious starting point. I'm assuming these are macro or struct definitions related to parameter handling, and `kernel/params.c` sounds like the right place to start looking, given my familiarity with how the kernel organizes its source code. I'm probably looking at macros that are either pre-processing definitions related to other structs, maybe for integer parameters. Now let's crack open that file and search.
|
| 339/5 |
2026/09/09 18:02 |
tool |
read-file |
0m
Args: map[File:kernel/params.c FirstLine:230 LineCount:40]
Results: map[Contents: 230: EXPORT_SYMBOL(param_get_##name); \
231: EXPORT_SYMBOL(param_ops_##name)
232:
233:
234: STANDARD_PARAM_DEF(byte, unsigned char, "%hhu", kstrtou8);
235: STANDARD_PARAM_DEF(short, short, "%hi", kstrtos16);
236: STANDARD_PARAM_DEF(ushort, unsigned short, "%hu", kstrtou16);
237: STANDARD_PARAM_DEF(int, int, "%i", kstrtoint);
238: STANDARD_PARAM_DEF(uint, unsigned int, "%u", kstrtouint);
239: STANDARD_PARAM_DEF(long, long, "%li", kstrtol);
240: STANDARD_PARAM_DEF(ulong, unsigned long, "%lu", kstrtoul);
241: STANDARD_PARAM_DEF(ullong, unsigned long long, "%llu", kstrtoull);
242: STANDARD_PARAM_DEF(hexint, unsigned int, "%#08x", kstrtouint);
243:
244: int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
245: unsigned int min, unsigned int max)
246: {
247: unsigned int num;
248: int ret;
249:
250: if (!val)
251: return -EINVAL;
252: ret = kstrtouint(val, 0, &num);
253: if (ret)
254: return ret;
255: if (num < min || num > max)
256: return -EINVAL;
257: *((unsigned int *)kp->arg) = num;
258: return 0;
259: }
260: EXPORT_SYMBOL_GPL(param_set_uint_minmax);
261:
262: int param_set_charp(const char *val, const struct kernel_param *kp)
263: {
264: char *tmp;
265: size_t len, maxlen = 1024;
266:
267: len = strnlen(val, maxlen + 1);
268: if (len == maxlen + 1) {
269: pr_err("%s: string parameter too long\n", kp->name);
]
|
| 340/5 |
2026/09/09 18:02 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 27911
output: 30
thoughts: 216
Thoughts: **Analyzing Integer Parameter Validation**
Okay, so I'm looking at how this integer parameter, let's call it `scatter_elem_sz`, is handled. The current implementation uses `kstrtoint` for parsing the string input. Now, `kstrtoint` is known for its behavior; it converts a string to an integer, but crucially, it returns `-ERANGE` on overflow. Therefore, an input like `2147483648` (which exceeds the maximum `int`) *should* trigger an error. However, a user writing `-1` or `0` will succeed with `kstrtoint` because it's in the range of `int` - it just results in `-1` and `0` respectively being stored.
That's when it clicked! I need to validate the input against a min and max value, not just the string conversion!
Hold on… *param_set_uint_minmax*! That's it! It's a kernel helper specifically designed for module parameters that require a minimum and maximum value.
The real question is, can I use `param_set_uint_minmax` with `module_param_cb`? Let me see how `param_set_uint_minmax` is used throughout the kernel to verify it's the right choice, and how it's best implemented to correctly guard against out-of-bounds input. I'll search for its usage across the codebase.
|
| 341/5 |
2026/09/09 18:03 |
tool |
grepper |
0m
Args: map[Expression:param_set_uint_minmax PathPrefix:drivers/]
Results: map[Output:drivers/block/ublk_drv.c=5945=static int ublk_set_max_unprivileged_ublks(const char *buf,
--
drivers/block/ublk_drv.c-5947-{
drivers/block/ublk_drv.c:5948: return param_set_uint_minmax(buf, kp, 0, UBLK_MAX_UBLKS);
drivers/block/ublk_drv.c-5949-}
--
drivers/nvme/host/pci.c=341=static int io_queue_depth_set(const char *val, const struct kernel_param *kp)
drivers/nvme/host/pci.c-342-{
drivers/nvme/host/pci.c:343: return param_set_uint_minmax(val, kp, NVME_PCI_MIN_QUEUE_SIZE,
drivers/nvme/host/pci.c-344- NVME_PCI_MAX_QUEUE_SIZE);
--
drivers/ufs/core/ufs-mcq.c=40=static int rw_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-41-{
drivers/ufs/core/ufs-mcq.c:42: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_RW_QUEUES,
drivers/ufs/core/ufs-mcq.c-43- num_possible_cpus());
--
drivers/ufs/core/ufs-mcq.c=56=static int read_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-57-{
drivers/ufs/core/ufs-mcq.c:58: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_READ_QUEUES,
drivers/ufs/core/ufs-mcq.c-59- num_possible_cpus());
--
drivers/ufs/core/ufs-mcq.c=72=static int poll_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-73-{
drivers/ufs/core/ufs-mcq.c:74: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_POLL_QUEUES,
drivers/ufs/core/ufs-mcq.c-75- num_possible_cpus());
--
drivers/ufs/core/ufs-txeq.c=25=static int txeq_gear_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-txeq.c-26-{
drivers/ufs/core/ufs-txeq.c:27: return param_set_uint_minmax(val, kp, UFS_HS_G1, UFS_HS_GEAR_MAX);
drivers/ufs/core/ufs-txeq.c-28-}
--
drivers/ufs/core/ufs-txeq.c=47=static int txeq_setting_sel_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-txeq.c-48-{
drivers/ufs/core/ufs-txeq.c:49: return param_set_uint_minmax(val, kp, 0, 1);
drivers/ufs/core/ufs-txeq.c-50-}
--
drivers/ufs/core/ufshcd.c=125=static int uic_cmd_timeout_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufshcd.c-126-{
drivers/ufs/core/ufshcd.c:127: return param_set_uint_minmax(val, kp, UIC_CMD_TIMEOUT_DEFAULT,
drivers/ufs/core/ufshcd.c-128- UIC_CMD_TIMEOUT_MAX);
--
drivers/ufs/core/ufshcd.c=142=static int dev_cmd_timeout_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufshcd.c-143-{
drivers/ufs/core/ufshcd.c:144: return param_set_uint_minmax(val, kp, QUERY_REQ_TIMEOUT_MIN,
drivers/ufs/core/ufshcd.c-145- QUERY_REQ_TIMEOUT_MAX);
]
|
| 342/5 |
2026/09/09 18:03 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 29619
output: 35
thoughts: 78
Thoughts: Okay, here's my take on those thoughts, framed as my own mental processing:
**Examining Driver Parameter Validation**
Right, `param_set_uint_minmax()` is everywhere in driver code. It's a workhorse for ensuring sensible parameter ranges, I see it constantly. Now, I should check out `scatter_elem_sz`, specifically in `drivers/scsi/sg.c`. Hmm, what's this `scatter_elem_sz`? I'm drawing a blank, need a quick refresher. Okay, let me jump to lines 80-100 in `drivers/scsi/sg.c` and figure out what we're dealing with.
|
| 343/5 |
2026/09/09 18:03 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:80 LineCount:30]
Results: map[Contents: 80: #define SG_MAX_CDB_SIZE 252
81:
82: #define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
83:
84: /* N.B. This variable is readable and writeable via
85: * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
86: * of this size (or less if there is not enough memory) will be reserved
87: * for use by this file descriptor.
88: */
89:
90: /* picks up init parameter */
91: static int def_reserved_size = SG_DEF_RESERVED_SIZE;
92: static int sg_allow_dio = SG_ALLOW_DIO_DEF;
93:
94: static int scatter_elem_sz = SG_SCATTER_SZ;
95: static int scatter_elem_sz_prev = SG_SCATTER_SZ;
96:
97: #define SG_SECTOR_SZ 512
98:
99: static int sg_add_device(struct device *);
100: static void sg_remove_device(struct device *);
101:
102: static DEFINE_IDR(sg_index_idr);
103: static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
104: file descriptor list for device */
105:
106: static struct class_interface sg_interface = {
107: .add_dev = sg_add_device,
108: .remove_dev = sg_remove_device,
109: };
]
|
| 344/5 |
2026/09/09 18:03 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 30369
output: 33
thoughts: 37
Thoughts: Okay, let's dive into this. Here's how I'd approach this task, as if these were my internal thoughts:
**Analyzing `scatter_elem_sz` and `scatter_elem_sz_prev` in `drivers/scsi/sg.c`**
Alright, time to get my hands dirty. I need to comprehensively understand how `scatter_elem_sz` and `scatter_elem_sz_prev` are used within the `drivers/scsi/sg.c` file. This means I'll need to meticulously trace every instance of those variables. I'm not just looking for their declaration; I need to follow their usage, how they're read, written, and what conditions influence those operations.
I'll be paying close attention to any potential pitfalls, especially regarding race conditions, potential overflow scenarios, or any logic that could lead to unexpected behavior. The SCSI subsystem is critical; any errors in this area can be catastrophic. I need to understand the intent of these variables: are they used for size calculations, tracking offsets, buffering, or something else entirely? The comments (or lack thereof!) in the code will be my primary guide. I'll need to form a detailed understanding of how these variables contribute to the scatter-gather functionality, making sure they're being managed and used correctly within this crucial driver. Any inconsistencies need to be flagged for further investigation. This will be a methodical and focused inspection.
|
| 345/5 |
2026/09/09 18:03 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 346/5 |
2026/09/09 18:03 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 31764
output: 37
thoughts: 65
Thoughts: Okay, here's my take on those initial observations, summarized in the first person, as requested:
**Kernel Scatter/Gather Observation and Review**
Alright, *that* caught my eye! I'm seeing something really specific here. I'm taking a look through this kernel code, and I've zeroed in on the usage of `scatter_elem_sz` and `scatter_elem_sz_prev`. And wouldn't you know it, these variables are only being used in a couple of spots, *period*. This immediately tells me we need to pay close attention to *exactly* what's happening in those locations. This limited scope of usage could mean the variables are central to a specific operation, or that they represent an area where a subtle bug might have snuck in, or even that they're a remnant of some refactoring. Time to dig in...
Let's read the entirety of the `sg_build_indirect()` function, from lines 1854 to 1925, and understand exactly how these variables are being used. No shortcuts, I need to get the whole picture. I'm going to carefully step through each line, keeping the larger context of scatter/gather DMA in mind. I'll be looking for how the sizes relate to the segment building and I'm looking for where the state of those variables changes. Let's see what we can find.
|
| 347/5 |
2026/09/09 18:03 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1854 LineCount:70]
Results: map[Contents:1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
]
|
| 348/5 |
2026/09/09 18:03 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 33417
output: 27
thoughts: 2639
Thoughts: **Analyzing the SG Module's Indirect Scatter-Gather Build and the Proposed Patch**
Okay, let's break this down. I'm looking at the `sg_build_indirect()` function, and the crash report is screaming a shift-out-of-bounds error. The root cause is pretty clear: a user setting `scatter_elem_sz` to zero through `/sys/module/sg/parameters/scatter_elem_sz`. This led to `get_order(0)` returning a massive order, which, when shifted, overflowed. The original code in `out:` tries to free pages allocated with the faulty `order`, but that doesn't solve the underlying problem.
The initial fix proposed seems to target the vulnerability in how `scatter_elem_sz` is handled. It seems the code was not checking the value correctly, and because `num` wasn't updated in the `if` block, we got the UB. Let's make sure the fix addresses it!
1. * The original code has a logical flaw: if `num` is smaller than `PAGE_SIZE`, the assignment to `scatter_elem_sz` doesn't affect `num`. The updated `num = PAGE_SIZE;` ensures `get_order` calculates with `PAGE_SIZE`, avoiding the massive order issue.
2. * The `(int)PAGE_SIZE` cast is essential to guard against integer overflow during comparison. This protects against scenarios where `scatter_elem_sz` might become a negative value (or, more accurately, a large unsigned value interpreted as a negative `int`) if an unsigned long is compared to an `int`. This guards against malicious attempts to set a negative value.
Now, the crucial question: Is this patch acceptable as a standalone fix? It correctly fixes the UB issue. But, does it violate the kernel architectural guidelines? The important part is, based on the architectural checklist, I'm not seeing any violations here.
The patch *does not* touch a destructor or teardown where a sentinel guard might be a smell of uninitialized states.
Therefore, this patch should be suitable for upstream submission as a single-patch fix.
|
| 349/5 |
2026/09/09 18:03 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 350/5 |
2026/09/09 18:03 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 37860
output: 28
thoughts: 129
Thoughts: **Investigating a Recent Commit**
Okay, so I'm looking at commit `d06a310b45e1`. Right, let's trace this thing back. I'll start by figuring out what the context of that commit was – what other commits were around it, when it was introduced, the usual. Ah, here's a link: `https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com`. That could give me some clues. Time to check `git log` around that timeframe. I'll look for commits related to that patch series, specifically the ones before and after – so maybe `3034148-2` or `3034148-1`. With this, I should be able to reconstruct the development history and understand the changes more clearly.
|
| 351/5 |
2026/09/09 18:03 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
]
|
| 352/5 |
2026/09/09 18:03 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 38375
output: 25
thoughts: 45
Thoughts: Here's my attempt at summarizing the thought process, as if I were an expert:
**Diving into the Code History**
Okay, so I'm being prompted to examine commit `50209dec14f8` and then `3033c471aaf6`. Right. Let's start with `50209dec14f8`. I need to understand the context, the rationale behind the change. I'll need to see the diff, the files modified, and perhaps the commit message. I'm going to quickly assess: What's the scope of the change? Is it a bug fix, a feature addition, a refactor, or something else entirely? What modules or systems are impacted? Is there a clear logical thread to the changes? What kind of testing was done to validate the changes. I'll be looking for potential side-effects or regressions based on my understanding of the codebase's architecture and the project's overall objectives. I also want to consider how this commit relates to the subsequent one. I need to be efficient and find any clues on the reasons and impacts.
|
| 353/5 |
2026/09/09 18:03 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 50209dec14f8c594a9ef26237b7e7ddd39e12a40
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:44 2026 +0800
scsi: sg: Remove deprecated sg-big-buff
These deprecated sysctl has been broken since commit 26d1c80fd61e
("scsi/sg: move sg-big-buff sysctl to scsi/sg.c") and nobody has found
this. I believe it's time to remove it, which will allow us to clean up a
significant amount of code.
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-4-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index f38d36fbeef3..2b4b2a1a8e44 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -81,14 +81,14 @@ static int sg_proc_init(void);
#define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
-static int sg_big_buff = SG_DEF_RESERVED_SIZE;
/* N.B. This variable is readable and writeable via
- /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
- of this size (or less if there is not enough memory) will be reserved
- for use by this file descriptor. [Deprecated usage: this variable is also
- readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into
- the kernel (i.e. it is not a module).] */
-static int def_reserved_size = -1; /* picks up init parameter */
+ * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
+ * of this size (or less if there is not enough memory) will be reserved
+ * for use by this file descriptor.
+ */
+
+/* picks up init parameter */
+static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
@@ -1663,35 +1663,6 @@ MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
-#ifdef CONFIG_SYSCTL
-#include <linux/sysctl.h>
-
-static const struct ctl_table sg_sysctls[] = {
- {
- .procname = "sg-big-buff",
- .data = &sg_big_buff,
- .maxlen = sizeof(int),
- .mode = 0444,
- .proc_handler = proc_dointvec,
- },
-};
-
-static struct ctl_table_header *hdr;
-static void register_sg_sysctls(void)
-{
- if (!hdr)
- hdr = register_sysctl("kernel", sg_sysctls);
-}
-
-static void unregister_sg_sysctls(void)
-{
- unregister_sysctl_table(hdr);
-}
-#else
-#define register_sg_sysctls() do { } while (0)
-#define unregister_sg_sysctls() do { } while (0)
-#endif /* CONFIG_SYSCTL */
-
static int __init
init_sg(void)
{
@@ -1701,10 +1672,6 @@ init_sg(void)
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
- if (def_reserved_size >= 0)
- sg_big_buff = def_reserved_size;
- else
- def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1716,7 +1683,6 @@ init_sg(void)
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
- register_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
@@ -1731,7 +1697,6 @@ init_sg(void)
static void __exit
exit_sg(void)
{
- unregister_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
remove_proc_subtree("scsi/sg", NULL);
#endif /* CONFIG_SCSI_PROC_FS */
@@ -2207,10 +2172,8 @@ sg_add_sfp(Sg_device * sdp)
write_unlock_irqrestore(&sdp->sfd_lock, iflags);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_add_sfp: sfp=0x%p\n", sfp));
- if (unlikely(sg_big_buff != def_reserved_size))
- sg_big_buff = def_reserved_size;
- bufflen = min_t(int, sg_big_buff,
+ bufflen = min_t(int, def_reserved_size,
max_sectors_bytes(sdp->device->request_queue));
sg_build_reserve(sfp, bufflen);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
@@ -2438,7 +2401,7 @@ sg_proc_write_adio(struct file *filp, const char __user *buffer,
static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)
{
- return single_open(file, sg_proc_seq_show_int, &sg_big_buff);
+ return single_open(file, sg_proc_seq_show_int, &def_reserved_size);
}
static ssize_t
@@ -2455,7 +2418,7 @@ sg_proc_write_dressz(struct file *filp, const char __user *buffer,
if (err)
return err;
if (k <= 1048576) { /* limit "big buff" to 1 MB */
- sg_big_buff = k;
+ def_reserved_size = k;
return count;
}
return -ERANGE;
@@ -2628,7 +2591,7 @@ static int sg_proc_seq_show_debug(struct seq_file *s, void *v)
if (it && (0 == it->index))
seq_printf(s, "max_active_device=%d def_reserved_size=%d\n",
- (int)it->max, sg_big_buff);
+ (int)it->max, def_reserved_size);
read_lock_irqsave(&sg_index_lock, iflags);
sdp = it ? sg_lookup_dev(it->index) : NULL;
]
|
| 354/5 |
2026/09/09 18:03 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 40759
output: 27
thoughts: 1327
Thoughts: **Analyzing a Potential Vulnerability in the SCSI SG Driver**
Okay, here's what's running through my head as I examine this. I see this series of commits from Yang Erkun, focusing on the SCSI SG driver. The first thing that jumps out is that he fixed a soft lockup issue related to `def_reserved_size` by using `module_param_cb` for validation. Clever. This prevents users from writing arbitrary, and therefore dangerous, integer values to the parameter through sysfs. It's clear that `-1` was causing havoc when used to initialize `def_reserved_size` in the `sg_add_sfp()` and therefore the code needs to prevent it at the source.
Then, my gaze shifted to `scatter_elem_sz`, and I immediately see a mirror image of the problem with `def_reserved_size`. The same sysfs interface for writing directly to a global variable, `scatter_elem_sz`, without any safeguards. Writing `0` or `-1` is going to cause a problem in `sg_build_indirect`, because the value is later read in that same function. Now, this is something I need to look into and fix, I would be surprised if that wasn't a problem.
The proposed patch is definitely an attempt to address this issue. The code is changing the logic in `sg_build_indirect()`, specifically lines related to `scatter_elem_sz` and `order`. It looks like there's an attempt to ensure `scatter_elem_sz` is at least `PAGE_SIZE` and limit the `order` to `MAX_PAGE_ORDER`. But here's where my expert instincts kick in. Is this a "band-aid" fix, or does it address the architectural problem? According to the architectural guidelines, "Naive patches often introduce defensive sentinel guards (e.g., ad-hoc if (!ptr) return; checks, status flags, or suppressed warnings) directly at the point of failure. While locally avoiding crashes, they degrade subsystem architecture by leaving uninitialized states reachable. Maintainer "good taste" solves the root cause by shifting invariants (making invalid states unrepresentable) and moving dynamic runtime checks into static typestate guarantees."
Where is the root cause? The crash happened inside `sg_build_indirect()`, when calculating `ret_sz`. The patch is *modifying* that calculation inside `sg_build_indirect()`. If we are using `module_param_cb` for `def_reserved_size`, wouldn't validating at the sysfs boundary make more sense? It looks like the patch is addressing the *point of failure* instead of the root cause, which is the lack of validation! If we validated `scatter_elem_sz` at the sysfs layer, then the checks inside `sg_build_indirect()` might not even be necessary!
Also, I'm questioning the use of `scatter_elem_sz_prev`. Why is this global variable necessary in the first place? And, if the value can be invalid, why isn't this validated when the value changes? I need to go deeper. A quick `git blame` on that variable, or the original commit, should provide some clarity on why that variable is even there.
|
| 355/5 |
2026/09/09 18:04 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 356/5 |
2026/09/09 18:04 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 47208
output: 26
thoughts: 822
Thoughts: **Analyzing the Scatter/Gather List Optimization**
Okay, let's dive into this old commit, 6460e75a104d from 2006. It's about optimizing scatter-gather list allocation, specifically looking at Douglas Gilbert's code. I'm seeing changes related to `scatter_elem_sz` and `scatter_elem_sz_prev`, and how `sg_page_malloc` is used. My intuition tells me this is about managing the size of the memory chunks allocated for I/O.
My first thought is that the original version of `sg_page_malloc` in 2006, passed a value for `num` which determined the requested size (`rqSz`). It looks like if `num` was smaller than `PAGE_SIZE`, the allocation would *start* with a page size allocation via `alloc_pages` using order zero. That means the allocation was *rounded up* to at least a full page if it was smaller than a page.
Looking at `sg_build_indirect`, the old implementation recomputed `num` within the loop, using `scatter_elem_sz_prev`. Remember this was happening inside the loop, using `num = min(rem_sz, PAGE_SIZE)`. Crucially, it did *not* call `get_order` on this value *before* the loop. Essentially, `num` was re-written inside the loop, never relying on a previous value.
In 2006, when `scatter_elem_sz` was initially 0, `scatter_elem_sz_prev` was initialized to `PAGE_SIZE`, and the code within the loop then did: `num = min(rem_sz, PAGE_SIZE)`. The next step in this loop was to call `sg_page_malloc(PAGE_SIZE, ...)` using order 0. Therefore, the old code in 2006 *did not* have a bug in it.
Now, let me examine this later commit 10db10d144c0 ("sg: convert the indirect IO path to use the block layer") and see how this was changed.
|
| 357/5 |
2026/09/09 18:04 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 358/5 |
2026/09/09 18:04 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 58168
output: 458
thoughts: 2511
Thoughts: **Analyzing a Scatter-Gather Driver Patch: A Maintainer's Perspective**
Okay, so I'm diving into this proposed patch for the SCSI scatter-gather driver. My initial reaction? This is a bit of a mixed bag. Fujita Tomonori's commit from back in 2008 seems to be the root of this. He removed `sg_page_malloc` and replaced it with this `get_order(num)` approach, but it looks like he missed a crucial detail when `num` is less than `PAGE_SIZE`. The value of `num` isn't updated, which means we might end up with `get_order(0)`, resulting in potential allocation problems.
The patch's changes, especially the `min_t` call and the explicit cast to `(int)PAGE_SIZE`, raise some serious questions for me as a maintainer. Why are we trying to sanitize a module parameter *within* a critical function like `sg_build_indirect()`? This seems like a band-aid solution. I've seen this before in other similar contexts like the `def_reserved_size` fix from January 2026, which took the correct approach by validating the parameter using `module_param_cb` during write time. This way we prevent the driver from ever entering an invalid state.
The core of the issue is allowing userspace to write arbitrary values to `scatter_elem_sz` in the first place. Wouldn't it be better to prevent invalid values from being written in the first place, using mechanisms like `module_param_cb` or `param_set_uint_minmax` for parameter validation? This is what I would call "good taste" in the context of kernel architectural design, making invalid states unrepresentable.
And it is not just this specific issue. There is also the concurrency issue. The variables `scatter_elem_sz` and `scatter_elem_sz_prev` are modified without any locks within `sg_build_indirect()`. This could lead to serious problems with multiple threads accessing `/dev/sg` concurrently. If this variable is validated in `module_param_cb`, this problem would be avoided.
Now, let's play devil's advocate and consider the patch's acceptance. The single-patch constraint is the key here. This patch is isolated to `drivers/scsi/sg.c`, which makes it a candidate for acceptance, assuming the patch correctly fixes the bug, does not introduce any new issues, and avoids sentinel band-aids within its local scope. However, these points also are arguable since the `min_t` and `(int)PAGE_SIZE` seem to be sentinel guards to me. The root of the problem isn't fixed, just worked around.
In short, there is a lot to consider.
|
| 359/5 |
2026/09/09 18:04 |
tool |
codeexpert |
2m
Args: map[Question:In drivers/scsi/sg.c, the module parameter scatter_elem_sz can be set to 0 or negative via sysfs /sys/module/sg/parameters/scatter_elem_sz.
When opened, sg_build_indirect() executes:
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
When scatter_elem_sz is 0, num is not updated, get_order(0) is called, resulting in undefined behavior and UBSAN shift-out-of-bounds in 1 << (PAGE_SHIFT + order).
Also, if scatter_elem_sz is negative, num < PAGE_SIZE is false due to unsigned comparison (PAGE_SIZE is unsigned long).
Compare two approaches to fix this:
1. Local fix in sg.c:
In init_sg and sg_build_indirect, change check to (int)PAGE_SIZE, add num = PAGE_SIZE, and cap order with min_t(int, order, MAX_PAGE_ORDER).
2. Architectural fix:
Use module_param_cb (similar to def_reserved_size in commit d06a310b45e1) to validate scatter_elem_sz upon writing in sysfs / module load (rejecting values < PAGE_SIZE or > max supported size), preventing invalid values from entering scatter_elem_sz in the first place.
From the perspective of upstream Linux kernel maintainer taste and architecture, evaluate approach 1 vs approach 2. Is approach 1 considered an acceptable clean fix or a band-aid with code smell? Would maintainers require approach 2?]
Results: map[Answer:From upstream Linux kernel maintainer taste and architecture, Approach 1 is considered a band-aid with distinct code smells, whereas Approach 2 is the correct architectural fix that upstream maintainers would require.]
|
| 360/6 |
2026/09/09 18:04 |
agent |
codeexpert |
2m
Model:
Results: map[Answer:From upstream Linux kernel maintainer taste and architecture, Approach 1 is considered a band-aid with distinct code smells, whereas Approach 2 is the correct architectural fix that upstream maintainers would require.]
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.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
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: In drivers/scsi/sg.c, the module parameter scatter_elem_sz can be set to 0 or negative via sysfs /sys/module/sg/parameters/scatter_elem_sz.
When opened, sg_build_indirect() executes:
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
When scatter_elem_sz is 0, num is not updated, get_order(0) is called, resulting in undefined behavior and UBSAN shift-out-of-bounds in 1 << (PAGE_SHIFT + order).
Also, if scatter_elem_sz is negative, num < PAGE_SIZE is false due to unsigned comparison (PAGE_SIZE is unsigned long).
Compare two approaches to fix this:
1. Local fix in sg.c:
In init_sg and sg_build_indirect, change check to (int)PAGE_SIZE, add num = PAGE_SIZE, and cap order with min_t(int, order, MAX_PAGE_ORDER).
2. Architectural fix:
Use module_param_cb (similar to def_reserved_size in commit d06a310b45e1) to validate scatter_elem_sz upon writing in sysfs / module load (rejecting values < PAGE_SIZE or > max supported size), preventing invalid values from entering scatter_elem_sz in the first place.
From the perspective of upstream Linux kernel maintainer taste and architecture, evaluate approach 1 vs approach 2. Is approach 1 considered an acceptable clean fix or a band-aid with code smell? Would maintainers require approach 2?
|
| 361/7 |
2026/09/09 18:04 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4486
output: 60
thoughts: 426
Thoughts: **Analyzing the Potential Issue in sg.c**
Okay, let's break this down meticulously. The crux of the matter seems to revolve around the `scatter_elem_sz` module parameter in `/sys/module/sg/parameters/scatter_elem_sz` within `drivers/scsi/sg.c`. The question highlights a vulnerability if this parameter is set to zero or negative.
My first thought is to zero in on the `sg_build_indirect()` function. It's the critical point where this parameter comes into play. From the provided code snippet, it's clear `num` is directly assigned from `scatter_elem_sz`. The interesting part is the `if (unlikely(num != scatter_elem_sz_prev))` block. The logic there *should* update `scatter_elem_sz` to `PAGE_SIZE` if `num` is less than `PAGE_SIZE`. The concern arises here: if `scatter_elem_sz` *starts* as zero, `num` is initialized to 0. Even after the conditional update, `num` will still be zero, leading to the call `get_order(0)`. That's where it potentially gets problematic.
The code assumes `num` will be positive. We know that if `scatter_elem_sz` is negative, `num < PAGE_SIZE` will be false because it does an unsigned comparison, the branch will be skipped, but `num` can still be negative.
My immediate action is to thoroughly investigate the definitions and handling of `scatter_elem_sz` and `def_reserved_size` within the `drivers/scsi/sg.c` file itself. I also need to understand the context of commit `d06a310b45e1` to see if there was some related fix or change.
I'm thinking I need some tools to help. Let's fire up some tools and get a closer look at the source code and the mentioned commit. I need to understand how these values are initialized and used in order to accurately assess the potential vulnerabilities.
|
| 362/7 |
2026/09/09 18:04 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 363/7 |
2026/09/09 18:04 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 364/7 |
2026/09/09 18:04 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7754
output: 74
thoughts: 31
Thoughts: Here's my analysis of the provided thought process, tailored for an expert audience:
**Analyzing SCSI Generic (sg) Initialization and Indirect Mapping in drivers/scsi/sg.c**
Alright, let's dive into the guts of the `sg` driver. My immediate focus is going to be the interplay between `init_sg` and `sg_build_indirect` within the `drivers/scsi/sg.c` file. I'm assuming we're dealing with SCSI Generic here, so I need to understand how the scatter-gather lists are initialized and how the driver handles indirect mapping. My immediate questions are going to be: How are the SG lists set up initially? What specific situations trigger the use of indirect mapping, and what are the performance implications? What potential race conditions or memory management issues are in play? I also want to see how this implementation interacts with the core SCSI stack; particularly how requests are submitted and completed. I'll be looking for any signs of optimization or known problem areas related to handling large I/O operations or potentially fragmented memory regions, keeping in mind the hardware context involved in indirect mappings. This is where the devil lives, so to speak.
|
| 365/7 |
2026/09/09 18:04 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1665 LineCount:40]
Results: map[Contents:1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
1675: rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1676: SG_MAX_DEVS, "sg");
1677: if (rc)
1678: return rc;
1679: rc = class_register(&sg_sysfs_class);
1680: if (rc)
1681: goto err_out;
1682: sg_sysfs_valid = 1;
1683: rc = scsi_register_interface(&sg_interface);
1684: if (0 == rc) {
1685: #ifdef CONFIG_SCSI_PROC_FS
1686: sg_proc_init();
1687: #endif /* CONFIG_SCSI_PROC_FS */
1688: return 0;
1689: }
1690: class_unregister(&sg_sysfs_class);
1691: err_out:
1692: unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
1693: return rc;
1694: }
1695:
1696: static void __exit
1697: exit_sg(void)
1698: {
1699: #ifdef CONFIG_SCSI_PROC_FS
1700: remove_proc_subtree("scsi/sg", NULL);
1701: #endif /* CONFIG_SCSI_PROC_FS */
1702: scsi_unregister_interface(&sg_interface);
1703: class_unregister(&sg_sysfs_class);
1704: sg_sysfs_valid = 0;
]
|
| 366/7 |
2026/09/09 18:04 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1865 LineCount:60]
Results: map[Contents:1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
]
|
| 367/7 |
2026/09/09 18:04 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 9737
output: 37
thoughts: 35
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing `sg_build_indirect` (Lines 1925-1950)**
Okay, let's take a closer look at what's going on within `sg_build_indirect`. Specifically, I'm focusing on lines 1925 through 1950. I want to see if anything significant jumps out in that section, perhaps related to memory allocation, error handling, or specific calculations the function performs during indirect buffer construction. I'm hoping to quickly identify any potential bottlenecks, unusual patterns, or areas that might warrant further investigation based on my prior experience with similar build functions. This could be anything from redundant operations to potential race conditions depending on the context. Let's see what these lines reveal.
|
| 368/7 |
2026/09/09 18:04 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1925 LineCount:30]
Results: map[Contents:1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
1931: static void
1932: sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
1933: {
1934: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1935: "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
1936: if (schp->pages && schp->sglist_len > 0) {
1937: if (!schp->dio_in_use) {
1938: int k;
1939:
1940: for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
1941: SCSI_LOG_TIMEOUT(5,
1942: sg_printk(KERN_INFO, sfp->parentdp,
1943: "sg_remove_scat: k=%d, pg=0x%p\n",
1944: k, schp->pages[k]));
1945: __free_pages(schp->pages[k], schp->page_order);
1946: }
1947:
1948: kfree(schp->pages);
1949: }
1950: }
1951: memset(schp, 0, sizeof (*schp));
1952: }
1953:
1954: static int
]
|
| 369/7 |
2026/09/09 18:04 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10462
output: 19
thoughts: 48
Thoughts: Okay, let's get down to brass tacks.
**Investigating `scatter_elem_sz` Usage**
Alright, I need to get a clear picture of where `scatter_elem_sz` is being used within the `sg.c` code and potentially across the entire codebase. My initial strategy is to leverage `grepper` – that trusty tool is perfect for a full-repository search. I'll fire it up and target `scatter_elem_sz` to uncover all instances of its use and understand the complete context. This will give me a comprehensive view of how this variable is integrated into the system.
|
| 370/7 |
2026/09/09 18:04 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 371/7 |
2026/09/09 18:04 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 11683
output: 20
thoughts: 31
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Investigating `SG_SCATTER_SZ`**
Alright, let's dive in. I need to understand what `SG_SCATTER_SZ` is actually defined as. It's likely a critical constant or macro related to scatter/gather operations, and understanding its value is crucial for optimizing or debugging something I'm probably working on. So, the first logical step is to quickly track down its definition. Time to unleash the `grep` – that's the fastest and most efficient way to pinpoint where `SG_SCATTER_SZ` is declared in this code base or project. I'll need to know where it is so I know its dependencies and purpose. Once I know where it's defined, I can look at its actual value and its context. Let's see what that yields.
|
| 372/7 |
2026/09/09 18:04 |
tool |
grepper |
0m
Args: map[Expression:SG_SCATTER_SZ]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1660=MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c:1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
drivers/scsi/sg.c-1662-MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
--
include/scsi/sg.h=175=typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
--
include/scsi/sg.h-249-
include/scsi/sg.h:250:#define SG_SCATTER_SZ (8 * 4096)
include/scsi/sg.h-251-/* Largest size (in bytes) a single scatter-gather list element can have.
include/scsi/sg.h:252: The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
include/scsi/sg.h-253- This value should be a power of 2 (and may be rounded up internally).
--
include/scsi/sg.h-261-#define SG_DEF_KEEP_ORPHAN 0
include/scsi/sg.h:262:#define SG_DEF_RESERVED_SIZE SG_SCATTER_SZ /* load time option */
include/scsi/sg.h-263-
]
|
| 373/7 |
2026/09/09 18:04 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 12415
output: 28
thoughts: 372
Thoughts: **Analyzing a Recent SCSI Fix**
Okay, so I'm looking at this commit, `d06a310b45e153872033dd0cf19d5a2279121099`, and it's addressing an interesting issue with `def_reserved_size` in the SCSI generic driver, `sg`. The bug is that this parameter defines the default buffer size reserved for each `Sg_fd`, and the existing validation in `sg_proc_write_dressz` is bypassed if the module parameter is modified directly. This can then lead to a soft lockup, which is never good. The fix, as expected, is to use `module_param_cb` to enforce validation and reject invalid values for `def_reserved_size`. Seems like a straightforward, but crucial, safeguard.
Hang on a minute... Let me quickly check the date on this commit. Hmm, it says January 27, 2026. Either this is a very recent commit, or maybe it is a commit that is not even in the main tree yet! Let's hope it's the former. I note that it was reviewed by Bart Van Assche, which is always a good sign, and signed off by Martin K. Petersen. Good to see the names I recognize.
I'd better take a look at the history of the sg driver code. Let me quickly execute `git log -n 5 drivers/scsi/sg.c` to see the last five commits made to that file. This should give me a better understanding of the code's recent evolution and any related changes.
|
| 374/7 |
2026/09/09 18:04 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
]
|
| 375/7 |
2026/09/09 18:04 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 13322
output: 26
thoughts: 904
Thoughts: **Analyzing the SG Driver's Scatter-Gather Element Size Handling**
Okay, let's break this down. We have a vulnerability in the `sg` driver's `scatter_elem_sz` parameter. The issue arises from the lack of input validation and how its value is used within `sg_build_indirect`. Specifically, allowing `scatter_elem_sz` to be set to 0 or a negative value via sysfs leads to undefined behavior and a UBSAN shift-out-of-bounds error.
First, let's examine the current problematic code: within `sg_build_indirect`, the code tries to adjust `scatter_elem_sz` if it's less than `PAGE_SIZE`. The core problem is in this `if (num < PAGE_SIZE)` comparison. Because `PAGE_SIZE` is an `unsigned long` and `num` is an `int`, a negative `num` will be *incorrectly* treated as a very large positive unsigned number due to usual arithmetic conversions, bypassing the expected size check. This means negative numbers will result in `scatter_elem_sz_prev` getting set to that negative value, which will result in `get_order(num)`, which can lead to unpredictable behavior. With `num` being 0, `get_order()` will also cause undefined behavior, leading to the reported error.
We're presented with two proposed fixes:
1. **Local Fix:** Modify `sg.c` directly. This approach involves changing the check to `(int)PAGE_SIZE`, adding `num = PAGE_SIZE`, and capping the calculated `order` with `min_t(int, order, MAX_PAGE_ORDER)`. While this *addresses* the immediate issue, it's a bit of a band-aid. Converting the `PAGE_SIZE` is a kludge, but does at least enable the code to be correct, and capping the order is another.
2. **Architectural Fix:** Use `module_param_cb` to validate `scatter_elem_sz` upon module load *and* during sysfs writes. This means rejecting values less than `PAGE_SIZE` or greater than a maximum supported size *at the source*. This prevents the invalid value from even entering `scatter_elem_sz` in the first place. This is architecturally sound and leverages existing kernel mechanisms, similar to what was done in commit `d06a310b45e1`.
From my perspective as an upstream maintainer, option 2 is *clearly* the preferred approach. The local fix is a code smell. It addresses the immediate issue but doesn't prevent similar problems from arising in the future. Input validation is a fundamental principle of kernel design. We *must* ensure that external inputs (like module parameters) are within expected ranges to prevent undefined behavior and security vulnerabilities. The architectural fix implements this validation at the point of entry and uses a well-established mechanism. The approach is cleaner, more robust, and prevents the problem from happening. Given the historical precedent and focus on input validation, maintainers would *absolutely* require the architectural fix (option 2). It's the right way to do things in the kernel.
|
| 376/7 |
2026/09/09 18:05 |
tool |
grepper |
0m
Args: map[Expression:get_order\( PathPrefix:include/]
Results: map[Output:include/asm-generic/getorder.h-28- */
include/asm-generic/getorder.h:29:static __always_inline __attribute_const__ int get_order(unsigned long size)
include/asm-generic/getorder.h-30-{
--
include/linux/dma-map-ops.h=143=static inline void dma_free_contiguous(struct device *dev, struct page *page,
--
include/linux/dma-map-ops.h-145-{
include/linux/dma-map-ops.h:146: __free_pages(page, get_order(size));
include/linux/dma-map-ops.h-147-}
--
include/linux/mm.h=1784=static inline unsigned int compound_order(const struct page *page)
--
include/linux/mm.h-1796- *
include/linux/mm.h:1797: * A folio is composed of 2^order pages. See get_order() for the definition
include/linux/mm.h-1798- * of order.
--
include/linux/mm_types_task.h=36=struct page_frag {
--
include/linux/mm_types_task.h-47-#define PAGE_FRAG_CACHE_MAX_SIZE __ALIGN_MASK(32768, ~PAGE_MASK)
include/linux/mm_types_task.h:48:#define PAGE_FRAG_CACHE_MAX_ORDER get_order(PAGE_FRAG_CACHE_MAX_SIZE)
include/linux/mm_types_task.h-49-struct page_frag_cache {
--
include/linux/pagemap.h=707=typedef unsigned int __bitwise fgf_t;
--
include/linux/pagemap.h-721-
include/linux/pagemap.h:722:static inline unsigned int filemap_get_order(size_t size)
include/linux/pagemap.h-723-{
--
include/linux/pagemap.h=743=static inline fgf_t fgf_set_order(size_t size)
include/linux/pagemap.h-744-{
include/linux/pagemap.h:745: unsigned int order = filemap_get_order(size);
include/linux/pagemap.h-746-
--
include/linux/xarray.h=1557=void xas_create_range(struct xa_state *);
--
include/linux/xarray.h-1559-#ifdef CONFIG_XARRAY_MULTI
include/linux/xarray.h:1560:int xa_get_order(struct xarray *, unsigned long index);
include/linux/xarray.h:1561:int xas_get_order(struct xa_state *xas);
include/linux/xarray.h-1562-void xas_split(struct xa_state *, void *entry, unsigned int order);
--
include/linux/xarray.h=1565=unsigned int xas_try_split_min_order(unsigned int order);
include/linux/xarray.h-1566-#else
include/linux/xarray.h:1567:static inline int xa_get_order(struct xarray *xa, unsigned long index)
include/linux/xarray.h-1568-{
--
include/linux/xarray.h-1571-
include/linux/xarray.h:1572:static inline int xas_get_order(struct xa_state *xas)
include/linux/xarray.h-1573-{
--
include/net/sock.h=3089=extern __u32 sysctl_rmem_default;
include/net/sock.h-3090-
include/net/sock.h:3091:#define SKB_FRAG_PAGE_ORDER get_order(32768)
include/net/sock.h-3092-DECLARE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
]
|
| 377/7 |
2026/09/09 18:05 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 15955
output: 36
thoughts: 16
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into `getorder.h`**
Okay, time to get specific. I need to refresh my understanding of how the page order calculation works at the kernel level. Specifically, I should be thinking about the memory allocation strategies and how they influence performance. Let's start with a look at `include/asm-generic/getorder.h`. This is where the core logic for determining the order of a page allocation should reside, and it's essential for understanding fragmentation and memory allocation in a given architecture. This should give me the foundation I need to understand how the allocation strategies work and how they influence performance.
|
| 378/7 |
2026/09/09 18:05 |
tool |
read-file |
0m
Args: map[File:include/asm-generic/getorder.h FirstLine:1 LineCount:50]
Results: map[Contents: 1: /* SPDX-License-Identifier: GPL-2.0 */
2: #ifndef __ASM_GENERIC_GETORDER_H
3: #define __ASM_GENERIC_GETORDER_H
4:
5: #ifndef __ASSEMBLER__
6:
7: #include <linux/compiler.h>
8: #include <linux/log2.h>
9:
10: /**
11: * get_order - Determine the allocation order of a memory size
12: * @size: The size for which to get the order
13: *
14: * Determine the allocation order of a particular sized block of memory. This
15: * is on a logarithmic scale, where:
16: *
17: * 0 -> 2^0 * PAGE_SIZE and below
18: * 1 -> 2^1 * PAGE_SIZE to 2^0 * PAGE_SIZE + 1
19: * 2 -> 2^2 * PAGE_SIZE to 2^1 * PAGE_SIZE + 1
20: * 3 -> 2^3 * PAGE_SIZE to 2^2 * PAGE_SIZE + 1
21: * 4 -> 2^4 * PAGE_SIZE to 2^3 * PAGE_SIZE + 1
22: * ...
23: *
24: * The order returned is used to find the smallest allocation granule required
25: * to hold an object of the specified size.
26: *
27: * The result is undefined if the size is 0.
28: */
29: static __always_inline __attribute_const__ int get_order(unsigned long size)
30: {
31: if (__builtin_constant_p(size)) {
32: if (!size)
33: return BITS_PER_LONG - PAGE_SHIFT;
34:
35: if (size < (1UL << PAGE_SHIFT))
36: return 0;
37:
38: return ilog2((size) - 1) - PAGE_SHIFT + 1;
39: }
40:
41: size--;
42: size >>= PAGE_SHIFT;
43: #if BITS_PER_LONG == 32
44: return fls(size);
45: #else
46: return fls64(size);
47: #endif
48: }
49:
50: #endif /* __ASSEMBLER__ */
]
|
| 379/7 |
2026/09/09 18:05 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16858
output: 38
thoughts: 1039
Thoughts: **Analyzing `sg_build_indirect` for Potential Issues**
Okay, let's break down this `sg_build_indirect` function. The first thing that jumps out is the potential for undefined behavior in `get_order(size)`. If `size` is zero, we're in trouble. The `size--` wraps, then a right shift combined with `fls64` and bit shifting into calculating `ret_sz` could lead to a 64-bit shift on a 32-bit int, triggering a shift-out-of-bounds error and UBSAN flagging that as undefined behavior.
Now, let's consider edge cases. If `num` is zero, the code goes into an `if` block where it *doesn't* update `num`. So, `num` is 0, which then calls `get_order(0)` again, leading back to the same undefined behavior. Similarly, if a negative number is used, this will also result in the same error in `get_order()`.
And, what if `scatter_elem_sz` is huge? Like, 2GB? `get_order` calculates an order that might exceed `MAX_PAGE_ORDER`. That'll cause buddy allocator warnings or failures, which isn't good.
The real kicker here is the *lack* of locking on those global variables: `scatter_elem_sz` and `scatter_elem_sz_prev`. A race condition is very likely. Multiple threads can read and write those variables simultaneously. They both read and modify both without any protection!
I have to think about what is happening here:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
Okay, so there's an attempt to handle changes between the reads, but it's not thread-safe and the logic could introduce the issues I mentioned above.
And then, this section within the loop also has issues:
```c
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
```
Wait, why? I need to look at the history of these variables. Git blame time!
|
| 380/7 |
2026/09/09 18:05 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz_prev PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 381/7 |
2026/09/09 18:05 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18576
output: 27
thoughts: 20
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm deep in my domain of expertise:
**Diving into Commit 6460e75a104d**
Alright, time to get to work. Let's see what we're dealing with here. The first thought is, "Right, let's zoom in on this specific commit: `6460e75a104d`." It's clear that focusing on this commit is critical right now. What changes were made? Why were they made? Let's get to the bottom of this. I need to understand the impact of these alterations. This commit could contain a minor bug fix, a significant refactor, or even a completely new feature, so it’s important to give it my undivided attention. Let's start digging!
|
| 382/7 |
2026/09/09 18:05 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 383/7 |
2026/09/09 18:05 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 23213
output: 36
thoughts: 563
Thoughts: **Analyzing the `def_reserved_size` Vulnerability and Fix**
Okay, let's dive into this `def_reserved_size` issue. My initial thought is to trace the evolution of this parameter. Looking at commit `6460e75a104d`, `def_reserved_size` was initially exposed through `module_param_named`. But then, things got interesting. Commit `d06a310b45e1` highlights the problem: a negative or excessively large value written to `/sys/module/sg/parameters/def_reserved_size` could lead to a soft lockup. It makes sense, exposing an integer parameter like that without validation is a classic recipe for trouble.
So, `d06a310b45e1` introduced a fix, which is crucial to examine. They replaced `module_param_named` with `module_param_cb`. Now, this is where the interesting part begins. A custom callback (`def_reserved_size_set`) was implemented, enforcing bounds: limiting the value to between 0 and 1MB. This is a solid approach. The `kstrtoint` function seems appropriate here for string to integer conversion. The validation check with `if (size < 0 || size > 1048576)` is precisely what was needed to prevent the initial vulnerability.
Now, who was responsible for this? It looks like the commit was authored January 27 2026, reviewed by Bart Van Assche, and signed off by Martin K. Petersen. That's good, seeing the SCSI subsystem maintainer's sign-off gives me some confidence in the fix. Let's see if there is more related discussion. Let me check the git logs for discussions. I will now perform a `git log` search using `CodeRegexp: "scatter_elem_sz"` to see if there are any related commits or discussions.
|
| 384/7 |
2026/09/09 18:05 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 385/7 |
2026/09/09 18:05 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24292
output: 26
thoughts: 50
Thoughts: Okay, let's dive into this.
**Analyzing the `sg_build_indirect` Block Layer Conversion**
Alright, so commit `10db10d144c0` is the one that converted `sg_build_indirect` to leverage the block layer. That's a significant change, I need to understand the implications of that shift. Let's pull up the details for commit `10db10d144c0` and dissect the implementation. What were the performance characteristics before the change? What were the driving factors for the conversion? I'm curious about the specific optimizations or benefits they were targeting by integrating with the block layer. I'll need to scrutinize the code diffs for clues about buffer management, data transfer, and error handling. This is probably going to be interesting.
|
| 386/7 |
2026/09/09 18:05 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 387/7 |
2026/09/09 18:05 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 34189
output: 21
thoughts: 3122
Thoughts: **Analyzing the SG Driver and Fixing Parameter Validation**
Okay, so I've been digging into this SCSI generic (sg) driver code and trying to figure out the best way to handle the `scatter_elem_sz` parameter. The goal is to prevent the driver from misbehaving when a user sets this value to something inappropriate, like zero or a negative number, which seems to be the current problem.
I've traced the issue back to commit 10db10d144c0, where `get_order()` started being used. Before this, there was more explicit calculation for page allocation, but now, the code relies on `get_order()`, which can lead to problems if the size (`num`) passed to it is invalid. I noticed the original code in the old patch has some tricks to protect against `scatter_elem_sz` values, but those checks aren't being used now. There seems to be a significant amount of assumptions about the validity of `scatter_elem_sz` and how the driver uses it.
Specifically, there's a problem with how the driver handles cases where `scatter_elem_sz` is less than `PAGE_SIZE`. In the old code, there were checks and updates, but they're not fully correct now. And, the original code used `num` only to check for `scatter_elem_sz_prev`, and inside the loop with `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`. This meant that `scatter_elem_sz` was effectively never *validated* for values.
Now, let's look at the current potential fixes.
**Approach 1: Local Fix in `sg.c`**
This involves changing the checks to explicitly cast `PAGE_SIZE` to an `int` and capping `order` with `min_t`. This would require changes in `init_sg` and `sg_build_indirect`. My gut feeling is that this is a band-aid solution. It addresses the symptom (invalid size) but doesn't fix the root cause (allowing invalid input in the first place). It's also inconsistent and introduces code smells.
**Approach 2: Architectural Fix with `module_param_cb`**
This approach uses `module_param_cb` to validate `scatter_elem_sz` when it's written via sysfs or during module loading. This way, we reject invalid values upfront, preventing them from even entering the `scatter_elem_sz` variable.
The key is input validation *at the user-kernel boundary*. When a sysfs attribute is set, we must sanitize immediately. Allowing invalid values to contaminate the kernel state is a design flaw. It's a fundamental issue of how the driver handles user input.
**Why Approach 1 is Problematic**
I'm very wary of approach 1. There are so many red flags.
First, it violates the user-space contract. If user space writes an invalid value, success is returned, and then a "fix" in `sg_build_indirect` *magically* fixes things. This is silent clamping, which is always bad.
Second, the checks will be duplicated, since `init_sg` and `sg_build_indirect` (and anywhere else the size is used) would need to be checked. This is code duplication and is a violation of the DRY principle.
Third, there is race conditions. I/O could be in process while this variable is being modified which can lead to bad behavior.
Fourth, there's the fragility. If a change is made to how `PAGE_SIZE` is stored (if it were an `unsigned long long`), the cast could cause subtle bugs.
Lastly, and most significantly, consider that we had the *exact* same issue with `def_reserved_size` and the SCSI maintainers fixed that with `module_param_cb`, which is the architectural solution. The drivers had the exact same issue, which was solved by validating the size as the value was passed into the module.
**The Preferred Approach**
Given all that, the architectural approach (approach 2) is *much* better. Validating the parameter at the kernel-user boundary using `module_param_cb` is the right thing to do from an architectural perspective. That's the way to protect against the driver's current buggy behavior.
So, in summary, Approach 2 (using `module_param_cb`) is the proper way. It's clean, robust, and in line with kernel coding practices and the specific fix already used in the same driver.
|
| 388/7 |
2026/09/09 18:06 |
tool |
grepper |
0m
Args: map[Expression:#define MAX_PAGE_ORDER]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
--
tools/perf/builtin-kmem.c=284=static struct perf_session *kmem_session;
--
tools/perf/builtin-kmem.c-286-#define MAX_MIGRATE_TYPES 6
tools/perf/builtin-kmem.c:287:#define MAX_PAGE_ORDER 11
tools/perf/builtin-kmem.c-288-
--
tools/testing/memblock/linux/mmzone.h=16=enum zone_type {
--
tools/testing/memblock/linux/mmzone.h-20-#define MAX_NR_ZONES __MAX_NR_ZONES
tools/testing/memblock/linux/mmzone.h:21:#define MAX_PAGE_ORDER 10
tools/testing/memblock/linux/mmzone.h-22-#define MAX_ORDER_NR_PAGES (1 << MAX_PAGE_ORDER)
--
tools/testing/vma/linux/mmzone.h=16=enum zone_type {
--
tools/testing/vma/linux/mmzone.h-20-#define MAX_NR_ZONES __MAX_NR_ZONES
tools/testing/vma/linux/mmzone.h:21:#define MAX_PAGE_ORDER 10
tools/testing/vma/linux/mmzone.h-22-#define MAX_ORDER_NR_PAGES (1 << MAX_PAGE_ORDER)
--
tools/testing/vsock/vsock_test.c=1661=static void test_stream_msgzcopy_leak_errq_server(const struct test_opts *opts)
--
tools/testing/vsock/vsock_test.c-1741- */
tools/testing/vsock/vsock_test.c:1742:#define MAX_PAGE_ORDER 10 /* usually */
tools/testing/vsock/vsock_test.c-1743-#define PAGE_SIZE 4096
]
|
| 389/7 |
2026/09/09 18:06 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 38907
output: 30
thoughts: 26
Thoughts: Here's my summary, as though I were thinking through the problem:
**Delving into `MAX_PAGE_ORDER`**
Okay, time to get my hands dirty. I need to understand the role of `MAX_PAGE_ORDER`. Let's assume this is in a memory allocation context since it references "page". The name itself implies a maximum order, so I'm betting it relates to the maximum size of a page block that the system can handle. My gut says I'll find its usage in `page_alloc.c` or a file similarly named, most likely involved in the physical memory allocation routines. I need to trace where it is defined, where it is used, and what values it can reasonably take on. I'm especially interested in how it affects the `alloc_pages()` or `__get_free_pages()` implementation (or whatever the relevant kernel APIs are). I'll be looking for things like boundary checks, bit shifts, or calculations involving the page size. This is key to figuring out how the memory allocator does its job. I bet there are some interesting implications for performance and fragmentation. Right, let's start digging into the source code...
|
| 390/7 |
2026/09/09 18:06 |
tool |
grepper |
0m
Args: map[Expression:get_order PathPrefix:mm/page_alloc.c]
Results: map[Output:mm/page_alloc.c=5633=void *alloc_pages_exact_noprof(size_t size, gfp_t gfp_mask)
mm/page_alloc.c-5634-{
mm/page_alloc.c:5635: unsigned int order = get_order(size);
mm/page_alloc.c-5636- unsigned long addr;
--
mm/page_alloc.c=5658=void * __meminit alloc_pages_exact_nid_noprof(int nid, size_t size, gfp_t gfp_mask)
mm/page_alloc.c-5659-{
mm/page_alloc.c:5660: unsigned int order = get_order(size);
mm/page_alloc.c-5661- struct page *p;
]
|
| 391/7 |
2026/09/09 18:06 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 39430
output: 34
thoughts: 91
Thoughts: Okay, here's my interpretation of that thought process, from an expert's perspective:
**Diving into the `alloc_pages` Function**
Right, so I'm thinking about the `alloc_pages(gfp_mask, order)` function call. Of course, the first thing that jumps out is the `order` parameter. We're talking about page allocation here, and specifically, allocating *2^order* pages. Now, my immediate concern is the sanity check: If this `order` value is greater than `MAX_PAGE_ORDER`, the allocation is supposed to fail and loudly! We get a `WARN_ON_ONCE_GFP` call. That's a classic sign of someone trying to grab a massive chunk of memory, something to be avoided.
Now I'm immediately interested in the details of that allocation, so I will start by looking at `alloc_pages_noprof` in `include/linux/gfp.h` or `mm/page_alloc.c` .
|
| 392/7 |
2026/09/09 18:06 |
tool |
grepper |
0m
Args: map[Expression:WARN_ON_ONCE.*MAX_PAGE_ORDER PathPrefix:mm/]
Results: map[Output:mm/page_alloc.c=5330=static inline bool alloc_order_allowed(gfp_t gfp, unsigned int order,
--
mm/page_alloc.c-5339- */
mm/page_alloc.c:5340: return !(WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp));
mm/page_alloc.c-5341-}
--
mm/page_alloc.c=6445=void free_reserved_pages(struct page *page, unsigned int order)
--
mm/page_alloc.c-6450- VM_WARN_ON_ONCE(!IS_ALIGNED(page_to_pfn(page), nr_pages));
mm/page_alloc.c:6451: VM_WARN_ON_ONCE(order > MAX_PAGE_ORDER);
mm/page_alloc.c-6452-
--
mm/vmstat.c=1114=static int __fragmentation_index(unsigned int order, struct contig_page_info *info)
--
mm/vmstat.c-1117-
mm/vmstat.c:1118: if (WARN_ON_ONCE(order > MAX_PAGE_ORDER))
mm/vmstat.c-1119- return 0;
]
|
| 393/7 |
2026/09/09 18:06 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 40114
output: 55
thoughts: 5591
Thoughts: **My Analysis of the `scatter_elem_sz` Issue**
Okay, after a deep dive, here's my considered assessment. I've been looking at the `alloc_order_allowed` check, and the implications of `order > MAX_PAGE_ORDER`. It's pretty clear that if we try to allocate more than `PAGE_SIZE << MAX_PAGE_ORDER`, we're triggering a kernel warning, and the allocation will fail. This brings us to the core issue: how to handle user-provided values for `scatter_elem_sz`, which directly impacts the allocation order.
Looking at Approach 1, immediately I see some problems. They are attempting to add code, and it's a bit of a scattered fix. We have this check in `sg_build_indirect` to try to handle the edge cases of incorrect input.
Approach 2, however, is a different beast altogether. With this method, we're registering a `module_param_cb` for `scatter_elem_sz`. The setter callback has some nice logic:
1. Parse user input.
2. Crucially, enforce bounds validation right at the entry point. It rejects invalid values with `-EINVAL` or `-ERANGE`. This includes values less than `PAGE_SIZE` or larger than `PAGE_SIZE << MAX_PAGE_ORDER`.
And here's where it gets interesting: the invalid values are blocked *before* they can mess things up. We are stopping bad data right at the system boundary. This means that, no matter what, `scatter_elem_sz` is always valid: at least `PAGE_SIZE` and at most what is supported by contiguous memory allocation.
I've also realized that the module parameter parsing happens at *boot* and *load* time as well (it calls `.set` when parsing `modprobe sg scatter_elem_sz=...` or boot args), so it's a very robust solution.
Digging further, I looked at the actual `sg_build_indirect` code. I found that the `num < PAGE_SIZE` check is there, but even if hit, `num` wasn't actually *updated*. And then it was used in another place. In short, the bug in `sg_build_indirect` is that `num` is set, but then that value might not be valid inside the `if` statement.
Then I stepped back to evaluate, and I realized there's a serious question of upstream maintainer preferences. How to structure code, and handle bad inputs? Let's break it down:
1. **Architectural Cleanliness:** Approach 2 is much more in line with good software design principles. Validating input at the boundary is key (input sanitization). Approach 1? We're taking bad input and then putting defensive checks down in the driver, that is bad design.
2. **Sysfs API Contract and User Experience:** Approach 2 immediately tells the user when the value is invalid. Approach 1 is silent; a write succeeds, but the value is secretly changed later. This is a known anti-pattern.
3. **Subsystem Precedent:** We have a direct precedent within the *same* file! In commit `d06a310b45e1`, for the `def_reserved_size` parameter, we find exactly this, with a `module_param_cb`. It shows that this is the approved approach in `drivers/scsi/sg.c`
4. **Approach 1's Code Smells:** It relies on a type punning hack using cast, is a band-aid fix (instead of solving the fundamental problem), has incomplete and fragile fixes, and has a data race vulnerability and the issue is scattered across multiple locations.
5. **Why Maintainers Would Reject Approach 1 / Require Approach 2:** They would be *very* unlikely to accept Approach 1. It's a band-aid, leaves the user interface broken, scatters code around, and is inconsistent with the pattern in this exact file. Approach 2 would be required.
Now, do we clean up `sg_build_indirect` as well? If the validation is done with the `module_param_cb`, you *could* clean up `sg_build_indirect`. You could simplify the redundant conditional logic as defense-in-depth, but Approach 2 is required.
In short, Approach 1 is a band-aid, while Approach 2 provides an architecturally sound solution by validating inputs at the boundary. The maintainers would require Approach 2.
|
| 394/7 |
2026/09/09 18:06 |
tool |
set-results |
0m
Args: map[Answer:From upstream Linux kernel maintainer taste and architecture, Approach 1 is considered a band-aid with distinct code smells, whereas Approach 2 is the correct architectural fix that upstream maintainers would require.]
Results: map[Answer:From upstream Linux kernel maintainer taste and architecture, Approach 1 is considered a band-aid with distinct code smells, whereas Approach 2 is the correct architectural fix that upstream maintainers would require.]
|
| 395/5 |
2026/09/09 18:06 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 61788
output: 420
thoughts: 2368
Thoughts: **Review of Scatter Element Size Patch for sg.c**
Alright, let's break this down. CodeExpert's feedback is spot on: Approach 1 is a band-aid, and we need to implement Approach 2 for proper upstream acceptance. The core of the issue is this: we're allowing invalid values to be written to `/sys/module/sg/parameters/scatter_elem_sz` and then trying to "fix" things in the data path within `sg_build_indirect()`. That's a classic violation of subsystem boundaries. We need to validate at the *entry point*—the sysfs parameter write handler. Rejecting invalid input *immediately* with `-EINVAL` or `-ERANGE` is the right move.
I see a clear precedent for this in `sg.c` itself! Commit `d06a310b45e1` addressed a similar vulnerability with `def_reserved_size` using `module_param_cb()` and a `.set` callback. That's the pattern upstream maintainers have signed off on. This isn't just about taste; it's about good architectural design.
The current approach also introduces data races. We're mutating `scatter_elem_sz` and `scatter_elem_sz_prev` within `sg_build_indirect()`—during device open and request processing—without proper locking. Concurrent access is a problem. Serializing the validation at the sysfs boundary fixes this.
The signedness hack with `(int)PAGE_SIZE` is also problematic. Casting is just a cludge. We can avoid this with proper input validation using `kstrtouint` and a clear range check.
And finally, we have an unbounded upper range and resulting state inconsistency. Clamping `order` in `sg_build_indirect()` leaves `scatter_elem_sz` in a weird state if userspace provides a huge value. We must validate the upper bound at the parameter boundary.
Looking at Approach 2, that example code looks clean. We can use `param_set_uint_minmax` with no issues. And if we do, because we control the valid range, we can be more sure of the logic in `init_sg()` and `sg_build_indirect()`. If `scatter_elem_sz` is guaranteed to be within the valid range, many of those checks and adjustments might be redundant.
So, *ReviewApproved=false* is the correct call here. This isn't just about code correctness; it's about adhering to the established architectural standards for the scsi subsystem. We need to list the "Kernel Architectural Design & Maintainer Taste" violations in the review comments: The current patch has a few problems, and they are listed above. We need to explain how to fix the current patch. In line with commit d06a310b45e1, you can use `module_param_cb` with a `.set` callback to validate and reject invalid values (`< PAGE_SIZE` or `> (PAGE_SIZE << MAX_PAGE_ORDER)`) at write time with `-EINVAL`/`-ERANGE`.
|
| 396/5 |
2026/09/09 18:06 |
tool |
set-results |
0m
Args: map[ReviewApproved:false ReviewComments:[Boundary validation vs. data-path band-aid: The patch attempts to sanitize invalid module parameter values inside the I/O fast path (sg_build_indirect()) rather than rejecting them at the sysfs boundary. Allowing userspace to write invalid values (0, negative values, or values exceeding max page order) into /sys/module/sg/parameters/scatter_elem_sz and having sg_build_indirect() silently mutate global state violates caller/callee responsibility and invariant hygiene. Subsystem idiom alignment: Follow the exact precedent recently established in drivers/scsi/sg.c by commit d06a310b45e1 ("scsi: sg: Resolve soft lockup issue when opening /dev/sgX") for def_reserved_size. Use module_param_cb() with a custom .set callback (or param_set_uint_minmax()) to validate that scatter_elem_sz is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER] at configuration time, returning -EINVAL or -ERANGE on invalid input. Concurrency and global state mutation: Mutating global variables (scatter_elem_sz and scatter_elem_sz_prev) without locks inside sg_build_indirect() introduces data races between concurrent opens and requests. Validating and updating scatter_elem_sz at the sysfs/module parameter entry point eliminates uncoordinated runtime mutations of global state. Typing and state divergence: Casting PAGE_SIZE to (int)PAGE_SIZE to work around signed/unsigned comparison is an anti-pattern. Furthermore, clamping order with min_t(int, order, MAX_PAGE_ORDER) in sg_build_indirect() leaves scatter_elem_sz set to an out-of-range value (e.g. INT_MAX), causing permanent divergence between the sysfs parameter and actual driver allocation behavior.]]
Results: map[ReviewApproved:false ReviewComments:[Boundary validation vs. data-path band-aid: The patch attempts to sanitize invalid module parameter values inside the I/O fast path (sg_build_indirect()) rather than rejecting them at the sysfs boundary. Allowing userspace to write invalid values (0, negative values, or values exceeding max page order) into /sys/module/sg/parameters/scatter_elem_sz and having sg_build_indirect() silently mutate global state violates caller/callee responsibility and invariant hygiene. Subsystem idiom alignment: Follow the exact precedent recently established in drivers/scsi/sg.c by commit d06a310b45e1 ("scsi: sg: Resolve soft lockup issue when opening /dev/sgX") for def_reserved_size. Use module_param_cb() with a custom .set callback (or param_set_uint_minmax()) to validate that scatter_elem_sz is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER] at configuration time, returning -EINVAL or -ERANGE on invalid input. Concurrency and global state mutation: Mutating global variables (scatter_elem_sz and scatter_elem_sz_prev) without locks inside sg_build_indirect() introduces data races between concurrent opens and requests. Validating and updating scatter_elem_sz at the sysfs/module parameter entry point eliminates uncoordinated runtime mutations of global state. Typing and state divergence: Casting PAGE_SIZE to (int)PAGE_SIZE to work around signed/unsigned comparison is an anti-pattern. Furthermore, clamping order with min_t(int, order, MAX_PAGE_ORDER) in sg_build_indirect() leaves scatter_elem_sz set to an out-of-range value (e.g. INT_MAX), causing permanent divergence between the sysfs parameter and actual driver allocation behavior.]]
|
| 397/4 |
2026/09/09 18:07 |
action |
evaluate-patch-review |
0m
Results: map[NeedsIteration:true ReviewFeedback:- Boundary validation vs. data-path band-aid: The patch attempts to sanitize invalid module parameter values inside the I/O fast path (sg_build_indirect()) rather than rejecting them at the sysfs boundary. Allowing userspace to write invalid values (0, negative values, or values exceeding max page order) into /sys/module/sg/parameters/scatter_elem_sz and having sg_build_indirect() silently mutate global state violates caller/callee responsibility and invariant hygiene.
- Subsystem idiom alignment: Follow the exact precedent recently established in drivers/scsi/sg.c by commit d06a310b45e1 ("scsi: sg: Resolve soft lockup issue when opening /dev/sgX") for def_reserved_size. Use module_param_cb() with a custom .set callback (or param_set_uint_minmax()) to validate that scatter_elem_sz is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER] at configuration time, returning -EINVAL or -ERANGE on invalid input.
- Concurrency and global state mutation: Mutating global variables (scatter_elem_sz and scatter_elem_sz_prev) without locks inside sg_build_indirect() introduces data races between concurrent opens and requests. Validating and updating scatter_elem_sz at the sysfs/module parameter entry point eliminates uncoordinated runtime mutations of global state.
- Typing and state divergence: Casting PAGE_SIZE to (int)PAGE_SIZE to work around signed/unsigned comparison is an anti-pattern. Furthermore, clamping order with min_t(int, order, MAX_PAGE_ORDER) in sg_build_indirect() leaves scatter_elem_sz set to an out-of-range value (e.g. INT_MAX), causing permanent divergence between the sysfs parameter and actual driver allocation behavior.]
|
| 398/2 |
2026/09/09 18:07 |
iteration |
1 |
1h03m
|
| 399/3 |
2026/09/09 18:07 |
agent |
patch-generator |
26m
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, an initial explanation of the root cause done by another
kernel expert, and a summary of how similar bugs were fixed in the past.
Use the codeeditor tool to do code edits.
Note: you will not see your changes when looking at the code using codesearch tools.
Use the patch-diff tool to review the modifications you applied.
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.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
The explanation of the root cause of the bug is:
An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
Historical context on how similar bugs were fixed in the past:
Based on a review of the kernel history, the proposed fix aligns perfectly with established idioms and patterns used to resolve similar bugs across the kernel.
Here is a summary of how similar issues have been addressed in the past:
### 1. Handling `get_order(0)` and Undefined Behavior
Passing `0` to `get_order()` or `ilog2()` is known to cause undefined behavior, often resulting in a shift-out-of-bounds (since it underflows and produces a massive shift exponent).
* **`null_blk` (Commit `95491fb05105`)**: A similar bug occurred where a `zone_size` of `0` was passed to `ilog2()`, causing a shift-out-of-bounds. The fix involved validating the input to ensure it was non-zero and adding a defensive check to return early if the size was `0`.
* **`perf` (Commit `dbc48c8f41c2`)**: The driver was passing a `0` to `get_order()` due to a truncation issue. The commit message explicitly notes that the result of `get_order(0)` is undefined and fixed it by validating the maximum supported value before the call.
**Conclusion for `sg.c`:** Updating the local variable `num = PAGE_SIZE` when `num < PAGE_SIZE` is the correct approach. It ensures that `get_order()` is never called with `0`, preventing the undefined behavior and subsequent shift-out-of-bounds.
### 2. Bounding Allocation Orders to `MAX_PAGE_ORDER`
Unbounded sizes passed to `get_order()` can result in an `order` that exceeds `MAX_PAGE_ORDER`. This leads to either a shift-out-of-bounds when calculating the size (`1 << (PAGE_SHIFT + order)`) or a `WARN_ON_ONCE` in the page allocator.
* **`net/smc` (Commit `4cc5130ee84a`)**: To prevent `alloc_pages()` from failing with a warning when requesting physically contiguous buffers, the allocation size was explicitly capped using `min_t(int, bufsize, PAGE_SIZE << MAX_PAGE_ORDER)`.
* **`mm/compaction` (Commit `d1366e74342e`)**: A bogus compound order caused a UBSAN shift-out-of-bounds warning `(1UL << order)`. The fix was to explicitly add an `order <= MAX_PAGE_ORDER` check before performing the shift.
* **`scsi/mpi3mr` (Commit `8c6b808c8c2a`)**: The driver was attempting to allocate massive diagnostic buffers, triggering a `MAX_PAGE_ORDER` warning in the allocator. The fix added a `get_order(size) > MAX_PAGE_ORDER` check to fall back to a retry loop with a smaller size.
**Conclusion for `sg.c`:** Capping the order with `order = min_t(int, order, MAX_PAGE_ORDER)` is a standard and safe kernel idiom. Since `sg_build_indirect()` already contains a fallback loop (`retry:`) that decrements the `order` and tries again if `alloc_pages()` fails, bounding it to `MAX_PAGE_ORDER` upfront elegantly prevents both the shift-out-of-bounds and the allocator warning without requiring any structural changes to the loop.
Another developer tried to fix this bug with the following strategy:
### Root Cause Analysis
The UBSAN warning `shift exponent 64 is too large for 32-bit type 'int'` occurred in `sg_build_indirect()` when `scatter_elem_sz` was set to `0` via `/sys/module/sg/parameters/scatter_elem_sz`:
1. In `sg_build_indirect()`, local variable `num` is initialized to `scatter_elem_sz` (`0`).
2. The check `if (unlikely(num != scatter_elem_sz_prev))` detects the change and `if (num < PAGE_SIZE)` checks whether `num` is smaller than `PAGE_SIZE`. It updates the globals `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`, but fails to update the local variable `num`.
3. As a result, `num` remains `0` and is passed to `get_order(num)`. Passing `0` to `get_order()` results in undefined behavior (underflowing `size--` in the generic implementation to `~0UL`, which computes `order = 52` on 64-bit architectures).
4. Subsequently, `ret_sz = 1 << (PAGE_SHIFT + order)` attempts to shift `1` by `12 + 52 = 64`, which exceeds the 32-bit integer width and triggers the UBSAN shift-out-of-bounds report.
### Additional Issues Identified
1. **Signed/Unsigned Comparison with `PAGE_SIZE`**:
`scatter_elem_sz` and `num` are signed `int` variables, whereas `PAGE_SIZE` is `unsigned long`. Due to C integer promotion rules, comparing `num < PAGE_SIZE` converts `num` to `unsigned long`. If a negative value is supplied (e.g. user writes `-1` to `/sys/module/sg/parameters/scatter_elem_sz` or passes `sg.scatter_elem_sz=-1` on the kernel command line), `(unsigned long)-1` is `ULONG_MAX`, so `num < PAGE_SIZE` evaluates to `false`. The same mistake was present in `init_sg()`. Casting `(int)PAGE_SIZE` ensures signed comparison so that negative values are properly clamped to `PAGE_SIZE`.
2. **Unbounded Allocation Order**:
If `scatter_elem_sz` is set to a very large positive number (e.g., `INT_MAX`), `get_order(num)` evaluates to `19`. `1 << (PAGE_SHIFT + order)` would shift by `31`, overflowing a signed 32-bit `int`, and calling `alloc_pages(gfp_mask, order)` with an order greater than `MAX_PAGE_ORDER` triggers a kernel warning (`WARN_ON_ONCE_GFP`). Bounding `order` to `MAX_PAGE_ORDER` via `min_t(int, order, MAX_PAGE_ORDER)` avoids this.
### Fix Details
1. In `sg_build_indirect()`:
- Added `num = PAGE_SIZE;` inside the clamp block when `num < (int)PAGE_SIZE`.
- Cast `(int)PAGE_SIZE` in the comparison to ensure negative values are also clamped.
- Clamped `order` using `min_t(int, order, MAX_PAGE_ORDER)`.
2. In `init_sg()`:
- Cast `(int)PAGE_SIZE` in `scatter_elem_sz < (int)PAGE_SIZE` so negative module parameters passed at boot time are correctly clamped.
and the following patch:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..24d29a150 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1667,7 +1667,7 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
@@ -1875,14 +1875,16 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
+ if (num < (int)PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
+ num = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
However, a senior maintainer reviewed the patch and requested architectural/design revisions:
- Boundary validation vs. data-path band-aid: The patch attempts to sanitize invalid module parameter values inside the I/O fast path (sg_build_indirect()) rather than rejecting them at the sysfs boundary. Allowing userspace to write invalid values (0, negative values, or values exceeding max page order) into /sys/module/sg/parameters/scatter_elem_sz and having sg_build_indirect() silently mutate global state violates caller/callee responsibility and invariant hygiene.
- Subsystem idiom alignment: Follow the exact precedent recently established in drivers/scsi/sg.c by commit d06a310b45e1 ("scsi: sg: Resolve soft lockup issue when opening /dev/sgX") for def_reserved_size. Use module_param_cb() with a custom .set callback (or param_set_uint_minmax()) to validate that scatter_elem_sz is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER] at configuration time, returning -EINVAL or -ERANGE on invalid input.
- Concurrency and global state mutation: Mutating global variables (scatter_elem_sz and scatter_elem_sz_prev) without locks inside sg_build_indirect() introduces data races between concurrent opens and requests. Validating and updating scatter_elem_sz at the sysfs/module parameter entry point eliminates uncoordinated runtime mutations of global state.
- Typing and state divergence: Casting PAGE_SIZE to (int)PAGE_SIZE to work around signed/unsigned comparison is an anti-pattern. Furthermore, clamping order with min_t(int, order, MAX_PAGE_ORDER) in sg_build_indirect() leaves scatter_elem_sz set to an out-of-range value (e.g. INT_MAX), causing permanent divergence between the sysfs parameter and actual driver allocation behavior.
Revise the patch to eliminate these architectural flaws, satisfy maintainer invariants,
and address all reviewer feedback.
Note: the source tree does not contain the patch yet (so you need to recreate the complete,
revised patch from scratch using the codeeditor tool).
Reply: An architectural revision has been applied to address the root cause and the senior maintainer's feedback:
### Root Cause & Deficiencies of Previous Approaches
1. **Root Cause**:
Writing `"0"` to `/sys/module/sg/parameters/scatter_elem_sz` set `scatter_elem_sz = 0`. During `sg_build_indirect()`, the driver detected that `num < PAGE_SIZE` and updated global variables, but failed to update local variable `num`. `get_order(0)` underflowed into calculating `order = 52`, which subsequently resulted in `1 << (12 + 52)` (shifting 1 by 64 bits), triggering the UBSAN `shift-out-of-bounds` panic.
2. **Architectural Deficiencies in Previous Attempts**:
- **Data-path sanitization**: Patching `sg_build_indirect()` to sanitize out-of-range module parameter values inside the I/O fast path violates invariant hygiene and caller/callee boundaries.
- **Data races and global mutation**: Mutating `scatter_elem_sz` and `scatter_elem_sz_prev` inside `sg_build_indirect()` without synchronization introduces data races between concurrent opens and requests.
- **Parameter divergence**: Clamping `order` inside `sg_build_indirect()` leaves the sysfs parameter at an invalid value while driver allocations diverge silently.
- **Anti-patterns**: Casting `(int)PAGE_SIZE` to work around signed/unsigned comparison.
### Fix Details
Following the subsystem precedent in `drivers/scsi/sg.c` (commit `d06a310b45e1` for `def_reserved_size`):
1. **Module Parameter Boundary Validation**:
- Replaced `module_param_named(scatter_elem_sz, ...)` with `module_param_cb()` using a custom `.set` callback `scatter_elem_sz_set()`.
- Validates that user input is within `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`, rejecting invalid or out-of-range inputs with `-ERANGE` (or `-EINVAL` on malformed input) at the sysfs boundary.
2. **Eliminated Unsynchronized Global State**:
- Removed `scatter_elem_sz_prev` completely from the driver.
- In `init_sg()`, ensured `scatter_elem_sz` is clamped to `PAGE_SIZE` if `PAGE_SIZE > SG_SCATTER_SZ` without referencing `scatter_elem_sz_prev`.
3. **Simplified `sg_build_indirect()`**:
- Removed the runtime mutation and tracking block from `sg_build_indirect()`.
- Initialized allocation order directly via `order = get_order(scatter_elem_sz)`.
- Simplified the per-element size logging to use `num = min(rem_sz, ret_sz)`.
|
| 400/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 9253
output: 27
thoughts: 81
Thoughts: Here's my analysis of the situation:
**Deconstructing the Senior Maintainer's Feedback**
Okay, time to dive in and understand the issue, as well as the senior maintainer's concerns. My initial step is to zero in on the commit referenced in their feedback. I need to understand the context surrounding the `def_reserved_size` implementation, and what led to the changes they're now pointing out.
The obvious route is to use `git show` on that specific commit, `d06a310b45e1`. This should quickly reveal the code changes related to that function, alongside the commit message. Seeing the code diff will allow me to assess the prior implementation of `def_reserved_size`, and quickly understand the scope of the change. This information is key to figuring out the root cause for the feedback I received, and determining the appropriate path forward.
|
| 401/4 |
2026/09/09 18:07 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 402/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 10866
output: 37
thoughts: 75
Thoughts: **Analyzing SCSI Scatter-Gather List Construction**
Okay, so commit `d06a310b45e1` seems like a key, a very specific implementation I need to understand. Let's dig in and see exactly how they're handling scatter-gather list construction. My primary focus is on `drivers/scsi/sg.c`, specifically around the functions and variables dealing with the size of scatter elements, initialization, and how the indirect lists are built. I know there are likely several implementations, so I want to understand their approach, the assumptions they make, and whether their design could impact my work. Time to dissect that code and see if it gives me new insights. I will make sure to check `scatter_elem_sz`, `init_sg`, and `sg_build_indirect` to see the structure and assumptions being used.
|
| 403/4 |
2026/09/09 18:07 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1620 LineCount:60]
Results: map[Contents:1620:
1621: kref_put(&sdp->d_ref, sg_device_destroy);
1622: }
1623:
1624: module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
1655: MODULE_DESCRIPTION("SCSI generic (sg) driver");
1656: MODULE_LICENSE("GPL");
1657: MODULE_VERSION(SG_VERSION_STR);
1658: MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
1659:
1660: MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
1662: MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1663: MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
1664:
1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
1675: rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1676: SG_MAX_DEVS, "sg");
1677: if (rc)
1678: return rc;
1679: rc = class_register(&sg_sysfs_class);
]
|
| 404/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 12100
output: 37
thoughts: 62
Thoughts: Okay, let's dive into `sg_build_indirect` and how those `scatter_elem_sz` variables come into play. I'll need to refresh my memory on the specifics, so let me pull up `drivers/scsi/sg.c` and take a look around lines 1860-1920. I want to see exactly how the sizes are being handled within that indirect build process. The goal is to fully understand their roles and interactions in context.
|
| 405/4 |
2026/09/09 18:07 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1860 LineCount:60]
Results: map[Contents:1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
]
|
| 406/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 13340
output: 33
thoughts: 54
Thoughts: **Investigating the Scatter/Gather Element Size in SCSI Driver**
Okay, so I need to understand the implications of `scatter_elem_sz` and `scatter_elem_sz_prev` within the `drivers/scsi/sg.c` file. Time to dig in and see where these variables are actually *used* within that code. Given my expertise, I suspect their usage might be crucial to performance or specific hardware interactions, so I'm keen to get a holistic view. I'll leverage my preferred tools – either `codesearch-find-references` or `grepper` – to rapidly pinpoint every instance where those variables are referenced. This should give me a complete picture of their scope and impact.
|
| 407/4 |
2026/09/09 18:07 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 408/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 14600
output: 31
thoughts: 41
Thoughts: Okay, let's dive into this. I'm taking a look at `drivers/scsi/sg.c`. I'm already pretty familiar with this area, but I need to make sure I haven't missed anything. I'm wondering if there are any `procfs` handlers lurking in here related to `scatter_elem_sz`. It seems like something I should be aware of, but I don't recall it off the top of my head. Time to do a quick check and make sure I haven't missed a detail.
|
| 409/4 |
2026/09/09 18:07 |
tool |
grepper |
0m
Args: map[Expression:elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 410/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 15811
output: 38
thoughts: 1279
Thoughts: **Analyzing the Senior Maintainer's Feedback**
Okay, let's break down this feedback point by point. The senior maintainer clearly has some concerns, so I need to address these issues effectively.
First, this is about aligning with the established idiom. They want me to look at `drivers/scsi/sg.c` and use `module_param_cb()` for validating the `scatter_elem_sz` parameter. The goal is to ensure the value falls within the range `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`. Returning `-EINVAL` or `-ERANGE` on bad input is key here. I need to implement a `.set` callback function similar to `def_reserved_size_set` to perform this validation. I need to ensure that the data type used is appropriate. `PAGE_SIZE << MAX_PAGE_ORDER` is the upper bound here and I need to ensure that this is safe and does not overflow. Looking at the example, I need to figure out what type `scatter_elem_sz` should be and how to handle the parsing using `kstrtoint`. Currently, `scatter_elem_sz` and `scatter_elem_sz_prev` are both integers.
Then, there's the question of `scatter_elem_sz_prev`. I need to figure out if it is still needed. I will check the git history.
|
| 411/4 |
2026/09/09 18:07 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz_prev PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 412/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 17491
output: 27
thoughts: 32
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing Commits: 6460e75a104d and 10db10d144c0**
Alright, let's dive in. I need to get a handle on the changes introduced by commits `6460e75a104d` and `10db10d144c0`. I immediately begin to visualize the potential impact, considering the codebase and any previous context I have. Let's see what's actually been implemented in those commits. I want to rapidly evaluate the nature of the changes, focusing on whether they are refactoring, new features, bug fixes, or something entirely different. What are the dependencies? Are there any potential regressions I should be looking out for? I am trying to see what architectural decisions or assumptions these commits expose. Depending on the nature of the change I'll be able to tell what tests, if any, have been affected. Then, I can make some judgements as to the quality of the work and if any adjustments are needed.
|
| 413/4 |
2026/09/09 18:07 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 414/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 22198
output: 26
thoughts: 61
Thoughts: Here's my take on those thoughts:
**Analyzing the Evolution of Indirect I/O in the SCSI Generic Driver**
Okay, so I'm digging into commit `10db10d144c0` – that's where the SCSI generic (sg) driver's indirect I/O path was converted to leverage the block layer. I need to refresh my memory on the specifics of how this happened and, specifically, how `sg_build_indirect` was affected. Time to dive into the code from that commit and see what the changes look like. I'll focus on the evolution of that crucial function.
|
| 415/4 |
2026/09/09 18:07 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 416/4 |
2026/09/09 18:07 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 32064
output: 22
thoughts: 4389
Thoughts: **Analyzing and Refactoring `sg_build_indirect` for Maintainer Compliance**
Alright, let's break this down. We're looking at `sg_build_indirect` in `drivers/scsi/sg.c`, specifically how it handles `scatter_elem_sz` and how the maintainer wants to see it changed. My initial thought is, "Okay, this is about ensuring that this allocation logic is clean and thread-safe." The current code has some historical baggage, and the maintainer's critique points out some serious flaws.
My attention is drawn to lines 1899-1904: the conditional update of `scatter_elem_sz`. The old code seems to be dealing with the evolution from page-per-element to order-of-pages allocation, and the need to "round up" to the nearest power of 2. The original intent of Douglas Gilbert appears to have been to ensure `scatter_elem_sz` always reflects the actual size allocated, even if the user specifies a non-power-of-2 value. The `scatter_elem_sz_prev` seems to have served a caching function, but is it *really* needed anymore? Is it dead code?
The maintainer's feedback is crystal clear. Validate the module parameter *at the boundary* (sysfs), use `module_param_cb` or `param_set_uint_minmax` to constrain `scatter_elem_sz` to `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`. This is the core issue! If the value is good, then don't ever change it inside the data path! We're talking about removing the data races and cleaning up the flow. That means no more mutations of `scatter_elem_sz` and `scatter_elem_sz_prev` within `sg_build_indirect` if we are doing this correctly.
My focus goes to "Can we remove the `scatter_elem_sz_prev` variable entirely?" Let's look more closely at the use of `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`. It seems like `scatter_elem_sz_prev` is only used to hold the size of the previous element, which is in fact now `ret_sz`.
The code's logic becomes clearer after re-reading the maintainer's comments. It's about validating the module parameter up front and ensuring the data path is not modified. The code still contains carry-over from the old code, which is confusing. The code essentially compares a variable called `num`, which is the old value, to what may be a rounded-up `ret_sz`.
So, it seems that if we validate `scatter_elem_sz` to make sure it's valid, and keep it valid, then we can simplify the code and remove `scatter_elem_sz_prev` and any of the conditional logic that attempts to update `scatter_elem_sz` inside the allocation loop. We *should* validate that the values can be set to valid power-of-2 values!
The suggestion to use `param_set_uint_minmax` is important. This validates at the module parameter level. I now need to make sure that `param_set_uint_minmax` can be used correctly to constrain `scatter_elem_sz` to `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]` within the sysfs entry point. This is the key to preventing the data races and making the code more robust.
|
| 417/4 |
2026/09/09 18:08 |
tool |
grepper |
0m
Args: map[Expression:param_set_uint_minmax]
Results: map[Output:drivers/block/ublk_drv.c=5945=static int ublk_set_max_unprivileged_ublks(const char *buf,
--
drivers/block/ublk_drv.c-5947-{
drivers/block/ublk_drv.c:5948: return param_set_uint_minmax(buf, kp, 0, UBLK_MAX_UBLKS);
drivers/block/ublk_drv.c-5949-}
--
drivers/nvme/host/pci.c=341=static int io_queue_depth_set(const char *val, const struct kernel_param *kp)
drivers/nvme/host/pci.c-342-{
drivers/nvme/host/pci.c:343: return param_set_uint_minmax(val, kp, NVME_PCI_MIN_QUEUE_SIZE,
drivers/nvme/host/pci.c-344- NVME_PCI_MAX_QUEUE_SIZE);
--
drivers/ufs/core/ufs-mcq.c=40=static int rw_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-41-{
drivers/ufs/core/ufs-mcq.c:42: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_RW_QUEUES,
drivers/ufs/core/ufs-mcq.c-43- num_possible_cpus());
--
drivers/ufs/core/ufs-mcq.c=56=static int read_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-57-{
drivers/ufs/core/ufs-mcq.c:58: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_READ_QUEUES,
drivers/ufs/core/ufs-mcq.c-59- num_possible_cpus());
--
drivers/ufs/core/ufs-mcq.c=72=static int poll_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-73-{
drivers/ufs/core/ufs-mcq.c:74: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_POLL_QUEUES,
drivers/ufs/core/ufs-mcq.c-75- num_possible_cpus());
--
drivers/ufs/core/ufs-txeq.c=25=static int txeq_gear_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-txeq.c-26-{
drivers/ufs/core/ufs-txeq.c:27: return param_set_uint_minmax(val, kp, UFS_HS_G1, UFS_HS_GEAR_MAX);
drivers/ufs/core/ufs-txeq.c-28-}
--
drivers/ufs/core/ufs-txeq.c=47=static int txeq_setting_sel_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-txeq.c-48-{
drivers/ufs/core/ufs-txeq.c:49: return param_set_uint_minmax(val, kp, 0, 1);
drivers/ufs/core/ufs-txeq.c-50-}
--
drivers/ufs/core/ufshcd.c=125=static int uic_cmd_timeout_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufshcd.c-126-{
drivers/ufs/core/ufshcd.c:127: return param_set_uint_minmax(val, kp, UIC_CMD_TIMEOUT_DEFAULT,
drivers/ufs/core/ufshcd.c-128- UIC_CMD_TIMEOUT_MAX);
--
drivers/ufs/core/ufshcd.c=142=static int dev_cmd_timeout_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufshcd.c-143-{
drivers/ufs/core/ufshcd.c:144: return param_set_uint_minmax(val, kp, QUERY_REQ_TIMEOUT_MIN,
drivers/ufs/core/ufshcd.c-145- QUERY_REQ_TIMEOUT_MAX);
--
include/linux/moduleparam.h=461=int param_get_uint(char *buffer, const struct kernel_param *kp);
include/linux/moduleparam.h:462:int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
include/linux/moduleparam.h-463- unsigned int min, unsigned int max);
--
kernel/params.c=242=STANDARD_PARAM_DEF(hexint, unsigned int, "%#08x", kstrtouint);
kernel/params.c-243-
kernel/params.c:244:int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
kernel/params.c-245- unsigned int min, unsigned int max)
--
kernel/params.c-259-}
kernel/params.c:260:EXPORT_SYMBOL_GPL(param_set_uint_minmax);
kernel/params.c-261-
--
kernel/sched/ext/ext.c=227=static int set_slice_us(const char *val, const struct kernel_param *kp)
kernel/sched/ext/ext.c-228-{
kernel/sched/ext/ext.c:229: return param_set_uint_minmax(val, kp, 100, 100 * USEC_PER_MSEC);
kernel/sched/ext/ext.c-230-}
--
kernel/sched/ext/ext.c=237=static int set_bypass_lb_intv_us(const char *val, const struct kernel_param *kp)
kernel/sched/ext/ext.c-238-{
kernel/sched/ext/ext.c:239: return param_set_uint_minmax(val, kp, 0, 10 * USEC_PER_SEC);
kernel/sched/ext/ext.c-240-}
--
mm/page_reporting.c=18=static int page_order_update_notify(const char *val, const struct kernel_param *kp)
--
mm/page_reporting.c-23- */
mm/page_reporting.c:24: return param_set_uint_minmax(val, kp, 0, MAX_PAGE_ORDER);
mm/page_reporting.c-25-}
--
net/ipv4/tcp_dctcp.c=62=static int dctcp_shift_g_set(const char *val, const struct kernel_param *kp)
net/ipv4/tcp_dctcp.c-63-{
net/ipv4/tcp_dctcp.c:64: return param_set_uint_minmax(val, kp, 0, 10);
net/ipv4/tcp_dctcp.c-65-}
--
net/sunrpc/xprtsock.c=3730=static int param_set_portnr(const char *val, const struct kernel_param *kp)
net/sunrpc/xprtsock.c-3731-{
net/sunrpc/xprtsock.c:3732: return param_set_uint_minmax(val, kp,
net/sunrpc/xprtsock.c-3733- RPC_MIN_RESVPORT,
--
net/sunrpc/xprtsock.c=3748=static int param_set_slot_table_size(const char *val,
--
net/sunrpc/xprtsock.c-3750-{
net/sunrpc/xprtsock.c:3751: return param_set_uint_minmax(val, kp,
net/sunrpc/xprtsock.c-3752- RPC_MIN_SLOT_TABLE,
--
net/sunrpc/xprtsock.c=3764=static int param_set_max_slot_table_size(const char *val,
--
net/sunrpc/xprtsock.c-3766-{
net/sunrpc/xprtsock.c:3767: return param_set_uint_minmax(val, kp,
net/sunrpc/xprtsock.c-3768- RPC_MIN_SLOT_TABLE,
]
|
| 418/4 |
2026/09/09 18:08 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 39454
output: 33
thoughts: 25
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into `param_set_uint_minmax` Implementation**
Okay, time to dig into the guts of `kernel/params.c` and specifically, the `param_set_uint_minmax` function. I'm expecting to see a pretty standard pattern here, but the devil's in the details, as always. My immediate concerns will be around:
* **Error Handling:** How robust is the input validation? Does it check for NULL pointers for the `param` struct and any associated data? Are there checks for values *below* the minimum or *above* the maximum allowed uint? Are error codes clearly defined and propagated appropriately? This needs to be bulletproof. I'm hoping to see a solid `EINVAL` or similar for out-of-bounds attempts.
* **Atomicity/Concurrency:** If this is a multi-threaded environment (and let's assume it is, given we're in kernel space), what measures are in place to ensure atomic updates? Is there a mutex protecting the parameter's data? Are there read/write locks or atomic operations being used to avoid race conditions? I'll be particularly scrutinizing this section, as integer overflow is a common problem.
* **Data Type Considerations:** Is the uint being stored in the most efficient manner, given the architecture? Is there any sign extension that needs to be accounted for? Are there any compiler optimizations that may impact the expected behavior, such as if we're dealing with different word sizes?
* **Logging/Debugging:** Is there sufficient logging, either for success or failure? Ideally, I'd like to see debug messages that identify the parameter name, the attempted value, and the min/max bounds. This is absolutely critical for tracking down subtle issues during testing and debugging.
* **Range Checks:** Of course, there need to be range checks! I'll be checking these to see if they are correct, and if any overflow issues could occur.
Essentially, I'm expecting to see a well-structured function with rigorous error handling, attention to concurrency, and clear, informative logging. It needs to be safe, efficient, and easy to debug. Let's see if the code lives up to these expectations... time to start reading.
|
| 419/4 |
2026/09/09 18:08 |
tool |
read-file |
0m
Args: map[File:kernel/params.c FirstLine:240 LineCount:25]
Results: map[Contents: 240: STANDARD_PARAM_DEF(ulong, unsigned long, "%lu", kstrtoul);
241: STANDARD_PARAM_DEF(ullong, unsigned long long, "%llu", kstrtoull);
242: STANDARD_PARAM_DEF(hexint, unsigned int, "%#08x", kstrtouint);
243:
244: int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
245: unsigned int min, unsigned int max)
246: {
247: unsigned int num;
248: int ret;
249:
250: if (!val)
251: return -EINVAL;
252: ret = kstrtouint(val, 0, &num);
253: if (ret)
254: return ret;
255: if (num < min || num > max)
256: return -EINVAL;
257: *((unsigned int *)kp->arg) = num;
258: return 0;
259: }
260: EXPORT_SYMBOL_GPL(param_set_uint_minmax);
261:
262: int param_set_charp(const char *val, const struct kernel_param *kp)
263: {
264: char *tmp;
]
|
| 420/4 |
2026/09/09 18:08 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 40410
output: 26
thoughts: 1691
Thoughts: **Analyzing Parameter Setting for Scatter Element Size**
Okay, let's break this down. I'm looking at how we're handling the `scatter_elem_sz` parameter, and I'm seeing some potential issues with the current implementation.
First, I examined `param_set_uint_minmax`. It's a standard function for setting unsigned integer parameters with min/max bounds. It uses `kstrtouint` to parse the string input, which is the correct approach for an unsigned value. The crucial part here is the validation against the `min` and `max` values.
The maintainer's comment points to commit `d06a310b45e1` in `drivers/scsi/sg.c` as a precedent, and specifically, the use of `module_param_cb` with a custom `.set` callback, or `param_set_uint_minmax` for validating the parameter. This suggests we should also use one of these two methods, if the parameter must be validated. Let's make sure it's validated, as the comment suggests.
I then looked at `def_reserved_size` in `sg.c`, which follows the same pattern as the other patch. `def_reserved_size` is an `int`. This is interesting because the maintainer's comment also mentions a need to align with subsystem idioms.
Now, the core of the issue: what's the type of `scatter_elem_sz`? I see it's currently defined as `static int scatter_elem_sz = SG_SCATTER_SZ;`. That's where things get interesting. The maintainer's comments say to *validate* this against a minimum and maximum.
The maintainer's comment mentions an anti-pattern: casting `PAGE_SIZE` to `(int)PAGE_SIZE` to deal with signed/unsigned comparisons. This is a clear indicator of a problem because `PAGE_SIZE` is an `unsigned long`, and comparing it directly to a signed integer can lead to unexpected behavior due to implicit type conversions. This is the root of the signed/unsigned comparison issue.
So the original patch had signed `int` for `scatter_elem_sz` and `num`. In `init_sg`, this was used:
```c
if (scatter_elem_sz < (int)PAGE_SIZE)
```
and `sg_build_indirect` had:
```c
if (num < (int)PAGE_SIZE)
```
Now, the question becomes, can we use `kstrtoint` (or `kstrtouint`, or `param_set_uint_minmax`) for the `.set` callback? Let's assume for the moment that `scatter_elem_sz` *remains* an `int`.
Let's assume the callback:
```c
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
scatter_elem_sz = size;
return 0;
}
```
Here's the problem: *C integer promotion* will kick in during the comparison `size < PAGE_SIZE`. `size` (which is `int`) will be promoted to `unsigned long` because `PAGE_SIZE` is `unsigned long`. If `size` is negative (say, -1), it will be converted to a *very large positive* `unsigned long` value. That leads to a *false* result when compared to `PAGE_SIZE`, so negative values might pass the check!
The same logic will apply when comparing `size > (PAGE_SIZE << MAX_PAGE_ORDER)`!
In other words, a negative size could *bypass* the `PAGE_SIZE` validation. That's a huge bug!
I need to confirm whether `kstrtouint` accepts negative numbers, but I think `param_set_uint_minmax` will correctly return an error on a negative value. I need to investigate the kernel's handling of `kstrtouint`.
|
| 421/4 |
2026/09/09 18:08 |
tool |
grepper |
0m
Args: map[Expression:kstrtouint PathPrefix:lib/]
Results: map[Output:lib/dynamic_debug.c=340=static inline int parse_lineno(const char *str, unsigned int *val)
--
lib/dynamic_debug.c-346- }
lib/dynamic_debug.c:347: if (kstrtouint(str, 10, val) < 0) {
lib/dynamic_debug.c-348- pr_err("bad line-number: %s\n", str);
--
lib/fault-inject.c=295=static ssize_t fault_uint_attr_store(unsigned int *val, const char *page, size_t count)
--
lib/fault-inject.c-299-
lib/fault-inject.c:300: result = kstrtouint(page, 0, &tmp);
lib/fault-inject.c-301- if (result < 0)
--
lib/kstrtox.c=213=EXPORT_SYMBOL(_kstrtol);
--
lib/kstrtox.c-215-/**
lib/kstrtox.c:216: * kstrtouint - convert a string to an unsigned int
lib/kstrtox.c-217- * @s: The start of the string. The string must be null-terminated, and may also
--
lib/kstrtox.c=230=noinline
lib/kstrtox.c:231:int kstrtouint(const char *s, unsigned int base, unsigned int *res)
lib/kstrtox.c-232-{
--
lib/kstrtox.c-243-}
lib/kstrtox.c:244:EXPORT_SYMBOL(kstrtouint);
lib/kstrtox.c-245-
--
lib/kstrtox.c=535=kstrto_from_user(kstrtol_from_user, kstrtol, long);
lib/kstrtox.c:536:kstrto_from_user(kstrtouint_from_user, kstrtouint, unsigned int);
lib/kstrtox.c-537-kstrto_from_user(kstrtoint_from_user, kstrtoint, int);
--
lib/parser.c=210=int match_uint(substring_t *s, unsigned int *result)
--
lib/parser.c-216-
lib/parser.c:217: return kstrtouint(buf, 10, result);
lib/parser.c-218-}
--
lib/stackdepot.c=104=static int __init parse_max_pools(char *str)
--
lib/stackdepot.c-109-
lib/stackdepot.c:110: rv = kstrtouint(str, 0, &max_pools);
lib/stackdepot.c-111- if (rv)
--
lib/test_kmod.c=872=static int test_dev_config_update_uint_sync(struct kmod_test_device *test_dev,
--
lib/test_kmod.c-880-
lib/test_kmod.c:881: ret = kstrtouint(buf, 10, &val);
lib/test_kmod.c-882- if (ret)
--
lib/test_kmod.c=906=static int test_dev_config_update_uint_range(struct kmod_test_device *test_dev,
--
lib/test_kmod.c-914-
lib/test_kmod.c:915: ret = kstrtouint(buf, 10, &val);
lib/test_kmod.c-916- if (ret)
]
|
| 422/4 |
2026/09/09 18:08 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 44027
output: 35
thoughts: 20
Thoughts: Here's my summary, as though I'm reading and thinking about the code:
**Diving into `kstrtouint`**
Okay, time to get into `lib/kstrtox.c` and take a look at `kstrtouint`. I'm expecting this to be a pretty crucial piece of the kernel's string-to-unsigned-integer conversion logic. I'll need to pay close attention to the error handling, overflow checks, and overall efficiency, as these functions are often performance-critical and absolutely *must* be robust in the face of potentially malicious or invalid input. I'm also curious to see how they've handled the various bases – decimal, hex, octal, etc. – and any potential platform-specific optimizations they might have employed. Let's see how they've structured the validation to avoid buffer overflows and ensure numerical correctness. It's time to assess the overall approach. I'm keen to evaluate the readability of the implementation as well, as this is a good indicator of overall maintainability. It will be exciting to dive into the low-level details.
|
| 423/4 |
2026/09/09 18:08 |
tool |
read-file |
0m
Args: map[File:lib/kstrtox.c FirstLine:225 LineCount:25]
Results: map[Contents: 225: * @res: Where to write the result of the conversion on success.
226: *
227: * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
228: * Preferred over simple_strtoul(). Return code must be checked.
229: */
230: noinline
231: int kstrtouint(const char *s, unsigned int base, unsigned int *res)
232: {
233: unsigned long long tmp;
234: int rv;
235:
236: rv = kstrtoull(s, base, &tmp);
237: if (rv < 0)
238: return rv;
239: if (tmp != (unsigned int)tmp)
240: return -ERANGE;
241: *res = tmp;
242: return 0;
243: }
244: EXPORT_SYMBOL(kstrtouint);
245:
246: /**
247: * kstrtoint - convert a string to an int
248: * @s: The start of the string. The string must be null-terminated, and may also
249: * include a single newline before its terminating null. The first character
]
|
| 424/4 |
2026/09/09 18:08 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 44694
output: 34
thoughts: 70
Thoughts: **Investigating a Potential Integer Conversion Bug**
Okay, so I'm digging into this `kstrtoull` function, and something's not quite sitting right. It seems like the way it handles negative signs when dealing with unsigned integers in `_parse_integer`, which is part of the `kstrtoull` process, might be problematic. Specifically, I'm concerned that a negative sign, when used with an unsigned integer, is resulting in `-EINVAL`, which isn't the expected behavior. I need to confirm this.
Therefore, I need to test what `kstrtoull("-1", ...)` actually returns. It's time to go into the code and see exactly what's happening. I'll need to go to `lib/kstrtox.c` and specifically look at line 50. Let's see if that line is the culprit!
|
| 425/4 |
2026/09/09 18:08 |
tool |
read-file |
0m
Args: map[File:lib/kstrtox.c FirstLine:50 LineCount:40]
Results: map[Contents: 50: *
51: * Convert non-negative integer string representation in explicitly given
52: * radix to an integer. If overflow occurs, value at @p is set to ULLONG_MAX.
53: *
54: * This function is the workhorse of other string conversion functions and it
55: * is discouraged to use it explicitly. Consider kstrto*() family instead.
56: *
57: * Return: Number of characters consumed, maybe ORed with overflow bit
58: */
59: noinline
60: unsigned int _parse_integer_limit(const char *s, unsigned int base, unsigned long long *p,
61: size_t max_chars, unsigned long long init)
62: {
63: unsigned int rv, overflow = 0;
64: unsigned long long res;
65:
66: res = init;
67: for (rv = 0; rv < max_chars; rv++, s++) {
68: unsigned int c = *s;
69: unsigned int lc = _tolower(c);
70: unsigned int val;
71:
72: if ('0' <= c && c <= '9')
73: val = c - '0';
74: else if ('a' <= lc && lc <= 'f')
75: val = lc - 'a' + 10;
76: else
77: break;
78:
79: if (val >= base)
80: break;
81: /*
82: * Check for overflow only if we are within range of
83: * it in the max base we support (16)
84: */
85: if (unlikely(res & (~0ull << 60))) {
86: if (check_mul_overflow(res, base, &res) ||
87: check_add_overflow(res, val, &res)) {
88: res = ULLONG_MAX;
89: overflow = KSTRTOX_OVERFLOW;
]
|
| 426/4 |
2026/09/09 18:08 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 45563
output: 37
thoughts: 11591
Thoughts: **Refining the Scatter Element Size Handling**
Okay, here's the breakdown of my thinking. The core issue is how the `scatter_elem_sz` parameter is handled, and how the maintainer wants to address the potential for concurrency issues and state divergence. My initial assessment was correct: using `kstrtouint` for the unsigned integer conversion is fine. The existing check with `_parse_integer_limit` for negative numbers would prevent negative values. The initial validation using the min/max comparison ( `num < min || num > max`) is correctly applied by the parameter setting callback.
The maintainer wants us to follow the style used in `drivers/scsi/sg.c` by commit `d06a310b45e1` to address the potential for concurrent accesses. This involves validating the `scatter_elem_sz` *at the point of module parameter setting* using `module_param_cb` and a custom `.set` callback, or `param_set_uint_minmax()`. I had considered both a custom callback and using `param_set_uint_minmax()`. I realized `param_set_uint_minmax` is designed to be used by a helper function that calls it. My original plan to use `kstrtouint` and compare to the `PAGE_SIZE` and `PAGE_SIZE << MAX_PAGE_ORDER` upper limit is what the maintainer is suggesting. I realized that `param_set_uint_minmax` would return `-EINVAL` for out of bounds, and not `-ERANGE`.
The commit being referenced, `d06a310b45e1`, uses the latter validation approach. `def_reserved_size_set` is a custom callback using `kstrtoint` and checking a range of values. The maintainer emphasized the "subsystem idiom alignment". The senior maintainer said that we can use the same technique.
The issue is the data race between concurrent opens and requests, which lead to data inconsistencies and non-deterministic behavior. I started to scrutinize `sg_build_indirect` more carefully, especially the variables `scatter_elem_sz` and `scatter_elem_sz_prev`.
The key is to *eliminate* the runtime modifications of the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` within the `sg_build_indirect()` function. That is the essence of the "concurrency and global state mutation" problem. By validating the parameter *at set time* and making sure the system never allows `scatter_elem_sz` to be an out-of-range value, we can be sure of the state of the scatter element size. This means the `sg_build_indirect()` function will just read the value of `scatter_elem_sz` and use it. The problem of comparing signed `int` to `unsigned long` with `PAGE_SIZE` and the `(int)PAGE_SIZE` casting goes away. With this design, the range validation prevents the need for the casting. This also resolves potential issues with negative input, the `Wsign-compare` warning.
I carefully checked the `init_sg()` function and the cases that happen when `scatter_elem_sz` is set at boot time. I was sure to check what happened when the system had larger page sizes. It uses `SG_SCATTER_SZ` initially (which defaults to a size that's below `PAGE_SIZE` in the common case). I also confirmed that if a smaller `scatter_elem_sz` is passed, `init_sg()` will update it to be `PAGE_SIZE`, and this is completely safe, with no need for locking.
I then did a comprehensive examination of all the usages of `scatter_elem_sz` and `scatter_elem_sz_prev` within the `sg.c` source. I was able to definitively show `scatter_elem_sz_prev` is not exported, not used externally, not in sysfs, and is only used internally in `sg_build_indirect()`. The `sg_build_indirect()` had multiple mutations of the `scatter_elem_sz`. After removing all usages of `scatter_elem_sz_prev` and validating and updating `scatter_elem_sz` only at configuration time, `scatter_elem_sz_prev` and all its uses can be deleted. The data path simplifies and there will be no race conditions when running the system.
I will create a patch that:
1. Uses `module_param_cb()` with a `.set` callback to validate `scatter_elem_sz` within `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]` at configuration time and returns either -EINVAL or -ERANGE on invalid input.
|
| 427/4 |
2026/09/09 18:09 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1915 LineCount:25]
Results: map[Contents:1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
1931: static void
1932: sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
1933: {
1934: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1935: "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
1936: if (schp->pages && schp->sglist_len > 0) {
1937: if (!schp->dio_in_use) {
1938: int k;
1939:
]
|
| 428/4 |
2026/09/09 18:09 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 58603
output: 25
thoughts: 4354
Thoughts: **Analyzing Parameter Validation for Scatter Element Size**
Okay, so I've been dissecting this code related to scatter/gather lists, specifically focusing on how the `scatter_elem_sz` parameter is handled. The core issue is ensuring this size falls within a valid range—`PAGE_SIZE` to `PAGE_SIZE << MAX_PAGE_ORDER`. There was a bug related to retries with decreasing page sizes, and the existing code had a flawed comparison. That's been sorted out.
Now, I'm at the parameter validation itself. The maintainer's feedback points toward using either a custom `.set` callback for `module_param_cb` or `param_set_uint_minmax`. I need to choose the *correct* approach, keeping the principle of following the established idiom from the `scsi: sg` subsystem.
Initially, I looked at a custom callback. It seemed straightforward: parse the input string, convert to an integer, and check against the range. I wrote it out in multiple ways, using `kstrtouint` and `kstrtoint`. The key point became the potential for signed/unsigned comparisons when using integers for the size parameter. This is an anti-pattern as noted by the maintainer.
The maintainer advised to return -EINVAL or -ERANGE on invalid input. Both are mentioned, but I have to decide which is most correct/idiomatic.
The `param_set_uint_minmax` function offers a cleaner solution. It uses `kstrtouint`, avoiding signed/unsigned comparisons entirely, and handles the range check in a safe manner. It immediately returns -EINVAL if the input is negative. Also, I looked for examples of `param_set_uint_minmax` usage in other parts of the kernel, like in the nvme and scheduler code, to ensure it's a good approach.
The crucial detail here is that `param_set_uint_minmax` expects an `unsigned int *` for the parameter's memory location, and it calls `kstrtouint`. Even though `scatter_elem_sz` is currently declared as `int` in the current version of the code, this is not an issue since `sizeof(int)` equals `sizeof(unsigned int)`. The parameter is never used as a negative value, it's a size in bytes.
It seems defining `scatter_elem_sz` as `int` is legacy. This is an unsigned size, and the value is constrained to positive values (PAGE_SIZE and up).
Ultimately, I'm leaning toward using `param_set_uint_minmax`. It's concise, avoids potential signed/unsigned issues, and handles range validation effectively. Also, this approach will avoid the need to cast PAGE_SIZE in the custom callback.
|
| 429/4 |
2026/09/09 18:09 |
tool |
grepper |
0m
Error:
Args: map[Expression:Wsign-compare PathPrefix:Makefile]
Results:
|
| 430/4 |
2026/09/09 18:09 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 63588
output: 26
thoughts: 13
Thoughts: Here's a summary of my immediate thought process:
**Diving into the Build Configuration**
Okay, time to get started. My first instinct is to zero in on the build process and how it handles warnings. Let's see... I'll start by checking the `scripts/Makefile.extrawarn` file. I'm expecting this file to hold the specific flags and settings that control the extra warning level in the build process. I'm looking for the definitions related to compile-time warnings, not just the general makefile structure itself. Knowing how warnings are treated is crucial, and `Makefile.extrawarn` is the most logical starting point for that investigation. Let's see what's in there.
|
| 431/4 |
2026/09/09 18:09 |
tool |
grepper |
0m
Args: map[Expression:Wsign-compare PathPrefix:scripts/]
Results: map[Output:scripts/Makefile.warn=186=KBUILD_CFLAGS += -Wredundant-decls
scripts/Makefile.warn:187:KBUILD_CFLAGS += -Wsign-compare
scripts/Makefile.warn-188-KBUILD_CFLAGS += -Wswitch-default
]
|
| 432/4 |
2026/09/09 18:09 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 63856
output: 22
thoughts: 12133
Thoughts: **Summary of Analysis and Proposed Implementation**
Okay, so the task at hand is to validate the `scatter_elem_sz` module parameter, ensuring it falls within the range `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`. The goal is to prevent the "anti-pattern" of data-path sanitization that the previous patch attempted and, as per the senior maintainer's feedback, strictly validate at configuration time (sysfs/module parameter entry). This will involve following the established precedent set by the `def_reserved_size` implementation in `drivers/scsi/sg.c`, as referenced in commit `d06a310b45e1`.
The original implementation had a critical flaw; the patch attempted to sanitize negative values. Because of the signed vs unsigned comparison of the `int scatter_elem_sz` with `PAGE_SIZE` which is `unsigned long`, `scatter_elem_sz < PAGE_SIZE` does not catch negative numbers in C because the comparisons were done in unsigned integer space, where negative numbers became large unsigned numbers. This leads to undefined behavior. Clamping values in the data path, as the previous patch did, is considered an "anti-pattern" as it introduces data races and the possibility of out-of-range values in sysfs and diverging from actual driver behavior.
Two approaches are available: `param_set_uint_minmax` or a custom `.set` callback function. Based on the senior maintainer’s directive to validate the size at configuration time, `param_set_uint_minmax` offers a clean solution because its underlying mechanisms can handle the bounds validation.
The `param_set_uint_minmax` function is preferred in this case as a concise way to handle the parameter's minimum and maximum ranges. It also enforces the bounds at configuration time. Importantly, `param_set_uint_minmax` ensures the code remains free of signed/unsigned comparison warnings and the parameter validation is done efficiently. The underlying mechanisms of `kstrtouint` combined with the comparison against min and max in `param_set_uint_minmax` is a far safer and more maintainable option. While a custom callback can be built that matches the functionality of `param_set_uint_minmax`, given the maintainer's focus on adhering to the paradigm of the `sg.c` commit, it's safe to leverage an out-of-the-box solution to validate that `scatter_elem_sz` is within `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`.
In essence, using `param_set_uint_minmax` will keep things safe and simple. There's no need to explicitly check for `size < 0` or cast `PAGE_SIZE` to `(int)PAGE_SIZE` which was the root issue in the original patch.
This can be implemented as:
```c
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
return param_set_uint_minmax(val, kp, PAGE_SIZE,
PAGE_SIZE << MAX_PAGE_ORDER);
}
static const struct kernel_param_ops scatter_elem_sz_ops = {
.set = scatter_elem_sz_set,
.get = param_get_uint,
};
module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
S_IRUGO | S_IWUSR);
```
The choice of `int` or `unsigned int` for `scatter_elem_sz` doesn't matter, though it's likely slightly cleaner to keep it as an `int` for backwards compatibility. The validation happens *before* the value is written to `scatter_elem_sz` so type is fine, though `unsigned int` might feel more correct in spirit. `param_set_uint_minmax` handles the validation and ensures correct values are assigned. This ensures that negative values and values outside of the bounds are rejected before they become a problem.
|
| 433/4 |
2026/09/09 18:10 |
tool |
grepper |
0m
Error:
Args: map[Expression:kstrtoint.*PAGE_SIZE]
Results:
|
| 434/4 |
2026/09/09 18:10 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 76922
output: 463
thoughts: 18018
Thoughts: **Analysis of Validating `scatter_elem_sz` in `sg.c`**
Okay, here's the breakdown of my thought process. The key here is validation of the `scatter_elem_sz` module parameter in the `sg.c` driver, and how to best implement this, especially concerning the senior maintainer's feedback. I'm focusing on aligning with existing kernel idioms and addressing the previous patch's shortcomings.
1. **Understanding the Requirement:** The goal is to ensure `scatter_elem_sz` (the scatter gather element size) falls within a valid range: `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`. Invalid values should be rejected *at the sysfs boundary*, not handled in the data path. This is key to preventing data races and maintaining a clean system state.
2. **The Maintainer's Guidance:** The maintainer explicitly suggests two options: a custom `.set` callback for `module_param_cb` *or* `param_set_uint_minmax()`. They also want us to follow the precedent established by commit `d06a310b45e1` in `drivers/scsi/sg.c`, specifically for `def_reserved_size`. And they want invalid input returning `-EINVAL` or `-ERANGE`.
3. **Analyzing `param_set_uint_minmax()`:** This kernel helper seems ideal. It's purpose-built for validating a numeric parameter within a min/max range. It handles null values, uses `kstrtouint` for parsing, validates the range, and writes the value. It's also `EXPORT_SYMBOL_GPL`, meaning the `sg` module can link to it without problems. It's used across several drivers.
4. **Why Not Use `param_set_uint_minmax` for `def_reserved_size`?** The reason the `def_reserved_size` commit didn't use it is because `def_reserved_size` was initialized to -1 which is a valid default value. `param_set_uint_minmax` expects a positive minimum value, so a custom `.set` callback was used to support a default negative value. `scatter_elem_sz` *doesn't* have a negative default. The initial value `SG_SCATTER_SZ` is non-negative, and it is also initialized after sysfs.
5. **Custom `.set` Callback (Mimicking `def_reserved_size`):** I can create a custom `.set` callback, closely mirroring the structure of `def_reserved_size_set`. This involves using `kstrtoint` (as per the precedent), parsing the input, validating the range, and returning `-ERANGE` or `-EINVAL` on error. It provides the same behavior that's desired by the maintainer.
6. **`kstrtoint` vs. `kstrtouint` and Signedness:** I need to carefully consider `kstrtoint` versus `kstrtouint`. `kstrtouint` would require us to change `scatter_elem_sz` to `unsigned int`. The advantage of using `kstrtoint` is that it allows us to easily check whether `-1` is passed to the paramter, and reject that input.
7. **`int` vs. `unsigned int` for `scatter_elem_sz`:** Is `scatter_elem_sz` better as `int` or `unsigned int`? There doesn't appear to be a technical reason for its current `int` type in the upstream code. The existing code uses it to initialize the value, but that could also be done if it was `unsigned int`. Importantly, even if it remains as `int` it should be fine. It is an internal variable, and `param_set_uint_minmax` converts `scatter_elem_sz` from `unsigned int` to `int` with no problem.
8. **Comparing the Options:**
* **Custom Callback:** Aligns with the *explicit* precedent from commit `d06a310b45e1`. It provides fine-grained control over error messages (returning -ERANGE or -EINVAL). And it can use `kstrtoint` with `int scatter_elem_sz`. The signedness checks need to be explicitly written in the code.
* **`param_set_uint_minmax()`:** More concise and cleaner. Handles most of the validation logic. Returns `-EINVAL` for out-of-range values and also uses `kstrtouint`.
9. **Making The Choice:** Based on the maintainer's directive to follow the exact pattern
|
| 435/4 |
2026/09/09 18:11 |
tool |
codeexpert |
3m
Args: map[Question:In drivers/scsi/sg.c, we need to validate module parameter scatter_elem_sz to ensure it is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER] at configuration time, eliminating runtime mutation and data races in sg_build_indirect().
Commit d06a310b45e1 recently added def_reserved_size_set() using module_param_cb() with a custom callback using kstrtoint() and returning -ERANGE if out of bounds, and -EINVAL on bad input.
Between:
Option 1 (custom .set callback with kstrtoint or kstrtouint, returning -ERANGE when size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)):
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val) return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret) return ret;
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
scatter_elem_sz = size;
return 0;
}
and Option 2 (using param_set_uint_minmax(val, kp, PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER)):
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
return param_set_uint_minmax(val, kp, PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER);
}
Which option better aligns with SCSI / sg subsystem conventions and kernel best practices?
Also, in sg_build_indirect(), scatter_elem_sz_prev was mutated along with scatter_elem_sz without locks. Should scatter_elem_sz_prev be completely removed, and what should the allocation order / loop in sg_build_indirect() look like?]
Results: map[Answer:Option 1 better aligns with SCSI/sg conventions. scatter_elem_sz_prev should be completely removed, and the sg_build_indirect() loop should be simplified to allocate order-sized pages without mutating global state.]
|
| 436/5 |
2026/09/09 18:11 |
agent |
codeexpert |
3m
Model:
Results: map[Answer:Option 1 better aligns with SCSI/sg conventions. scatter_elem_sz_prev should be completely removed, and the sg_build_indirect() loop should be simplified to allocate order-sized pages without mutating global state.]
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.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
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: In drivers/scsi/sg.c, we need to validate module parameter scatter_elem_sz to ensure it is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER] at configuration time, eliminating runtime mutation and data races in sg_build_indirect().
Commit d06a310b45e1 recently added def_reserved_size_set() using module_param_cb() with a custom callback using kstrtoint() and returning -ERANGE if out of bounds, and -EINVAL on bad input.
Between:
Option 1 (custom .set callback with kstrtoint or kstrtouint, returning -ERANGE when size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)):
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val) return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret) return ret;
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
scatter_elem_sz = size;
return 0;
}
and Option 2 (using param_set_uint_minmax(val, kp, PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER)):
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
return param_set_uint_minmax(val, kp, PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER);
}
Which option better aligns with SCSI / sg subsystem conventions and kernel best practices?
Also, in sg_build_indirect(), scatter_elem_sz_prev was mutated along with scatter_elem_sz without locks. Should scatter_elem_sz_prev be completely removed, and what should the allocation order / loop in sg_build_indirect() look like?
|
| 437/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4491
output: 27
thoughts: 553
Thoughts: **Analyzing Module Parameter Validation and Data Race Concerns in `sg.c`**
Okay, so the user wants me to weigh in on the best way to validate the `scatter_elem_sz` module parameter in `drivers/scsi/sg.c`. Specifically, they're looking at two options. The first, which is the current approach in that recent commit, involves a custom `.set` callback using `kstrtoint` (or `kstrtouint`) to perform the validation, returning `-ERANGE` for out-of-bounds values or `-EINVAL` for bad input. The second option proposes using `param_set_uint_minmax`, which seems cleaner by handling the min/max range directly. This is interesting, and I can see the potential benefits of the `param_set_uint_minmax` approach: it's less verbose and likely more robust, as it leverages existing kernel infrastructure. I need to consider which aligns better with SCSI and kernel conventions.
My immediate thoughts are, I need to understand the nuances of the `sg` subsystem and how module parameters are typically handled within it. I should look into the existing conventions in `sg.c` and potentially other relevant SCSI drivers to see how they handle similar validation scenarios. I also have to check the history of the module parameter and its corresponding variable to see the context and the rationale behind the original implementation. I need to figure out which is better from a code maintainability and clarity perspective.
Beyond the validation method itself, the prompt also brings up a potential data race related to `scatter_elem_sz` and `scatter_elem_sz_prev`. It mentions that `scatter_elem_sz_prev` is being mutated alongside `scatter_elem_sz` without any locks. Clearly, this is a serious concern, and I need to investigate the implications of removing `scatter_elem_sz_prev` altogether. The question is, can we eliminate it, and if so, how does that impact the allocation order or looping logic within `sg_build_indirect()`? I need to analyze the code flow within `sg_build_indirect()` to fully understand the impact. I suspect a careful review of how `scatter_elem_sz` is used in that function and in any functions that interact with it is needed.
To start my analysis, I'll need to dive into the `drivers/scsi/sg.c` code, especially focusing on commit `d06a310b45e1` to understand the specific changes that were made. I will be looking closely at how `scatter_elem_sz`, `scatter_elem_sz_prev`, and any related variables are accessed and modified. Then, I will start to think through and try to put in some tool calls to help get the right information to do the required work.
|
| 438/6 |
2026/09/09 18:11 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 439/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6981
output: 33
thoughts: 40
Thoughts: Here's a breakdown of my thought process, focusing on the `drivers/scsi/sg.c` code:
**Diving into the SCSI Scatter-Gather Logic**
Okay, so I'm focusing in on `drivers/scsi/sg.c` – that's where the scatter-gather implementation for SCSI devices lives. I want to zero in on how they handle the scatter-gather lists, specifically related to the size calculations and the indirect descriptor building. My key areas of interest are likely going to be the variables `scatter_elem_sz`, `scatter_elem_sz_prev`, and the function `sg_build_indirect`.
I’m expecting to see how they're figuring out the size of the scatter-gather elements and, more importantly, how that’s affecting the allocation and handling of indirect descriptors. I know scatter-gather is crucial for performance with direct memory access (DMA), so I want to understand how they optimize and handle potential edge cases or limitations in the hardware, especially when dealing with large data transfers or potentially fragmented memory regions. I'll likely be looking for the interplay between memory management, hardware capabilities, and how they construct the command descriptors. The `sg_build_indirect` function is the key here; it's responsible for building the actual lists that the hardware understands, and I want to see how it works internally. I'm expecting to see complexities of handling different hardware limitations, such as maximum segment sizes, and if there are clever workarounds in place. I bet there are some interesting optimizations in there.
|
| 440/6 |
2026/09/09 18:11 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 441/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 8403
output: 37
thoughts: 38
Thoughts: Here's a breakdown of my thought process, focusing on the `sg_build_indirect` function within the SCSI generic driver:
**Analyzing the Indirect SCSI Command Building**
Okay, I'm diving into `drivers/scsi/sg.c`, specifically around line 1850 through 1940. I need to understand how indirect SCSI commands are constructed using `sg_build_indirect`. Given my expertise in this area, my focus is going to be on the nuances of this function and how it handles the different elements within the SCSI command descriptor block (CDB) and data transfer parameters.
I need to quickly assess how it handles scatter-gather lists. I'll watch for how it interacts with the physical pages and their addresses. I'll need to figure out what the function's responsibility is, and how that responsibility is handled. It seems that it is responsible for building a list of data buffers to describe a data transfer.
I need to understand if there are any potential race conditions, or performance concerns with this process. I'll look at the data flow: what are the inputs it expects (like the sg list, the CDB, the data direction), what modifications it makes to these inputs, and what outputs it provides. Are there any error checks, and how are these handled? Is there a memory allocation strategy that might be less than optimal? Is it using any specific locking mechanisms? Are there any aspects of the code that are particularly clever or worth noting for future reference?
Essentially, I'm expecting to determine if this piece of code is written in an efficient and robust way. I'm looking for anything that might be a pain point for scalability or optimization. I'm going to look at the interactions to other parts of the SCSI subsystem, to determine how the build of an indirect command is integrated into a larger sequence of operations. This is the stage I'm at. Let's see what the code reveals!
|
| 442/6 |
2026/09/09 18:11 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1850 LineCount:80]
Results: map[Contents:1850: return tablesize; /* number of scat_gath elements allocated */
1851: }
1852:
1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
]
|
| 443/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10242
output: 22
thoughts: 975
Thoughts: **Vulnerability Assessment: sg_build_indirect in the sg Module**
Okay, I'm looking at `sg_build_indirect` and immediately my attention is drawn to `scatter_elem_sz` and `scatter_elem_sz_prev`. Let me see what this function does. Oh, here's the code. Now, I see that these variables are used to determine the size of the scatter gather elements. Lines 1899-1904 are particularly interesting.
Hang on a second… what's going on here? Why is `scatter_elem_sz` being *mutated* within this function? I'm getting a bad feeling about this. If someone passes a value for `scatter_elem_sz` of, let's say, 5000 bytes on a 4KB page system, `get_order(5000)` will return 1, and `ret_sz` becomes 8192. Then, this condition `ret_sz > scatter_elem_sz_prev` (8192 > 5000) is true, so `scatter_elem_sz` gets rounded up to 8192! And…wait a minute… this `scatter_elem_sz` is a *global module parameter*!
This is an issue! That means concurrent calls to `sg_build_indirect` could be reading and modifying `scatter_elem_sz` and `scatter_elem_sz_prev` simultaneously. That's a textbook race condition, right there.
But it gets worse. I'm now also considering negative `num` values, or when `order > MAX_PAGE_ORDER`! Let me check `get_order(num)`... ah, yes, if `num` is huge, or non-positive this could trigger some integer overflow or underflow issues.
Wait a second, what happens if this `scatter_elem_sz` is set via sysfs? Ah, here we are:
`module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);`
Anyone with root can do something like:
`echo -1 > /sys/module/sg/parameters/scatter_elem_sz`
or `echo 0 > ...`
or `echo 1000000000000 > ...`!
Now I'm really concerned. What if `scatter_elem_sz` is set to something larger than `PAGE_SIZE << MAX_PAGE_ORDER`? The `order` would become larger than `MAX_PAGE_ORDER`, and `alloc_pages(gfp_mask, order)` could trigger a `WARN_ON_ONCE`, or even cause a failure, crash, or lead to undefined behavior! This could be a serious vulnerability. Let's make sure to check the use of `param_set_uint_minmax` for this kind of parameter to ensure these values are under control, instead of some potentially unsafe custom callback.
|
| 444/6 |
2026/09/09 18:11 |
tool |
grepper |
0m
Args: map[Expression:param_set_uint_minmax]
Results: map[Output:drivers/block/ublk_drv.c=5945=static int ublk_set_max_unprivileged_ublks(const char *buf,
--
drivers/block/ublk_drv.c-5947-{
drivers/block/ublk_drv.c:5948: return param_set_uint_minmax(buf, kp, 0, UBLK_MAX_UBLKS);
drivers/block/ublk_drv.c-5949-}
--
drivers/nvme/host/pci.c=341=static int io_queue_depth_set(const char *val, const struct kernel_param *kp)
drivers/nvme/host/pci.c-342-{
drivers/nvme/host/pci.c:343: return param_set_uint_minmax(val, kp, NVME_PCI_MIN_QUEUE_SIZE,
drivers/nvme/host/pci.c-344- NVME_PCI_MAX_QUEUE_SIZE);
--
drivers/ufs/core/ufs-mcq.c=40=static int rw_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-41-{
drivers/ufs/core/ufs-mcq.c:42: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_RW_QUEUES,
drivers/ufs/core/ufs-mcq.c-43- num_possible_cpus());
--
drivers/ufs/core/ufs-mcq.c=56=static int read_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-57-{
drivers/ufs/core/ufs-mcq.c:58: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_READ_QUEUES,
drivers/ufs/core/ufs-mcq.c-59- num_possible_cpus());
--
drivers/ufs/core/ufs-mcq.c=72=static int poll_queue_count_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-mcq.c-73-{
drivers/ufs/core/ufs-mcq.c:74: return param_set_uint_minmax(val, kp, UFS_MCQ_MIN_POLL_QUEUES,
drivers/ufs/core/ufs-mcq.c-75- num_possible_cpus());
--
drivers/ufs/core/ufs-txeq.c=25=static int txeq_gear_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-txeq.c-26-{
drivers/ufs/core/ufs-txeq.c:27: return param_set_uint_minmax(val, kp, UFS_HS_G1, UFS_HS_GEAR_MAX);
drivers/ufs/core/ufs-txeq.c-28-}
--
drivers/ufs/core/ufs-txeq.c=47=static int txeq_setting_sel_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufs-txeq.c-48-{
drivers/ufs/core/ufs-txeq.c:49: return param_set_uint_minmax(val, kp, 0, 1);
drivers/ufs/core/ufs-txeq.c-50-}
--
drivers/ufs/core/ufshcd.c=125=static int uic_cmd_timeout_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufshcd.c-126-{
drivers/ufs/core/ufshcd.c:127: return param_set_uint_minmax(val, kp, UIC_CMD_TIMEOUT_DEFAULT,
drivers/ufs/core/ufshcd.c-128- UIC_CMD_TIMEOUT_MAX);
--
drivers/ufs/core/ufshcd.c=142=static int dev_cmd_timeout_set(const char *val, const struct kernel_param *kp)
drivers/ufs/core/ufshcd.c-143-{
drivers/ufs/core/ufshcd.c:144: return param_set_uint_minmax(val, kp, QUERY_REQ_TIMEOUT_MIN,
drivers/ufs/core/ufshcd.c-145- QUERY_REQ_TIMEOUT_MAX);
--
include/linux/moduleparam.h=461=int param_get_uint(char *buffer, const struct kernel_param *kp);
include/linux/moduleparam.h:462:int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
include/linux/moduleparam.h-463- unsigned int min, unsigned int max);
--
kernel/params.c=242=STANDARD_PARAM_DEF(hexint, unsigned int, "%#08x", kstrtouint);
kernel/params.c-243-
kernel/params.c:244:int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
kernel/params.c-245- unsigned int min, unsigned int max)
--
kernel/params.c-259-}
kernel/params.c:260:EXPORT_SYMBOL_GPL(param_set_uint_minmax);
kernel/params.c-261-
--
kernel/sched/ext/ext.c=227=static int set_slice_us(const char *val, const struct kernel_param *kp)
kernel/sched/ext/ext.c-228-{
kernel/sched/ext/ext.c:229: return param_set_uint_minmax(val, kp, 100, 100 * USEC_PER_MSEC);
kernel/sched/ext/ext.c-230-}
--
kernel/sched/ext/ext.c=237=static int set_bypass_lb_intv_us(const char *val, const struct kernel_param *kp)
kernel/sched/ext/ext.c-238-{
kernel/sched/ext/ext.c:239: return param_set_uint_minmax(val, kp, 0, 10 * USEC_PER_SEC);
kernel/sched/ext/ext.c-240-}
--
mm/page_reporting.c=18=static int page_order_update_notify(const char *val, const struct kernel_param *kp)
--
mm/page_reporting.c-23- */
mm/page_reporting.c:24: return param_set_uint_minmax(val, kp, 0, MAX_PAGE_ORDER);
mm/page_reporting.c-25-}
--
net/ipv4/tcp_dctcp.c=62=static int dctcp_shift_g_set(const char *val, const struct kernel_param *kp)
net/ipv4/tcp_dctcp.c-63-{
net/ipv4/tcp_dctcp.c:64: return param_set_uint_minmax(val, kp, 0, 10);
net/ipv4/tcp_dctcp.c-65-}
--
net/sunrpc/xprtsock.c=3730=static int param_set_portnr(const char *val, const struct kernel_param *kp)
net/sunrpc/xprtsock.c-3731-{
net/sunrpc/xprtsock.c:3732: return param_set_uint_minmax(val, kp,
net/sunrpc/xprtsock.c-3733- RPC_MIN_RESVPORT,
--
net/sunrpc/xprtsock.c=3748=static int param_set_slot_table_size(const char *val,
--
net/sunrpc/xprtsock.c-3750-{
net/sunrpc/xprtsock.c:3751: return param_set_uint_minmax(val, kp,
net/sunrpc/xprtsock.c-3752- RPC_MIN_SLOT_TABLE,
--
net/sunrpc/xprtsock.c=3764=static int param_set_max_slot_table_size(const char *val,
--
net/sunrpc/xprtsock.c-3766-{
net/sunrpc/xprtsock.c:3767: return param_set_uint_minmax(val, kp,
net/sunrpc/xprtsock.c-3768- RPC_MIN_SLOT_TABLE,
]
|
| 445/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14110
output: 37
thoughts: 25
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into `param_set_uint_minmax` Implementation**
Okay, time to dig into the guts of `kernel/params.c` and specifically, the `param_set_uint_minmax` function. I'm expecting to see a pretty standard pattern here, but the devil's in the details, as always. My immediate concerns will be around:
* **Error Handling:** How robust is the input validation? Does it check for NULL pointers for the `param` struct and any associated data? Are there checks for values *below* the minimum or *above* the maximum allowed uint? Are error codes clearly defined and propagated appropriately? This needs to be bulletproof. I'm hoping to see a solid `EINVAL` or similar for out-of-bounds attempts.
* **Atomicity/Concurrency:** If this is a multi-threaded environment (and let's assume it is, given we're in kernel space), what measures are in place to ensure atomic updates? Is there a mutex protecting the parameter's data? Are there read/write locks or atomic operations being used to avoid race conditions? I'll be particularly scrutinizing this section, as integer overflow is a common problem.
* **Data Type Considerations:** Is the uint being stored in the most efficient manner, given the architecture? Is there any sign extension that needs to be accounted for? Are there any compiler optimizations that may impact the expected behavior, such as if we're dealing with different word sizes?
* **Logging/Debugging:** Is there sufficient logging, either for success or failure? Ideally, I'd like to see debug messages that identify the parameter name, the attempted value, and the min/max bounds. This is absolutely critical for tracking down subtle issues during testing and debugging.
* **Range Checks:** Of course, there need to be range checks! I'll be checking these to see if they are correct, and if any overflow issues could occur.
Essentially, I'm expecting to see a well-structured function with rigorous error handling, attention to concurrency, and clear, informative logging. It needs to be safe, efficient, and easy to debug. Let's see if the code lives up to these expectations... time to start reading.
|
| 446/6 |
2026/09/09 18:11 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/params.c Name:param_set_uint_minmax]
Results: map[SourceCode: 244: int param_set_uint_minmax(const char *val, const struct kernel_param *kp,
245: unsigned int min, unsigned int max)
246: {
247: unsigned int num;
248: int ret;
249:
250: if (!val)
251: return -EINVAL;
252: ret = kstrtouint(val, 0, &num);
253: if (ret)
254: return ret;
255: if (num < min || num > max)
256: return -EINVAL;
257: *((unsigned int *)kp->arg) = num;
258: return 0;
259: }
SourceFile:kernel/params.c]
|
| 447/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14906
output: 29
thoughts: 623
Thoughts: **Analyzing Parameter Setting for SCSI/SG Subsystem**
Okay, so I'm looking at this `param_set_uint_minmax` function and immediately my expert brain jumps to the implications of using it. It's a straightforward way to set an unsigned integer parameter with minimum and maximum bounds. The task at hand is to determine the best approach for setting `scatter_elem_sz` within the SCSI/sg subsystem. I've got two options: a custom `.set` callback using `kstrtoint` and returning `-ERANGE` for out-of-bounds values, or leveraging `param_set_uint_minmax`. The key here is adherence to established conventions and kernel best practices.
My gut feeling is leaning towards `param_set_uint_minmax`. It's a kernel-provided utility, and using it implies a certain level of standardization. It's less code to maintain, and likely has been reviewed and tested thoroughly within the kernel community. On the other hand, the custom callback gives more control. The crucial thing now is to actually _see_ what the current best practices *are* within this subsystem. I need to get some context and confirm my initial thought.
The prompt is asking which option better aligns with SCSI / sg subsystem conventions and kernel best practices, and it highlights a concern about lock usage. I have to verify if `scatter_elem_sz_prev` should be removed completely and how the allocation order/loop within `sg_build_indirect()` should be handled. It looks like it was changed without using any locks, and that's not acceptable!
Alright, it's time to check the git history of `scatter_elem_sz` within `drivers/scsi/sg.c`, and other module parameters in `drivers/scsi/` in general. I want to see how these kinds of parameters are typically handled. More importantly, let's look at recent changes to `drivers/scsi/sg.c` to see if there are any other similar patterns. That should give me the real answer to this question! Let's get to it!
|
| 448/6 |
2026/09/09 18:11 |
tool |
git-log |
0m
Args: map[Count:10 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
5e2fde1a9433 block: pass io_comp_batch to rq_end_io_fn callback
0e1677654259 scsi: sg: Fix occasional bogus elapsed time that exceeds timeout
90449f2d1e1f scsi: sg: Do not sleep in atomic context
]
|
| 449/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16291
output: 31
thoughts: 34
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Digging Deeper into SCSI Driver Parameter Tuning**
Right, so we've got a handle on the initial problem, but I need to be thorough. I'm thinking, "Let's not just stop at the obvious." I need to expand the search and go deeper into the SCSI driver's parameter space. My brain's whirring, specifically on the `drivers/scsi` directory. I'm expanding my query.
I'm thinking, I know `param_set_uint_minmax` is important, that's almost always a good place to start when you are tuning the module, but I want to cast a wider net. I'll need to use other types of setting functions, so I am going to search for `param_set_` generally, as well as `param_set_uint_minmax`. I need to review and understand everything I can. After all, if there are module parameters, there is likely a function to set them.
That should unearth some interesting configuration knobs I might have missed in the initial scan. This is where the real nuance lies, figuring out the interactions, and identifying the optimal parameters for this specific hardware/software combination. This is where the fun begins.
|
| 450/6 |
2026/09/09 18:11 |
tool |
grepper |
0m
Args: map[Expression:module_param PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c:1625:module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1626-
--
drivers/scsi/sg.c=1646=static const struct kernel_param_ops def_reserved_size_ops = {
--
drivers/scsi/sg.c-1650-
drivers/scsi/sg.c:1651:module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
drivers/scsi/sg.c-1652- S_IRUGO | S_IWUSR);
]
|
| 451/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16918
output: 32
thoughts: 29
Thoughts: Here's my take on the thought process, as if it were my own:
**Investigating SCSI Driver Parameter Handling**
Okay, so I need to figure out how these SCSI drivers handle their parameters. Given what I know about kernel module parameters, I'm pretty sure there's going to be a standard way of doing this. My first instinct is to zero in on the `drivers/scsi` directory. That's the logical place to start looking for the core SCSI driver implementations.
Specifically, I'm expecting to find either `param_set_uint_minmax`, or `module_param_cb` being used. `param_set_uint_minmax` is the classic way to define a module parameter with a defined range, making sure nothing can be set out of bounds. `module_param_cb` is more flexible, letting me specify a custom callback function for more complex logic, validation, or side effects. I need to figure out which approach they've taken, or if they've cooked up something completely different. I'll start the search there. That should get me pointed in the right direction.
|
| 452/6 |
2026/09/09 18:11 |
tool |
grepper |
0m
Error:
Args: map[Expression:param_set_uint_minmax PathPrefix:drivers/scsi]
Results:
|
| 453/6 |
2026/09/09 18:11 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17232
output: 32
thoughts: 874
Thoughts: **Analyzing Parameter Setting in `drivers/scsi/sg.c`**
Okay, so I was wondering about the usage of `param_set_uint_minmax` in the `drivers/scsi` directory, and I didn't see it used directly. But wait, I should check `drivers/scsi/sg.c` itself. Right! And in `sg.c`, I see a commit, d06a310b45e1, authored by Yang Erkun, reviewed by Bart Van Assche, and applied by Martin K. Petersen. This is the place to start, clearly.
This commit introduces a `def_reserved_size_set` function. Let's dig in a bit. Okay, so now I'm thinking, why does the code in Option 1 use `-ERANGE` and not `-EINVAL`? I need to compare this to `param_set_uint_minmax`. Looking at the source of that function:
```c
if (num < min || num > max)
return -EINVAL;
*((unsigned int *)kp->arg) = num;
return 0;
```
Interesting. Now, I see that the core of what `param_set_uint_minmax` does is this line: `*((unsigned int *)kp->arg) = num;`. It writes an `unsigned int` to the memory pointed to by `kp->arg`. I should probably check the types here. What's the type of `scatter_elem_sz`? Hmm, in `drivers/scsi/sg.c`, `static int scatter_elem_sz = SG_SCATTER_SZ;`. So, it's an `int` or `unsigned int`. Okay, if we use Option 2:
```c
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
return param_set_uint_minmax(val, kp, PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER);
}
```
If `kp->arg` points to `&scatter_elem_sz`, then `param_set_uint_minmax` writes an `unsigned int` to this memory address.
Now, let's step back, and consider `def_reserved_size_set`. It's defined in the same commit.
```c
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
/* limit to 1 MB */
if (size < 0 || size > 1048576)
return -ERANGE;
def_reserved_size = size;
return 0;
}
```
The commit message specifically mentions validation. The message states, "The fix is to use module_param_cb to validate and reject invalid values assigned to def_reserved_size." Okay, so the function uses `-ERANGE` for the size validation. I'm going to have to dig into why. To continue, I'll need to check the context of where `sg_proc_write_dressz` is defined in `drivers/scsi/sg.c`.
|
| 454/6 |
2026/09/09 18:12 |
tool |
grepper |
0m
Args: map[Expression:sg_proc_write_dressz PathPrefix:drivers/scsi]
Results: map[Output:drivers/scsi/sg.c=2314=static int sg_proc_single_open_dressz(struct inode *inode, struct file *file);
drivers/scsi/sg.c:2315:static ssize_t sg_proc_write_dressz(struct file *filp,
drivers/scsi/sg.c-2316- const char __user *buffer, size_t count, loff_t *off);
drivers/scsi/sg.c=2317=static const struct proc_ops dressz_proc_ops = {
--
drivers/scsi/sg.c-2320- .proc_lseek = seq_lseek,
drivers/scsi/sg.c:2321: .proc_write = sg_proc_write_dressz,
drivers/scsi/sg.c-2322- .proc_release = single_release,
--
drivers/scsi/sg.c=2406=static ssize_t
drivers/scsi/sg.c:2407:sg_proc_write_dressz(struct file *filp, const char __user *buffer,
drivers/scsi/sg.c-2408- size_t count, loff_t *off)
]
|
| 455/6 |
2026/09/09 18:12 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 19211
output: 37
thoughts: 26
Thoughts: Here's my summary, as though I'm thinking through this code:
**Diving into `sg_proc_write_dressz`**
Okay, so I'm looking at `sg_proc_write_dressz` in the `drivers/scsi/sg.c` file. Right, I remember, that's the function handling the writing to the `/proc/scsi/sg/*` entry for the "dress" parameter, if I'm not mistaken. I need to refresh my memory on what that does, exactly. It's related to setting the DMA alignment or scatter-gather buffer addressing. I know it's a critical area for performance and sometimes compatibility with specific SCSI devices. Let's see how they've handled the input and what validation they're doing. I want to see if any potential race conditions exist, and if it could have any issues with new hardware. I also want to make sure no assumptions are being made that are going to cause problems. This could impact everything from simple reads and writes to more complex commands, so I want to be thorough.
|
| 456/6 |
2026/09/09 18:12 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:2405 LineCount:35]
Results: map[Contents:2405:
2406: static ssize_t
2407: sg_proc_write_dressz(struct file *filp, const char __user *buffer,
2408: size_t count, loff_t *off)
2409: {
2410: int err;
2411: unsigned long k = ULONG_MAX;
2412:
2413: if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2414: return -EACCES;
2415:
2416: err = kstrtoul_from_user(buffer, count, 0, &k);
2417: if (err)
2418: return err;
2419: if (k <= 1048576) { /* limit "big buff" to 1 MB */
2420: def_reserved_size = k;
2421: return count;
2422: }
2423: return -ERANGE;
2424: }
2425:
2426: static int sg_proc_seq_show_version(struct seq_file *s, void *v)
2427: {
2428: seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR,
2429: sg_version_date);
2430: return 0;
2431: }
2432:
2433: static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v)
2434: {
2435: seq_puts(s, "host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n");
2436: return 0;
2437: }
2438:
2439: struct sg_proc_deviter {
]
|
| 457/6 |
2026/09/09 18:12 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 20054
output: 41
thoughts: 645
Thoughts: **Analyzing Parameter Setting Best Practices in the SCSI Subsystem**
Okay, so I'm looking at these two options for setting the `scatter_elem_sz` parameter. The core issue is ensuring the value stays within a specific range: `PAGE_SIZE` to `PAGE_SIZE << MAX_PAGE_ORDER`. And I need to align the approach with both kernel best practices *and* the SCSI/sg subsystem conventions.
Right now, I'm thinking about how `sg_proc_write_dressz` returns `-ERANGE` if the size goes over `k > 1048576`, and how `def_reserved_size_set` was designed to align with that behavior by returning `-ERANGE` for out-of-range inputs and `-EINVAL` for bad input.
So, Option 1 is a custom `.set` callback using `kstrtoint`. It returns `-ERANGE` for values outside the allowed range, just like `def_reserved_size_set`. This seems consistent at first glance.
Option 2 leverages `param_set_uint_minmax`, which handles the range checking for me. It's concise. But, does it follow the subsystem convention?
Now, let's step back and re-read the *question*. It's about which option is better and about what exactly each of the options *does*. The real analysis starts here.
Analyzing Option 1: It mirrors `def_reserved_size_set` in `drivers/scsi/sg.c`, specifically commit `d06a310b45e1`. This is good, because I want to stick to the pattern! I'm seeing consistency here with the use of `-ERANGE` for out-of-bounds values, like `sg_proc_write_dressz`. This seems like a reasonable implementation. But what is Option 2 going to do?
Now I'm diving deeper. I need to understand kernel best practices *versus* subsystem conventions. What are the common patterns? What are other examples?
Time to dig into the kernel. I'm going to search for discussions, patches, and other module parameter callbacks, specifically focusing on the SCSI subsystem. I will look for references to `scatter_elem_sz` in git history on the SCSI mailing list. Finally, I need to do a `git log` on `scatter_elem_sz` across the entire history to get the complete picture. This should tell me everything I need to know about the conventions.
|
| 458/6 |
2026/09/09 18:12 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz Count:10 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 459/6 |
2026/09/09 18:12 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21337
output: 27
thoughts: 19
Thoughts: Okay, here's my attempt at summarizing my internal thought process as a subject matter expert, starting with a bolded header:
**Diving into Commit 6460e75a104d**
Alright, let's take a look at this commit, 6460e75a104d. Right off the bat, I need to understand the context. What's the scope of this one? What project is it in? What's the history around it? Knowing the branch and surrounding commits will give me the best idea of intent here. I'm already anticipating what to find based on what's been merged around it. Is this a bug fix? Feature implementation? Refactoring effort? The commit message better tell me what I am about to see. I am mentally prepared to jump to the code and evaluate for potential issues based on what I see here. Let's see if this lines up with my expectations. Time to dig in...
|
| 460/6 |
2026/09/09 18:12 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 461/6 |
2026/09/09 18:12 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 25999
output: 26
thoughts: 418
Thoughts: **Analyzing Scatter Gather Element Size Changes**
Alright, let's dive into this code. It seems like back in 2006, specifically with commit `6460e75a104d`, `scatter_elem_sz` and `scatter_elem_sz_prev` were introduced. I want to understand the rationale behind `scatter_elem_sz_prev`. Looking at the code from that commit, the purpose of `scatter_elem_sz_prev` is immediately clear: it's used to store a previous value to detect changes in the scatter element size. It looks like the code attempts to optimize by adjusting `scatter_elem_sz` to `PAGE_SIZE` if it's smaller.
It's set in this `if` block:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The loop that follows, where the scatter gather entries are built, appears to use `scatter_elem_sz_prev` to calculate the amount to allocate with `sg_page_malloc`. It seems like `scatter_elem_sz_prev` is updated inside the loop if `ret_sz` is larger.
```c
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
```
Okay, so it seems like the code is trying to minimize allocation sizes by caching a previously used size, but updating this size if the driver requested a larger buffer, presumably in an attempt to handle fragmentation, or some other memory issue.
Now, I need to see how commit `10db10d144c0` modified `sg_build_indirect`, because it seems relevant to this.
|
| 462/6 |
2026/09/09 18:12 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 463/6 |
2026/09/09 18:12 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 36640
output: 22
thoughts: 2878
Thoughts: **Analyzing Module Parameter Validation and Memory Allocation in SCSI/SG Subsystem**
Alright, let's break this down. My immediate focus is on the commit `10db10d144c0` and its impact on the `sg_build_indirect` function. It looks like the old approach of allocating pages individually using `sg_page_malloc` has been replaced by allocating blocks of pages with a uniform order via `alloc_pages`. This is definitely a performance optimization, but the devil, as always, is in the details.
The first thing I'm noticing is the role of `scatter_elem_sz` and `scatter_elem_sz_prev`. In the new code, `num` is only utilized within the logging and a conditional check. It's effectively doing nothing apart from an `if` statement to mutate these global variables. The allocation size (`ret_sz`) is determined *exclusively* by the order passed to `alloc_pages`, so whatever the value of `num` is, it is only updating `scatter_elem_sz` and `scatter_elem_sz_prev` if `ret_sz` is larger. It really seems superfluous. I have to figure out how `scatter_elem_sz` should be validated!
Now, this `retry` loop and the decrement of `order`... if allocation fails, it retries with a smaller page size. However, what is the role of the `scatter_elem_sz`? I remember in the `init_sg` function `scatter_elem_sz` is initialized to either `SG_SCATTER_SZ` or `PAGE_SIZE`, depending which is larger. It's also modifiable via module parameters.
Then, there is the problem of the `scatter_elem_sz` and `scatter_elem_sz_prev` updating. I believe they will require protection via a lock.
So the question is: which validation approach is better. Option 1: Custom callback using kstrtoint. Option 2: param_set_uint_minmax. Both should return error, however the custom callback appears to be doing better: d06a310b45e1. However, both will return the right error.
What about `param_set_uint_minmax`?
Next up, how to remove `scatter_elem_sz_prev`.
Since `num` is not utilized at all in the loop for memory allocation, and is only utilized for updating `scatter_elem_sz_prev`, I believe this can be eliminated.
The revised loop should look something like:
```c
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, ret_sz=%d\n", k, ret_sz));
} /* end of for loop */
schp->page_order = order;
schp->k_use_sg = k;
```
|
| 464/6 |
2026/09/09 18:12 |
tool |
git-log |
0m
Args: map[MessageRegexps:[def_reserved_size]]
Results: map[Output:d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
cd1c34f21f5b Documentation: Delete final reference to "sg_def_reserved_size" kernel parm
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 465/6 |
2026/09/09 18:13 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 40355
output: 24
thoughts: 512
Thoughts: **Diving into that `sg` Soft Lockup Fix**
Okay, let's revisit commit `d06a310b45e1`. Right, this is about the `sg` driver and that soft lockup when opening `/dev/sgX`. The issue boils down to an unchecked `def_reserved_size` parameter – apparently, someone could bypass the limit enforced by `sg_proc_write_dressz` and cause a lockup by directly modifying the module parameter. The fix makes use of `module_param_cb` for validation. Makes sense; that's the correct approach to prevent such issues.
But hold on... that patch link! `https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com`. That `...-3` at the end means it's part of a series! Now I'm curious. What was the *first* patch in that series? Or maybe even the second or fourth? I'm going to scan the git log and look for commits by Yang Erkun in January 2026. This might provide more context to the original problem and the complete set of solutions that were tried. It's almost always useful to see the bigger picture.
|
| 466/6 |
2026/09/09 18:13 |
tool |
git-log |
0m
Args: map[Count:5 MessageRegexps:[Yang Erkun]]
Results: map[Output:326d49039c10 nbd: add pre_defined_connections module parameter for pre-created devices
a9d414b4a15c nbd: remove queue freeze for newly created nbd from netlink path
f8d21c590e55 nbd: factor out a nbd_genl_foreach_sock
db285268df79 nbd: skip queue freeze when setting size at device startup
285908f554fe nbd: remove queue freeze in nbd_add_socket
]
|
| 467/6 |
2026/09/09 18:13 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 41324
output: 35
thoughts: 18
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Investigating Recent Code Changes**
Okay, I need to pinpoint the relevant commits. My initial approach will be to leverage the `git log` command. I'll target the search around the timeframe suggested, and likely broaden the scope using more precise date ranges if the first pass is too broad.
Next, I'll incorporate message regular expressions using `sg`. This is often a more effective way to filter commits than just dates, especially if I have some keywords or a general idea of what was modified. I can use this in combination with the date criteria for a more efficient search or to refine results if the date search is too noisy. This should allow me to narrow down the potential candidates quickly and efficiently.
|
| 468/6 |
2026/09/09 18:13 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/scsi/sg.c Since:3 months]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
]
|
| 469/6 |
2026/09/09 18:13 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 41578
output: 25
thoughts: 38
Thoughts: Here's a summary of my immediate thought process, focusing on the code references:
**Analyzing SCSI Driver Commits**
Okay, so the initial focus is on investigating two specific commits within the `drivers/scsi/sg.c` file. These are identified by their unique SHA-1 hashes: `50209dec14f8` and `3033c471aaf6`. The fact that I'm being directed to look at this specific driver and these commits suggests something of interest or concern is related to SCSI generic device access in this version of the kernel. This `sg.c` file is the entrypoint for userspace programs to directly access SCSI devices. I'll need to use these hashes to pull up those specific changes in the version control system. Then I'll quickly examine the changes in context. I'll try to understand if there are related commits and what adjacent code was altered. I need to understand the intent and the specific changes, what problem was being solved, or what feature was being added. What are the dependencies? I'll probably start with the more recent commit, then work backward to understand the context. This likely involves understanding any associated bug reports, mailing list discussions, or other commit messages that might shed light on the changes. My primary goal is to quickly pinpoint any potential vulnerabilities, performance regressions, or functional changes in the SCSI generic driver that could impact userspace applications.
|
| 470/6 |
2026/09/09 18:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 3033c471aaf675254efaa0da431e95d91a104b41
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:42 2026 +0800
scsi: sg: Fix sysctl sg-big-buff register during sg_init()
Commit 26d1c80fd61e ("scsi/sg: move sg-big-buff sysctl to scsi/sg.c") made
a mistake. sysctl sg-big-buff was not created because the call to
register_sg_sysctls() was placed on the wrong code path.
Fixes: 26d1c80fd61e ("scsi/sg: move sg-big-buff sysctl to scsi/sg.c")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-2-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 37bac49f30f0..71d34186dec9 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1691,13 +1691,13 @@ init_sg(void)
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
+ register_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
return 0;
}
class_unregister(&sg_sysfs_class);
- register_sg_sysctls();
err_out:
unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
return rc;
]
|
| 471/6 |
2026/09/09 18:13 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 42550
output: 25
thoughts: 18
Thoughts: Okay, here's my interpretation of what's going through my mind, delivered as a first-person summary, keeping in mind the audience is an expert:
**Analyzing Commit 50209dec14f8**
Alright, let's dive in. Commit 50209dec14f8... I need to refresh my memory on the context of this one. It's been a while since I last looked at it. Let me see... I need to quickly run through the diff, focusing on anything that might be problematic or that could introduce regressions. I'm looking for the usual suspects: potential performance bottlenecks, any subtle logic errors, changes to public interfaces that might break existing integrations, and any dependencies this commit introduces or alters. Let's see if the commit message provides any clue to begin with, or if it lacks the proper information. I also need to make sure that the suggested changes don't violate any established coding style. I am interested in performance.
|
| 472/6 |
2026/09/09 18:13 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 50209dec14f8c594a9ef26237b7e7ddd39e12a40
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:44 2026 +0800
scsi: sg: Remove deprecated sg-big-buff
These deprecated sysctl has been broken since commit 26d1c80fd61e
("scsi/sg: move sg-big-buff sysctl to scsi/sg.c") and nobody has found
this. I believe it's time to remove it, which will allow us to clean up a
significant amount of code.
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-4-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index f38d36fbeef3..2b4b2a1a8e44 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -81,14 +81,14 @@ static int sg_proc_init(void);
#define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
-static int sg_big_buff = SG_DEF_RESERVED_SIZE;
/* N.B. This variable is readable and writeable via
- /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
- of this size (or less if there is not enough memory) will be reserved
- for use by this file descriptor. [Deprecated usage: this variable is also
- readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into
- the kernel (i.e. it is not a module).] */
-static int def_reserved_size = -1; /* picks up init parameter */
+ * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
+ * of this size (or less if there is not enough memory) will be reserved
+ * for use by this file descriptor.
+ */
+
+/* picks up init parameter */
+static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
@@ -1663,35 +1663,6 @@ MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
-#ifdef CONFIG_SYSCTL
-#include <linux/sysctl.h>
-
-static const struct ctl_table sg_sysctls[] = {
- {
- .procname = "sg-big-buff",
- .data = &sg_big_buff,
- .maxlen = sizeof(int),
- .mode = 0444,
- .proc_handler = proc_dointvec,
- },
-};
-
-static struct ctl_table_header *hdr;
-static void register_sg_sysctls(void)
-{
- if (!hdr)
- hdr = register_sysctl("kernel", sg_sysctls);
-}
-
-static void unregister_sg_sysctls(void)
-{
- unregister_sysctl_table(hdr);
-}
-#else
-#define register_sg_sysctls() do { } while (0)
-#define unregister_sg_sysctls() do { } while (0)
-#endif /* CONFIG_SYSCTL */
-
static int __init
init_sg(void)
{
@@ -1701,10 +1672,6 @@ init_sg(void)
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
- if (def_reserved_size >= 0)
- sg_big_buff = def_reserved_size;
- else
- def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1716,7 +1683,6 @@ init_sg(void)
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
- register_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
@@ -1731,7 +1697,6 @@ init_sg(void)
static void __exit
exit_sg(void)
{
- unregister_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
remove_proc_subtree("scsi/sg", NULL);
#endif /* CONFIG_SCSI_PROC_FS */
@@ -2207,10 +2172,8 @@ sg_add_sfp(Sg_device * sdp)
write_unlock_irqrestore(&sdp->sfd_lock, iflags);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_add_sfp: sfp=0x%p\n", sfp));
- if (unlikely(sg_big_buff != def_reserved_size))
- sg_big_buff = def_reserved_size;
- bufflen = min_t(int, sg_big_buff,
+ bufflen = min_t(int, def_reserved_size,
max_sectors_bytes(sdp->device->request_queue));
sg_build_reserve(sfp, bufflen);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
@@ -2438,7 +2401,7 @@ sg_proc_write_adio(struct file *filp, const char __user *buffer,
static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)
{
- return single_open(file, sg_proc_seq_show_int, &sg_big_buff);
+ return single_open(file, sg_proc_seq_show_int, &def_reserved_size);
}
static ssize_t
@@ -2455,7 +2418,7 @@ sg_proc_write_dressz(struct file *filp, const char __user *buffer,
if (err)
return err;
if (k <= 1048576) { /* limit "big buff" to 1 MB */
- sg_big_buff = k;
+ def_reserved_size = k;
return count;
}
return -ERANGE;
@@ -2628,7 +2591,7 @@ static int sg_proc_seq_show_debug(struct seq_file *s, void *v)
if (it && (0 == it->index))
seq_printf(s, "max_active_device=%d def_reserved_size=%d\n",
- (int)it->max, sg_big_buff);
+ (int)it->max, def_reserved_size);
read_lock_irqsave(&sg_index_lock, iflags);
sdp = it ? sg_lookup_dev(it->index) : NULL;
]
|
| 473/6 |
2026/09/09 18:13 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 44876
output: 29
thoughts: 1855
Thoughts: **Analyzing the `scatter_elem_sz` Parameter in the SCSI/SG Subsystem**
Okay, let's break this down. We're looking at two options for setting the `scatter_elem_sz` parameter, and I need to figure out which aligns better with the existing conventions and best practices within the SCSI/SG subsystem, as well as general kernel guidelines.
First, let's establish the context. We've got a series of patches in January 2026 dealing with the `sg` driver, and it looks like there were some concerns about the `sg-big-buff` functionality. This parameter is crucial because its purpose is related to the allocation order in `sg_build_indirect()`. This means it has an impact on how scatter-gather lists are constructed.
Now, we're presented with two approaches:
* **Option 1:** A custom `.set` callback using `kstrtoint` (or similar) to handle the parameter's value, returning `-ERANGE` for values outside the acceptable range (less than `PAGE_SIZE` or greater than `PAGE_SIZE << MAX_PAGE_ORDER`) and other error codes as appropriate.
* **Option 2:** Using the `param_set_uint_minmax` helper function.
Let's dive into Option 1. The custom approach immediately resonates because it aligns directly with `def_reserved_size_set()` in `drivers/scsi/sg.c`. `def_reserved_size_set()` mirrors Option 1. This function uses a custom `.set` callback, employs `kstrtoint`, and returns `-ERANGE` for out-of-range values and `-EINVAL` for invalid input. This pattern appears consistent with how the SCSI/SG subsystem handles parameter validation and error reporting. Moreover, `scatter_elem_sz` is defined as a signed integer (`int`), and using `kstrtoint` maintains type consistency and proper error handling for negative values.
Now, let's look at Option 2. This uses `param_set_uint_minmax`. Right away, some red flags appear. `param_set_uint_minmax` would return `-EINVAL` for out-of-range values, which is inconsistent with the `-ERANGE` convention used in `sg.c` (specifically `def_reserved_size_set` and others). The existing convention in the SG driver prefers returning `-ERANGE` for out-of-range errors and `-EINVAL` for input errors. This inconsistency is a major concern. Also, `param_set_uint_minmax` casts the target argument to an `unsigned int *`, while `scatter_elem_sz` is a signed `int`. While this could be changed, it introduces a potential type mismatch.
Considering general kernel best practices, using `param_set_uint_minmax` would seem preferred because it promotes code reuse. However, in this specific case, `drivers/scsi/sg.c` already establishes a pattern of custom callbacks.
My analysis so far suggests that Option 1 is superior. However, I want to confirm my observations. Let's compare both from each point.
**Why Option 1 Better Aligns with SCSI / sg Subsystem Conventions:**
1. **Consistency:** The usage of `def_reserved_size_set` with its custom callback aligns perfectly with the pattern that was recently introduced in commit d06a310b45e1. This custom callback returns `-ERANGE` for range violations, and `-EINVAL` for input syntax errors.
2. **Error Code Semantics:** The SCSI generic driver is consistent in returning `-ERANGE` for range errors (e.g., in `sg_proc_write_dressz` and `def_reserved_size_set`). `param_set_uint_minmax` using `-EINVAL` for the same kind of error breaks the established convention.
3. **Type Compatibility:** Because `scatter_elem_sz` is an `int`, using `kstrtoint()` and the custom callback matches the existing type. There would be a signedness mismatch if the parameter was cast to `unsigned int`.
**Why someone could argue for Option 2 from general kernel best practices:**
1. **DRY / code reuse:** `param_set_uint_minmax()` is designed so drivers don't have to write their own range checking code.
**Conclusion:**
Given the context of the SCSI/SG subsystem and the established conventions in `drivers/scsi/sg.c`, I believe **Option 1 (custom callback)** is the superior choice. It maintains consistency, ensures correct error reporting, and avoids potential type issues. The recent commit introducing `def_reserved_size_set()` strongly reinforces this preference
|
| 474/6 |
2026/09/09 18:13 |
tool |
grepper |
0m
Args: map[Expression:module_param_cb PathPrefix:drivers/scsi]
Results: map[Output:drivers/scsi/sg.c=1646=static const struct kernel_param_ops def_reserved_size_ops = {
--
drivers/scsi/sg.c-1650-
drivers/scsi/sg.c:1651:module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
drivers/scsi/sg.c-1652- S_IRUGO | S_IWUSR);
]
|
| 475/6 |
2026/09/09 18:13 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 47917
output: 33
thoughts: 5468
Thoughts: **Analysis of `sg_build_indirect` in the SCSI Subsystem**
Alright, after meticulously examining the SCSI code, specifically the `sg.c` driver, I've got a clear picture. The `module_param_cb` associated with `scatter_elem_sz` in `drivers/scsi` is only used within `sg.c`'s `def_reserved_size_set` function. This is straightforward; the convention here is well-established.
Now, focusing on the core issue raised, concerning `scatter_elem_sz_prev` and the allocation order within `sg_build_indirect`, here's what I've dissected:
1. **`scatter_elem_sz_prev` Analysis**: This variable is an artifact of earlier designs, initially introduced when `scatter_elem_sz` was a runtime-modifiable module parameter *without* a validation callback. The original intent was to detect changes to this parameter during runtime, especially to clamp to `PAGE_SIZE` if modified to be smaller. However, with the current module parameter validation, ensuring `scatter_elem_sz` remains within bounds (\[PAGE\_SIZE, PAGE\_SIZE << MAX\_PAGE\_ORDER]) *at configuration time*, `scatter_elem_sz_prev` is entirely redundant. It's essentially dead code, no longer serving any purpose in this function. Its removal eliminates global state mutation during I/O, data races from concurrent threads accessing this variable, and simplifies the code significantly.
2. **`sg_build_indirect()` Redesign**: The goal is to optimize the allocation order and loop within this function. The original code was unnecessarily complex, primarily due to the now-redundant `scatter_elem_sz_prev` checks and adjustments. My revised approach simplifies the allocation logic:
* **Order Determination**: The allocation order is determined using a `READ_ONCE(scatter_elem_sz)` on the module parameter. With the assurance of its value after initialization, the allocation order calculation simplifies to `order = get_order(READ_ONCE(scatter_elem_sz));`, meaning that the function allocates all pages using this order, for the benefit of all users.
* **Allocation Loop**: The loop's structure is streamlined, with each iteration allocating a single page of the determined order, using `alloc_pages()`. The loop continues as long as there is remaining buffer size (`rem_sz > 0`) and the scatter-gather table has available elements (`k < mx_sc_elems`). The use of `rem_sz` means that if, for example, the order of a page has to be reduced on a second iteration of the function (because the order in the loop has been changed to its lowest allowable value), we would not have an issue if the size of the previous iteration was greater than the current size.
* **Error Handling**: If an allocation fails within the loop, the function will attempt to reduce the order by decrementing, and retrying the allocation by setting `goto retry;` to reduce fragmentation.
Ultimately, with `scatter_elem_sz_prev` eliminated and with the runtime checks removed, the code's allocation process simplifies to: Determine the order, allocate pages according to the order for the length of the buffer, and return an error code if the total allocated size is less than the buffer length (due to maximum number of scatter/gather tables). This significantly reduces the complexity, eliminates potential data races, and simplifies the overall code flow for scatter/gather I/O operations.
|
| 476/6 |
2026/09/09 18:14 |
tool |
grepper |
0m
Args: map[Expression:sg_build_indirect PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=183=static int sg_finish_rem_req(Sg_request * srp);
drivers/scsi/sg.c:184:static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size);
drivers/scsi/sg.c-185-static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count,
--
drivers/scsi/sg.c=1711=sg_start_req(Sg_request *srp, unsigned char *cmd)
--
drivers/scsi/sg.c-1782- } else {
drivers/scsi/sg.c:1783: res = sg_build_indirect(req_schp, sfp, dxfer_len);
drivers/scsi/sg.c-1784- if (res) {
--
drivers/scsi/sg.c=1853=static int
drivers/scsi/sg.c:1854:sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
drivers/scsi/sg.c-1855-{
--
drivers/scsi/sg.c-1867- SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
drivers/scsi/sg.c:1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
drivers/scsi/sg.c-1869- buff_size, blk_size));
--
drivers/scsi/sg.c-1906- SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
drivers/scsi/sg.c:1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
drivers/scsi/sg.c-1908- k, num, ret_sz));
--
drivers/scsi/sg.c-1913- SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
drivers/scsi/sg.c:1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
drivers/scsi/sg.c-1915- k, rem_sz));
--
drivers/scsi/sg.c=1988=sg_build_reserve(Sg_fd * sfp, int req_size)
--
drivers/scsi/sg.c-1996- req_size = PAGE_SIZE;
drivers/scsi/sg.c:1997: if (0 == sg_build_indirect(schp, sfp, req_size))
drivers/scsi/sg.c-1998- return;
]
|
| 477/6 |
2026/09/09 18:14 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 54917
output: 61
thoughts: 4898
Thoughts: **Analysis of sg Subsystem Code and Proposed Improvements**
Alright, let's break this down. From what I'm seeing, we're looking at some key points in the `sg` subsystem's interaction with the kernel parameters and the internal scatter-gather list building. The core issue seems to revolve around the handling of `scatter_elem_sz` and `scatter_elem_sz_prev`, particularly within `sg_build_indirect()`.
First, regarding the choice between Option 1 (custom callback using `kstrtoint`) and Option 2 (using `param_set_uint_minmax`): it's clear that Option 1 is the better choice from a subsystem perspective. The `sg` subsystem, as exemplified by the recent commit d06a310b45e1 ("scsi: sg: Resolve soft lockup issue when opening /dev/sgX") regarding `def_reserved_size_set()`, has established a pattern of using custom callbacks with `kstrtoint`. This returns `-EINVAL` on format errors (e.g. invalid characters) and `-ERANGE` for out-of-range values. Option 2 introduces an inconsistency, returning `-EINVAL` for range violations, which differs from the existing error handling within `sg.c`. Furthermore, `param_set_uint_minmax` is designed for `unsigned int`, whereas `scatter_elem_sz` is an `int`, creating a type mismatch. And crucially, from a SCSI perspective, `param_set_uint_minmax` is not used anywhere in `drivers/scsi/` (the entire SCSI subsystem), and a custom callback was explicitly reviewed and merged in the relevant commit. So, we stay consistent and aligned with established conventions and maintainers' preferences with the `kstrtoint` approach.
Now, concerning the `scatter_elem_sz_prev` variable: Yes, it needs to go. Its original purpose was to detect changes to `scatter_elem_sz` when there wasn't a callback in place and to cache results of a now-obsolete `sg_page_malloc` function, which was removed back in 2008. The configuration-time validation mechanism we have with the `module_param_cb` guarantees that `scatter_elem_sz` is within a valid range. Having a variable that tracks a previous value becomes redundant, and its presence introduces a data race. By removing it, we simplify the code and eliminate a potential source of concurrency issues.
Finally, for the allocation order and loop in `sg_build_indirect()`, the goal is to make it clean, safe, and efficient. We can do this safely: First, we can read `scatter_elem_sz` with `READ_ONCE(scatter_elem_sz)` to ensure we get a consistent value. And based on that value we calculate the order:
```c
int order = get_order(READ_ONCE(scatter_elem_sz));
```
The old logic that tried to adjust based on `scatter_elem_sz_prev` is completely removed. The loop becomes cleaner, with the correct order set as an unchanging parameter:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, ret_sz=%d\n",
k, ret_sz));
}
```
The allocation uses the determined order from the start and, if an allocation fails, we simply decrement the order (down to a single page). The result is much simpler: this guarantees all allocations within the buffer are the same order (or, when the loop encounters an error, the maximum possible size), no writes to `scatter_elem_sz` within the I/O path, and therefore no data races. It's a much more robust and understandable solution.
In short: Option 1 is consistent and correct; `scatter_elem_sz_prev` goes away; and `sg_build_indirect()` becomes significantly cleaner and safer. This is a solid improvement, addressing the issue with the I/O path logic.
|
| 478/6 |
2026/09/09 18:14 |
tool |
set-results |
0m
Args: map[Answer:Option 1 better aligns with SCSI/sg conventions. scatter_elem_sz_prev should be completely removed, and the sg_build_indirect() loop should be simplified to allocate order-sized pages without mutating global state.]
Results: map[Answer:Option 1 better aligns with SCSI/sg conventions. scatter_elem_sz_prev should be completely removed, and the sg_build_indirect() loop should be simplified to allocate order-sized pages without mutating global state.]
|
| 479/4 |
2026/09/09 18:14 |
llm |
patch-generator-compressor |
0m
Model:
Reply: ### Summary of Investigation and Current State
#### 1. Approaches Tried and Results (Including Dead-Ends)
- **Original developer's approach (rejected by senior maintainer):**
- Path: `drivers/scsi/sg.c`.
- Added `num = PAGE_SIZE;` inside `sg_build_indirect()` when `num < (int)PAGE_SIZE`.
- Cast `(int)PAGE_SIZE` in signed comparisons in both `sg_build_indirect()` and `init_sg()`.
- Clamped allocation order with `order = min_t(int, order, MAX_PAGE_ORDER);` inside `sg_build_indirect()`.
- **Maintainer rejection reasons:**
1. *Boundary validation vs. data-path band-aid*: Sanitizing module parameter values inside the I/O fast path (`sg_build_indirect()`) rather than rejecting invalid values (0, negative, or exceeding max page order) at the sysfs boundary violates caller/callee invariants.
2. *Subsystem idiom alignment*: Should follow precedent set in commit `d06a310b45e1` (`def_reserved_size`) using `module_param_cb()` with custom `.set` callback (or `param_set_uint_minmax()`) validating range `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`, returning `-EINVAL` or `-ERANGE`.
3. *Concurrency & data races*: Mutating global variables (`scatter_elem_sz` and `scatter_elem_sz_prev`) without locks inside `sg_build_indirect()` causes data races between concurrent opens and requests.
4. *Typing & state divergence*: Casting `PAGE_SIZE` to `(int)` is an anti-pattern. Clamping `order` with `min_t()` leaves `scatter_elem_sz` set to out-of-range values (e.g. `INT_MAX`), creating divergence between sysfs parameter and actual allocation behavior.
#### 2. Current Hypotheses and Planned Architecture
- **Root Cause:**
Writing `0` to `/sys/module/sg/parameters/scatter_elem_sz` sets `scatter_elem_sz = 0`. In `sg_build_indirect()`, `num` was initialized to `scatter_elem_sz` (`0`), detected `< PAGE_SIZE`, updated global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`, but did not update local variable `num`. `num = 0` was passed to `get_order(0)`, which produces undefined behavior (`order = 52` on 64-bit), causing `1 << (PAGE_SHIFT + order)` to shift by 64 bits on a 32-bit `int`, triggering UBSAN shift-out-of-bounds.
- **Architectural Solution Required:**
1. Define a custom `.set` parameter callback `scatter_elem_sz_set()` using `module_param_cb()` and `kernel_param_ops` (mirroring `def_reserved_size_ops` in commit `d06a310b45e1`).
2. In `scatter_elem_sz_set()`, validate `scatter_elem_sz` to be within `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`. Reject invalid inputs with `-EINVAL` (if null or parse fails) or `-ERANGE` (if out of bounds, including negative).
3. Eliminate uncoordinated runtime mutations of global variables inside `sg_build_indirect()`:
- Remove the block in `sg_build_indirect()` modifying `scatter_elem_sz` and `scatter_elem_sz_prev`.
- Remove the conditional in-loop mutation updating `scatter_elem_sz` and `scatter_elem_sz_prev` to `ret_sz`.
- Eliminate `scatter_elem_sz_prev` entirely: it was only used for tracking changes to `scatter_elem_sz` and runtime rounding up, is not exported, and is no longer needed.
4. In `sg_build_indirect()`:
- Read `scatter_elem_sz` into local variable `num` (or compute `order = get_order(scatter_elem_sz);`).
- Inside the loop, replace `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;` with `num = min(rem_sz, ret_sz);` (for logging `SCSI_LOG_TIMEOUT`).
5. In `init_sg()`:
- Ensure initial `scatter_elem_sz` is adjusted if `PAGE_SIZE > SG_SCATTER_SZ` (e.g. 64KB pages): `if (scatter_elem_sz < PAGE_SIZE) scatter_elem_sz = PAGE_SIZE;`. Remove `scatter_elem_sz_prev = scatter_elem_sz;`.
#### 3. Key Files, Functions, Snippets, and Values
- **File:** `drivers/scsi/sg.c`
- **Reference Implementation (`def_reserved_size` in `drivers/scsi/sg.c`, lines 1627-1653):**
```c
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
/* limit to 1 MB */
if (size < 0 || size > 1048576)
return -ERANGE;
def_reserved_size = size;
return 0;
}
static const struct kernel_param_ops def_reserved_size_ops = {
.set = def_reserved_size_set,
.get = param_get_int,
};
module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
S_IRUGO | S_IWUSR);
```
- **Declarations in `drivers/scsi/sg.c` (lines 94-95):**
```c
static int scatter_elem_sz = SG_SCATTER_SZ;
static int scatter_elem_sz_prev = SG_SCATTER_SZ; /* to be removed */
```
- **Current Parameter Definition (line 1624):**
```c
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
```
- **Current `init_sg()` (lines 1670-1673):**
```c
if (scatter_elem_sz < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
```
- **Current `sg_build_indirect()` (lines 1876-1910):**
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
```
- **Constants & Boundary Values:**
- `min`: `PAGE_SIZE`
- `max`: `PAGE_SIZE << MAX_PAGE_ORDER`
- When parsing `scatter_elem_sz`, `kstrtoint` with range check:
```c
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
```
Note: If `size` is signed `int`, comparing `size < 0 || size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)` ensures no negative overflow bypasses. Or using `kstrtouint` ensures negative strings like `"-1"` return `-EINVAL` automatically.
#### 4. Watch-Outs and Potential Traps
- Avoid casting `PAGE_SIZE` to `(int)PAGE_SIZE`.
- Ensure `scatter_elem_sz_prev` references are cleanly removed without leaving unused variable warnings.
- Avoid introducing any data races or global writes in `sg_build_indirect()`.
- Check all callers / references of `scatter_elem_sz` (only 4 locations in `drivers/scsi/sg.c`, no outside callers).
Tokens:
input: 59975
output: 2261
thoughts: 0
|
| 480/4 |
2026/09/09 18:14 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 49409
output: 451
thoughts: 70
Thoughts: **Analyzing SCSI/sg Conventions**
Okay, so I'm looking at this and thinking, Option 1 is definitely the way to go. It just *feels* right, aligns much better with the SCSI/sg conventions we're used to. It's cleaner. But before I commit to it completely, I need to get some more precise details.
Let's ping CodeExpert on a couple of points. First, I really need a deep dive into the `scatter_elem_sz_set` implementation. Specifically, I'm curious about how it handles negative numbers, and also what its logic is when `size` is smaller than `PAGE_SIZE`. These details are crucial for understanding potential edge cases and ensuring robustness.
Second, I need a very clear explanation of the exact simplifications made in `sg_build_indirect()` and `init_sg()`. Knowing precisely what changes were made there will help ensure that these functions haven't broken anything unexpectedly.
|
| 481/4 |
2026/09/09 18:14 |
tool |
codeexpert |
15m
Error:
Args: map[Question:In drivers/scsi/sg.c:
1. Regarding scatter_elem_sz_set():
Should the check be:
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
Given that size is an int, if the user supplies a negative number like -1, does 'size < PAGE_SIZE' behave correctly (due to integer promotion or should 'size < 0' or 'size < PAGE_SIZE' be written), or how should it be written to cleanly handle negative numbers without compiler warnings?
2. In sg_build_indirect():
Currently lines 1876-1910 contain:
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) { ... }
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (...) {
num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;
...
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(..., num, ret_sz));
}
What should this block look like once scatter_elem_sz_prev is removed and scatter_elem_sz is guaranteed valid? What should 'num' be in the loop for logging?
3. In init_sg():
Currently:
if (scatter_elem_sz < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
How should init_sg() be updated?]
|
| 482/5 |
2026/09/09 18:14 |
agent |
codeexpert |
14m
Model:
Error:
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.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
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: In drivers/scsi/sg.c:
1. Regarding scatter_elem_sz_set():
Should the check be:
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
Given that size is an int, if the user supplies a negative number like -1, does 'size < PAGE_SIZE' behave correctly (due to integer promotion or should 'size < 0' or 'size < PAGE_SIZE' be written), or how should it be written to cleanly handle negative numbers without compiler warnings?
2. In sg_build_indirect():
Currently lines 1876-1910 contain:
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) { ... }
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (...) {
num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;
...
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(..., num, ret_sz));
}
What should this block look like once scatter_elem_sz_prev is removed and scatter_elem_sz is guaranteed valid? What should 'num' be in the loop for logging?
3. In init_sg():
Currently:
if (scatter_elem_sz < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
How should init_sg() be updated?
|
| 483/6 |
2026/09/09 18:15 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4479
output: 33
thoughts: 513
Thoughts: **Analyzing SCSI Scatter-Gather List Management in `sg.c`**
Okay, so I'm diving into `drivers/scsi/sg.c`, specifically focusing on how scatter-gather lists are handled. I've got three key areas to investigate and some immediate questions.
Firstly, I'm looking at `scatter_elem_sz_set()`. The code currently has a size check, and I'm a bit concerned about how it handles potential integer overflows or unintended behavior with negative inputs. It's written as `if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))`. Given that 'size' is an integer, I want to confirm that this check correctly catches negative values, or if I need to explicitly check for `size < 0` to be absolutely sure. This is about robustness, avoiding any potential surprises down the line with edge cases, compiler optimizations, and the like.
Secondly, I'm examining `sg_build_indirect()`. The current logic, specifically lines 1876-1910, is a bit convoluted, and it relies on `scatter_elem_sz_prev`. Given that this `scatter_elem_sz_prev` variable is slated for removal, I need to understand what the simplified structure should look like once that dependency is gone. What calculations are actually necessary, and what should the variable 'num' represent in the logging statement inside the loop? The goal is efficiency and clarity here.
Finally, I'm turning my attention to `init_sg()`. There's an initialization step where `scatter_elem_sz` is set to `PAGE_SIZE` if it's smaller. This is straightforward, but I need to adapt the code now that `scatter_elem_sz_prev` is going away. How do I modify this initialization to maintain the correct behavior and initialization without that supporting variable?
Before I dive too deeply into the code and start looking at git history, let's do a quick search within the file itself. I'll get a quick picture.
|
| 484/6 |
2026/09/09 18:15 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 485/6 |
2026/09/09 18:15 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6486
output: 36
thoughts: 81
Thoughts: Here's my summary, as though I'm thinking through this myself:
**Investigating the `scatter_elem_sz` Parameter**
Okay, here's the kernel code, using `module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);`. I'm seeing `scatter_elem_sz` used as a module parameter; that's the starting point. But, hang on a second, didn't I see something, somewhere, about a potential improvement or a more controlled way to set this? It feels like I remember a patch or some discussion around a `scatter_elem_sz_set` function or variable. Time to dive into the Git logs and see if I can find any relevant commits or patch discussions. I need to search the commit messages and any related discussions for mentions of `scatter_elem_sz` to track any changes. Let's see if anything pops out related to a setter.
|
| 486/6 |
2026/09/09 18:15 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 487/6 |
2026/09/09 18:15 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 6878
output: 22
thoughts: 28
Thoughts: Here's my summary, as though I'm thinking through this process:
**Investigating `scatter_elem_sz` in Git History**
Okay, time to dig into this. I need to see where `scatter_elem_sz` is showing up in our codebase, specifically in the `git-log`. Let's use `git log` and see if it's referenced in `MessageRegexps` or, for that matter, anywhere in the commit messages themselves. This is a common debugging technique - understand the history of this term to understand how the code changed. This will give me a timeline, context, and potentially clue me in on *why* this might be relevant to the issue I'm chasing. Hopefully, this search will quickly illuminate the origin and evolution of the relevant functionality.
|
| 488/6 |
2026/09/09 18:15 |
tool |
git-log |
0m
Args: map[MessageRegexps:[scatter_elem_sz]]
Results: map[Output:4d2de3a50ce1 [SCSI] fix BUG when sum(scatterlist) > bufflen
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 489/6 |
2026/09/09 18:15 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7160
output: 35
thoughts: 49
Thoughts: Here's my take on those code sections:
**Diving into sg.c: A Quick Audit**
Okay, first things first, let's pull up `drivers/scsi/sg.c`. I need a quick refresh on how this thing works, so I'm honing in on specific regions. I think focusing on line 90-100 will remind me of the fundamental setup or structure – likely the initial data structures or important defines. Then, I should probably check line 1620-1675 to recall a key function or specific operation, maybe the command submission process. Finally, hitting line 1870-1920 will likely give me insight into error handling or maybe how data is returned. I suspect these are key points where I can assess the driver's current state and possibly identify potential areas of concern or possible improvements. I want to check for potential race conditions or locking issues.
|
| 490/6 |
2026/09/09 18:15 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:85 LineCount:40]
Results: map[Contents: 85: * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
86: * of this size (or less if there is not enough memory) will be reserved
87: * for use by this file descriptor.
88: */
89:
90: /* picks up init parameter */
91: static int def_reserved_size = SG_DEF_RESERVED_SIZE;
92: static int sg_allow_dio = SG_ALLOW_DIO_DEF;
93:
94: static int scatter_elem_sz = SG_SCATTER_SZ;
95: static int scatter_elem_sz_prev = SG_SCATTER_SZ;
96:
97: #define SG_SECTOR_SZ 512
98:
99: static int sg_add_device(struct device *);
100: static void sg_remove_device(struct device *);
101:
102: static DEFINE_IDR(sg_index_idr);
103: static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
104: file descriptor list for device */
105:
106: static struct class_interface sg_interface = {
107: .add_dev = sg_add_device,
108: .remove_dev = sg_remove_device,
109: };
110:
111: typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
112: unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */
113: unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
114: unsigned bufflen; /* Size of (aggregate) data buffer */
115: struct page **pages;
116: int page_order;
117: char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
118: unsigned char cmd_opcode; /* first byte of command */
119: } Sg_scatter_hold;
120:
121: struct sg_device; /* forward declarations */
122: struct sg_fd;
123:
124: typedef struct sg_request { /* SG_MAX_QUEUE requests outstanding per file */
]
|
| 491/6 |
2026/09/09 18:15 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 8106
output: 37
thoughts: 26
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing `drivers/scsi/sg.c` - Lines 1615-1675**
Okay, let's dive into this specific section of `drivers/scsi/sg.c`. I'm focusing on lines 1615-1675. Based on the surrounding code, I'm expecting this area to be handling some critical aspect of the SCSI generic (sg) driver's interaction with the block or SCSI layer – possibly command submission, error handling, or resource management. Given the line range, it is likely that this covers some core logic. I need to figure out the exact point of control within the driver, where the SCSI command is actually handled.
I need to quickly assess what the code is doing specifically. Is it a function call, a conditional block, or a loop? Does it handle a common or error path?
I'm looking for key data structures being manipulated: `scsi_cmnd`, `sg_io_hdr`, potentially `request_queue` or related SCSI structures. What is the driver doing when dealing with these structures? I need to understand the sequencing and dependencies.
Specifically, I'm trying to see how the code interacts with the `sg_io_hdr`. Is it queuing requests? Setting up scatter-gather lists? Dealing with timeouts or retries? Also, it will be good to keep in mind, if the data is being DMA'd to a device, or not, that will inform a lot of what I will be looking for.
I'll be mindful of the likely potential for race conditions or lock contention within this block. Is there appropriate locking involved? Are spinlocks or mutexes being used, and if so, how are they being acquired and released? I should make sure that this is handled correctly. Also, how are interrupts being handled? Are there any potential interrupt-related issues in this section?
I will then use my understanding of the SCSI command lifecycle and the sg driver's architecture to build a mental model of this part of the code's functionality, to see if there are any obvious areas for optimization, potential bugs or security vulnerabilities. It’s always good to scan for potential denial-of-service vectors, like unbounded loops or excessive resource consumption.
|
| 492/6 |
2026/09/09 18:16 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1615 LineCount:65]
Results: map[Contents:1615:
1616: sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
1617: device_destroy(&sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));
1618: cdev_del(sdp->cdev);
1619: sdp->cdev = NULL;
1620:
1621: kref_put(&sdp->d_ref, sg_device_destroy);
1622: }
1623:
1624: module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
1655: MODULE_DESCRIPTION("SCSI generic (sg) driver");
1656: MODULE_LICENSE("GPL");
1657: MODULE_VERSION(SG_VERSION_STR);
1658: MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
1659:
1660: MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
1662: MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1663: MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
1664:
1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
1675: rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1676: SG_MAX_DEVS, "sg");
1677: if (rc)
1678: return rc;
1679: rc = class_register(&sg_sysfs_class);
]
|
| 493/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 9707
output: 37
thoughts: 26
Thoughts: Here's my summary, as though I'm thinking through this process:
**Diving into `sg_build_indirect`**
Okay, let's zero in on `sg_build_indirect`. I'm specifically interested in the code block spanning roughly lines 1870 to 1925. I need to understand how this function is handling indirect rendering setup. I'm already familiar with the broader structure, so I can go directly to this section. I need to see how it's building the command buffers and setting up the data structures. I'm expecting to see things like buffer bindings, descriptor set updates, and potentially workgroup size calculations – all the low-level details that really matter when you're optimizing for GPU performance. Let's see how it's done... time to get my hands dirty.
|
| 494/6 |
2026/09/09 18:16 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1870 LineCount:55]
Results: map[Contents:1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
]
|
| 495/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10859
output: 38
thoughts: 258
Thoughts: **Analyzing the `def_reserved_size_set` Function**
Okay, let's dive in. I'm looking at this `def_reserved_size_set` function right above `init_sg`. It seems to be responsible for setting a default reserved size. The code's straightforward enough: it takes a string value (`val`) as input, attempts to convert it to an integer (`size`) using `kstrtoint`, and then validates that `size` falls within a reasonable range (0 to 1 MB). If everything checks out, it updates the `def_reserved_size` global variable. Makes sense. We're using `module_param_cb` which gives us more control over how the module parameter is handled. The operations structure handles the "set" and "get" functions, the set function taking the input val, setting the value, and the get function, returning the integer.
Now, I think it's time to check the commit history of `def_reserved_size_set`. Always good to understand the evolution of a function. Let's see why it was introduced, any design decisions that were made, or any bugs that were fixed along the way.
|
| 496/6 |
2026/09/09 18:16 |
tool |
git-log |
0m
Args: map[CodeRegexp:def_reserved_size_set PathPrefix:drivers/scsi/sg.c]
Results: map[Output:d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
]
|
| 497/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 11451
output: 27
thoughts: 25
Thoughts: Okay, here's my interpretation of what's going through my mind when approaching that git command, delivered as a first-person account suitable for an expert:
**Diving into Commit Details**
Alright, time to dissect commit `d06a310b45e1`. Right off the bat, I'm thinking, "Let's use `git show` to get the nitty-gritty." This isn't just a casual glance; I need the full picture. I expect `git show` to give me the commit message, the author, the committer, and of course, the diff – the *meat* of what changed. I'm going to look for any hidden details or potential oversights.
I'm mentally preparing for what I might find. Is this a substantial change, or a quick fix? Was the commit message descriptive or vague? Are there any obvious code smells? Depending on the context, I'll be looking for specific patterns: refactoring, bug fixes, feature additions, or perhaps a configuration tweak. I need to be ready to understand the reasoning behind the change, the impact it has, and any potential side effects. The diff will tell the story and I will be looking for patterns that are not obvious at first glance.
|
| 498/6 |
2026/09/09 18:16 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 499/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 13087
output: 20
thoughts: 102
Thoughts: **Initial Assessment of Commit Message**
Okay, let's break this down. First, that commit message, specifically the `Link` tag with that seemingly random string: `https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com`. Right, so I see a patch ID and, critically, `3034148-3-yangerkun@huawei.com`. That `-3-` in the middle and the email address... that signals a series. This is likely part of a patch set from Yang Erkung at Huawei. I need to investigate the context. My next move is clear. I'm going to fire up `git log` and search for any other commits by `yangerkun` or potentially related commits to get the full picture and understand the surrounding changes. Let's see what else he's been working on.
|
| 500/6 |
2026/09/09 18:16 |
tool |
git-log |
0m
Args: map[MessageRegexps:[yangerkun]]
Results: map[Output:326d49039c10 nbd: add pre_defined_connections module parameter for pre-created devices
a9d414b4a15c nbd: remove queue freeze for newly created nbd from netlink path
f8d21c590e55 nbd: factor out a nbd_genl_foreach_sock
db285268df79 nbd: skip queue freeze when setting size at device startup
285908f554fe nbd: remove queue freeze in nbd_add_socket
0fdee7c5fa88 nbd: clear queue limits on disconnect
04d8fb23e520 nbd: disallow NBD_SET_SOCK on an active device
fe247030f1ce nbd: simplify find_fallback() by removing redundant logic
516403d4d856 Revert "NFSD: Defer sub-object cleanup in export put callbacks"
4837fb36219e nfs: use nfsi->rwsem to protect traversal of the file lock list
]
|
| 501/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 13691
output: 28
thoughts: 23
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing Commit History**
Okay, so we're diving into this code base, and it looks like we need to understand the context of something that happened around commit `d06a310b45e1`. Rather than just blindly forging ahead, it makes sense to pause and focus our search there. I'm thinking, "Let's use that commit as a focal point." We can trace the modifications to the codebase which that commit introduces. We can start by identifying the exact changes introduced in that commit, and then examine the surrounding commit history. This strategic approach will let us understand the origin, the rationale, and the impact of the modifications made around that point. I'm expecting to gain a deeper understanding of the codebase's evolution, pinpoint specific issues, or discover the cause of a specific bug or change in behavior, by concentrating our efforts on that specific commit and its neighborhood. I'll need to use my Git skills to effectively search the commit history and inspect file diffs.
|
| 502/6 |
2026/09/09 18:16 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
]
|
| 503/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14121
output: 27
thoughts: 715
Thoughts: **My Analysis of This Patch Review**
Okay, let's break this down. First thought: `3034148-3-yangerkun@huawei.com`… I should check if this person has other related patches in this series or a different one dealing with `scatter_elem_sz` – that context could be important. The user seems to be asking some key questions about a patch related to `scatter_elem_sz` in the `sg.c` driver. It seems they are in the process of replacing and refactoring code that uses a variable, `scatter_elem_sz`, for the maximum scatter gather element size. They're implementing a new function called `scatter_elem_sz_set()`, likely to replace direct modification of this parameter via sysfs. This is where I come in, to assist in the code review and design.
The core of the issue boils down to how to handle this variable and its initialization, given that it's now set through a validated interface. I need to think carefully about the questions raised:
1. **`scatter_elem_sz_set()` Validation:** The user correctly flags potential issues with the validation logic. If `size` is an integer, how do we handle negative values correctly? We need to make sure the check is robust, probably using a clear `size < 0` check in addition to `size < PAGE_SIZE`. I need to ensure that the code is free of potential integer overflow issues and covers the intended range.
2. **`sg_build_indirect()` Refactoring:** The existing code in `sg_build_indirect()` seems convoluted. The main point is that `scatter_elem_sz_prev` has been removed. This means the code that previously had to deal with an arbitrary parameter value now needs to be simplified, now that it's validated through `scatter_elem_sz_set()`. The core question becomes how to streamline the logic within the loop, and what value of `num` should be used for the SCSI log.
3. **`init_sg()` Initialization:** The last question deals with `init_sg()`. Previously, `scatter_elem_sz` was adjusted to at least `PAGE_SIZE`. Now that `scatter_elem_sz` should be valid, how should this initialization function be updated? Perhaps the check is no longer needed.
I suspect the introduction of `scatter_elem_sz_set()` is to restrict the values that `scatter_elem_sz` can take. The fact that the user is now using `module_param_cb` suggests that they are trying to validate the parameter at load time or runtime to prevent potential issues. I also need to check commit `6460e75a104d` to see why the use of `scatter_elem_sz_prev` was introduced in the first place, as this is critical to understanding the previous design. This will inform me of the likely design intent and potential pitfalls. This is a refactoring, design question, and patch review all rolled into one, and it requires careful consideration of both correctness and efficiency.
|
| 504/6 |
2026/09/09 18:16 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 505/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 19932
output: 26
thoughts: 76
Thoughts: Okay, let's break this down.
**Initial Investigation into Scatter Element Size History**
Alright, so I need to trace the evolution of `scatter_elem_sz` and `scatter_elem_sz_prev`. The initial commit introducing them was 6460e75a104d, that's my starting point. Now, before I go too far, let me check something else related to `sg_build_indirect`, because those sorts of related changes are critical, I often find useful clues in related code modifications. I'll get back to what 10db10d144c0 did with `sg_build_indirect` – understanding its history could illuminate the context around the scatter element size changes. Let me check that quickly. Then I'll return to the original investigation.
|
| 506/6 |
2026/09/09 18:16 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 507/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 29855
output: 21
thoughts: 2604
Thoughts: **Deep Dive into `scatter_elem_sz` and `sg_build_indirect`**
Okay, this is intriguing. I'm seeing a fascinating evolution here, a classic example of incremental design and potential subtle bugs. Initially, in 2006, `sg_page_malloc` was responsible for allocating pages, and `scatter_elem_sz` could be adjusted. My initial reaction is to immediately question why that was done. It seems like the original implementation in 2006 used `sg_page_malloc` which rounded up `num` to the nearest power of 2, so the rounding behavior of `ret_sz > scatter_elem_sz_prev`, caused `scatter_elem_sz` to be rounded up as well.
The rewrite in 2008 with commit 10db10d144c0 introduces `sg_build_indirect` in its current form. The allocation strategy shifts to using `alloc_pages` with an `order` derived from `num` via `get_order(num)`. The `ret_sz`, the size of each allocated page, is calculated as `1 << (PAGE_SHIFT + order)`. The key, I think, is understanding how these variables interact within the loop. The code contains the condition `if (num == scatter_elem_sz_prev)`, and the rounding, `scatter_elem_sz = ret_sz; scatter_elem_sz_prev = ret_sz;`, but why? The variable `scatter_elem_sz` is not necessarily a power of 2.
Douglas Gilbert's commit 6460e75a104d, seems to be where the story of `scatter_elem_sz` really starts to come into focus. It's a module parameter, directly exposed to userspace. It is initialised and may be adjusted at runtime. It adjusts to `max(given(scatter_elem_sz), PAGE_SIZE)` and rounded up to the nearest power of 2, but there's no input validation - a user could set it to practically anything! Without a `.set` callback, the module has very little control! The module checks that the value is at least `PAGE_SIZE` in `init_sg()` and also clamps it when `sg_build_indirect` runs. The `rem_sz` is decremented by `ret_sz` each time.
The important point is that `scatter_elem_sz` could be non-power-of-2, leading to the condition where `ret_sz > scatter_elem_sz_prev` inside the loop, and the `scatter_elem_sz` then gets rounded up to the next power of two and is subsequently used. The current code is flawed, as there is the possibility that `order` may be decremented and `ret_sz` changes. If there's an allocation failure, it goes back to `retry` and decrements the `order`, halving the `ret_sz`, but does not update `scatter_elem_sz_prev`, so `scatter_elem_sz_prev` may be larger than the chunk being allocated. So if `ret_sz` is smaller, and `scatter_elem_sz_prev` is now out of date, each allocated chunk is `ret_sz` in reality. The code then uses `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`. This looks like a bug.
So the value that is actually important is `min(rem_sz, ret_sz)`. The original design intent of `num` is lost.
I need to search for existing discussions or patches related to this in the mailing lists or git history.
|
| 508/6 |
2026/09/09 18:16 |
tool |
grepper |
0m
Error:
Args: map[Expression:scatter_elem_sz_set]
Results:
|
| 509/6 |
2026/09/09 18:16 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 33303
output: 22
thoughts: 50
Thoughts: Okay, here's my interpretation of those thoughts, summarized from my perspective as someone deeply familiar with this code:
**Digging into a Potential Issue**
Alright, the debugger isn't finding anything that directly matches `scatter_elem_sz_set` in the current codebase. That's a bit odd. Time to backtrack and get a broader perspective. Let's see... the most sensible next step is to cast a wider net. I need to check the recent commit history, the git log, looking for anything related to `scatter_elem_sz` in any form. Perhaps a recent commit renamed it, or it was introduced in some subtly different way. Maybe a typo, maybe a refactor... need to follow the thread of this parameter's evolution to understand its context and whether it's related to the missing `scatter_elem_sz_set`. It's all about finding *where* that related functionality is and *how* it's changed.
|
| 510/6 |
2026/09/09 18:16 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:scatter_elem_sz]
Results:
|
| 511/6 |
2026/09/09 18:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 33613
output: 32
thoughts: 21
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Examining SCSI Driver History**
Alright, let's dive into the history of those SCSI drivers. My immediate impulse is to use `git log` – it's the standard tool for this sort of deep dive. The key will be scoping the search appropriately. Instead of a blanket check, I want to zero in on changes that are specifically relevant to the `drivers/scsi` directory. To do that efficiently, I'll incorporate a `PathPrefix` filter. This will prevent a flood of irrelevant commits cluttering the output and allow me to concentrate only on the driver code, associated headers, and related documentation. This targeted approach is much more efficient than a full history scan. This focused approach should give me the data I need without too much noise. I'll be looking for critical changes, recent bugfixes, and who's been actively working on that codebase, which is crucial for understanding its current state and future direction.
|
| 512/6 |
2026/09/09 18:27 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 513/6 |
2026/09/09 18:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 33937
output: 25
thoughts: 206
Thoughts: **Kernel Patch Detective Work**
Alright, so `scatter_elem_sz_set` isn't in the kernel tree yet. That clearly means this is something in development - a new patch, a patch series, or someone's actively working on it. Hold on... I need to jog my memory. Ah, *that* commit, `d06a310b45e1`! The one fixing the soft lockup issue with `/dev/sgX`. I recall it had a link to a patch message, and I'm spotting `3034148-3` in that message ID. That's key; it tells me this was *patch 3* in a series. Now the question is, what were the preceding patches and perhaps subsequent ones? I wonder if this relates to any other work *yangerkun* did in 2026 or even 2025. Time to check the commit logs. Let's see what else they've been up to...
|
| 514/6 |
2026/09/09 18:27 |
tool |
git-log |
0m
Args: map[Count:20 MessageRegexps:[Yang Erkun]]
Results: map[Output:326d49039c10 nbd: add pre_defined_connections module parameter for pre-created devices
a9d414b4a15c nbd: remove queue freeze for newly created nbd from netlink path
f8d21c590e55 nbd: factor out a nbd_genl_foreach_sock
db285268df79 nbd: skip queue freeze when setting size at device startup
285908f554fe nbd: remove queue freeze in nbd_add_socket
0fdee7c5fa88 nbd: clear queue limits on disconnect
04d8fb23e520 nbd: disallow NBD_SET_SOCK on an active device
516403d4d856 Revert "NFSD: Defer sub-object cleanup in export put callbacks"
4837fb36219e nfs: use nfsi->rwsem to protect traversal of the file lock list
725ecd80688b nsfs: fix wrong error code returned for pidns ioctls
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
f08fe8891c3e dcache: Limit the minimal number of bucket to two
d250bdf531d9 ext4: fix iloc.bh leak in ext4_xattr_inode_update_ref
cc742fd1d184 ext4: correct the comments place for EXT4_EXT_MAY_ZEROOUT
a9272422316f ext4: cleanup for ext4_map_blocks
dac092195b6a ext4: rename EXT4_GET_BLOCKS_PRE_IO
98b7bf54338b loop: fix backing file reference leak on validation error
13017b427118 md: make rdev_addable usable for rcu mode
]
|
| 515/6 |
2026/09/09 18:27 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 34925
output: 25
thoughts: 127
Thoughts: **Analyzing SCSI sg Driver Fixes**
Alright, let's dive in. I'm seeing three commits related to the SCSI sg driver, and it looks like they're addressing some key issues. First, there's `3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()`. Hmm, that sounds like a fix related to how the `sg-big-buff` sysctl is handled during initialization. I vaguely recall something about that – was it patch 1 or 2 in a sequence? Need to check that. Then, we have `d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX`. Soft lockups? Interesting. That’s probably patch 3. Opening device files can be tricky, so this is definitely something to pay attention to. Finally, `50209dec14f8 scsi: sg: Remove deprecated sg-big-buff`. Ah, finally! They're deprecating and removing `sg-big-buff`. Good riddance. This suggests the previous two patches may have been part of making this finally possible.
Now, the important part: I need to quickly grab the patch links from those commits. I'm going to scan the commit messages for the message-IDs. That'll let me trace back to the original discussions and see exactly what the motivations and full scope of these fixes were, what related discussions may have been had, and where they sat within a larger sequence of work, particularly any prior attempts to fix it.
|
| 516/6 |
2026/09/09 18:28 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 3033c471aaf675254efaa0da431e95d91a104b41
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:42 2026 +0800
scsi: sg: Fix sysctl sg-big-buff register during sg_init()
Commit 26d1c80fd61e ("scsi/sg: move sg-big-buff sysctl to scsi/sg.c") made
a mistake. sysctl sg-big-buff was not created because the call to
register_sg_sysctls() was placed on the wrong code path.
Fixes: 26d1c80fd61e ("scsi/sg: move sg-big-buff sysctl to scsi/sg.c")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-2-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 37bac49f30f0..71d34186dec9 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1691,13 +1691,13 @@ init_sg(void)
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
+ register_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
return 0;
}
class_unregister(&sg_sysfs_class);
- register_sg_sysctls();
err_out:
unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
return rc;
]
|
| 517/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 36032
output: 25
thoughts: 83
Thoughts: Okay, let's break this down.
**Decoding Versioning - A Quick Mental Check**
Right, so I'm looking at these version identifiers. The pattern suggests some sort of timestamp and patch number, maybe even a unique ID. Let's see... `20260127062044.3034148-2` and `20260127062044.3034148-3` - those clearly indicate versions, with patch levels '-2' and '-3' respectively, for a specific point in time. Probably build or deployment timestamps with an associated patch counter. I recognize that format immediately.
But what about that other one, `50209dec14f8`? Hmm, that's definitely not the same format. It looks like a short, hex-encoded string. My initial hunch is that it's probably a commit hash, a branch identifier, or some other unique identifier for version control, maybe git? I need more context to be certain, but the structure definitely suggests something like that. Perhaps an identifier from a different system, or an earlier versioning scheme? Let's keep digging and find out.
|
| 518/6 |
2026/09/09 18:28 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 50209dec14f8c594a9ef26237b7e7ddd39e12a40
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:44 2026 +0800
scsi: sg: Remove deprecated sg-big-buff
These deprecated sysctl has been broken since commit 26d1c80fd61e
("scsi/sg: move sg-big-buff sysctl to scsi/sg.c") and nobody has found
this. I believe it's time to remove it, which will allow us to clean up a
significant amount of code.
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-4-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index f38d36fbeef3..2b4b2a1a8e44 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -81,14 +81,14 @@ static int sg_proc_init(void);
#define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
-static int sg_big_buff = SG_DEF_RESERVED_SIZE;
/* N.B. This variable is readable and writeable via
- /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
- of this size (or less if there is not enough memory) will be reserved
- for use by this file descriptor. [Deprecated usage: this variable is also
- readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into
- the kernel (i.e. it is not a module).] */
-static int def_reserved_size = -1; /* picks up init parameter */
+ * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
+ * of this size (or less if there is not enough memory) will be reserved
+ * for use by this file descriptor.
+ */
+
+/* picks up init parameter */
+static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
@@ -1663,35 +1663,6 @@ MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
-#ifdef CONFIG_SYSCTL
-#include <linux/sysctl.h>
-
-static const struct ctl_table sg_sysctls[] = {
- {
- .procname = "sg-big-buff",
- .data = &sg_big_buff,
- .maxlen = sizeof(int),
- .mode = 0444,
- .proc_handler = proc_dointvec,
- },
-};
-
-static struct ctl_table_header *hdr;
-static void register_sg_sysctls(void)
-{
- if (!hdr)
- hdr = register_sysctl("kernel", sg_sysctls);
-}
-
-static void unregister_sg_sysctls(void)
-{
- unregister_sysctl_table(hdr);
-}
-#else
-#define register_sg_sysctls() do { } while (0)
-#define unregister_sg_sysctls() do { } while (0)
-#endif /* CONFIG_SYSCTL */
-
static int __init
init_sg(void)
{
@@ -1701,10 +1672,6 @@ init_sg(void)
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
}
- if (def_reserved_size >= 0)
- sg_big_buff = def_reserved_size;
- else
- def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1716,7 +1683,6 @@ init_sg(void)
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
- register_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
@@ -1731,7 +1697,6 @@ init_sg(void)
static void __exit
exit_sg(void)
{
- unregister_sg_sysctls();
#ifdef CONFIG_SCSI_PROC_FS
remove_proc_subtree("scsi/sg", NULL);
#endif /* CONFIG_SCSI_PROC_FS */
@@ -2207,10 +2172,8 @@ sg_add_sfp(Sg_device * sdp)
write_unlock_irqrestore(&sdp->sfd_lock, iflags);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_add_sfp: sfp=0x%p\n", sfp));
- if (unlikely(sg_big_buff != def_reserved_size))
- sg_big_buff = def_reserved_size;
- bufflen = min_t(int, sg_big_buff,
+ bufflen = min_t(int, def_reserved_size,
max_sectors_bytes(sdp->device->request_queue));
sg_build_reserve(sfp, bufflen);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
@@ -2438,7 +2401,7 @@ sg_proc_write_adio(struct file *filp, const char __user *buffer,
static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)
{
- return single_open(file, sg_proc_seq_show_int, &sg_big_buff);
+ return single_open(file, sg_proc_seq_show_int, &def_reserved_size);
}
static ssize_t
@@ -2455,7 +2418,7 @@ sg_proc_write_dressz(struct file *filp, const char __user *buffer,
if (err)
return err;
if (k <= 1048576) { /* limit "big buff" to 1 MB */
- sg_big_buff = k;
+ def_reserved_size = k;
return count;
}
return -ERANGE;
@@ -2628,7 +2591,7 @@ static int sg_proc_seq_show_debug(struct seq_file *s, void *v)
if (it && (0 == it->index))
seq_printf(s, "max_active_device=%d def_reserved_size=%d\n",
- (int)it->max, sg_big_buff);
+ (int)it->max, def_reserved_size);
read_lock_irqsave(&sg_index_lock, iflags);
sdp = it ? sg_lookup_dev(it->index) : NULL;
]
|
| 519/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 38478
output: 33
thoughts: 257
Thoughts: **Analyzing the User's Question about `scatter_elem_sz_set()`**
Okay, let's break this down meticulously. The user's question about `scatter_elem_sz_set()` has several layers. First, they're concerned about the bounds check: `if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))`. The core of the concern revolves around how this handles negative input values for `size`, which is declared as an `int`. They're wondering if the current check is robust and correct for negative values due to integer promotion or if we need to explicitly include `size < 0`. That's a valid point. We need to be absolutely sure this check is bulletproof.
A key point hinges on the data type of `PAGE_SIZE`. In kernel code, and likely here, `PAGE_SIZE` isn't a simple integer. Let me think. It is usually defined through `#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)` or `(1UL << PAGE_SHIFT)`. Ah! Right, it's an `unsigned long`! So, if `size` is an `int` and `PAGE_SIZE` is an `unsigned long`, that's a crucial cross-type comparison that needs careful consideration. How exactly is that comparison handled by the compiler? We have to ensure it's not causing unexpected behavior or, worse, vulnerabilities. I will double-check its definition, just to be absolutely certain.
|
| 520/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Error:
Args: map[Expression:#define PAGE_SIZE PathPrefix:arch/x86/include]
Results:
|
| 521/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 39104
output: 28
thoughts: 21
Thoughts: Here's my thought process, as requested:
**Finding the System's Page Size Definition**
Okay, so I need to nail down the `PAGE_SIZE` definition. This is fundamental, and I need to know where it's declared in this system. My first instinct, based on years of experience, is to start with the standard locations. I'm going to kick off a search for `#define PAGE_SIZE` in the system's include directories. Specifically, I'm thinking I'll start with the main `include/` directory, that's almost always a good bet for these kinds of system-level constants. If it's architecture-specific, it'll likely be in the `arch/` directory, so I'll be sure to expand the search there if I don't get a hit in `include/`. I'm expecting this to be fairly straightforward, a quick grep or find command should get me where I need to be. No need to overcomplicate things, start simple and see what we get.
|
| 522/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Args: map[Expression:#define PAGE_SIZE\b PathPrefix:include]
Results: map[Output:include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
]
|
| 523/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 39444
output: 25
thoughts: 24
Thoughts: Here's my summary, as though I'm thinking through this:
**Investigating Memory Page Size**
Okay, so I need to find the definition for `PAGE_SIZE`. This is a fundamental constant, obviously, so it's probably defined in a standard, architecture-independent header file. Let me quickly scan through my mental map of kernel include directories... Ah, yeah, that makes sense. `include/asm-generic/page.h` is the likely candidate. That's usually where these sorts of platform-agnostic definitions live. Or maybe something similar in the architecture-specific include directory, if I'm on a system that behaves non-typically. But let's start with the generic one. That's the go-to first check. Time to dive in there!
|
| 524/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Args: map[Expression:define PAGE_SIZE PathPrefix:arch]
Results: map[Output:arch/arc/include/uapi/asm/page.h-26-#define PAGE_SHIFT 13
arch/arc/include/uapi/asm/page.h:27:#define PAGE_SIZE _BITUL(PAGE_SHIFT) /* Default 8K */
arch/arc/include/uapi/asm/page.h-28-#define PAGE_MASK (~(PAGE_SIZE-1))
--
arch/hexagon/kernel/vmlinux.lds.S=21=See asm-generic/sections.h for seemingly required labels.
--
arch/hexagon/kernel/vmlinux.lds.S-23-
arch/hexagon/kernel/vmlinux.lds.S:24:#define PAGE_SIZE _PAGE_SIZE
arch/hexagon/kernel/vmlinux.lds.S-25-
--
arch/loongarch/kernel/vmlinux.lds.S-6-
arch/loongarch/kernel/vmlinux.lds.S:7:#define PAGE_SIZE _PAGE_SIZE
arch/loongarch/kernel/vmlinux.lds.S-8-#define RO_EXCEPTION_TABLE_ALIGN 4
--
arch/mips/kernel/vmlinux.lds.S-4-
arch/mips/kernel/vmlinux.lds.S:5:#define PAGE_SIZE _PAGE_SIZE
arch/mips/kernel/vmlinux.lds.S-6-
--
arch/powerpc/boot/page.h-16-#define PAGE_SHIFT 12
arch/powerpc/boot/page.h:17:#define PAGE_SIZE (ASM_CONST(1) << PAGE_SHIFT)
arch/powerpc/boot/page.h-18-#define PAGE_MASK (~(PAGE_SIZE-1))
--
arch/powerpc/include/asm/spu.h=442=struct spu_priv1 {
--
arch/powerpc/include/asm/spu.h-543- u64 smm_hid; /* 0x580 */
arch/powerpc/include/asm/spu.h:544:#define PAGE_SIZE_MASK 0xf000000000000000ull
arch/powerpc/include/asm/spu.h:545:#define PAGE_SIZE_16MB_64KB 0x2000000000000000ull
arch/powerpc/include/asm/spu.h-546- u8 pad_0x588_0x600[0x600 - 0x588]; /* 0x588 */
--
arch/sparc/lib/copy_page.S-30-#if (PAGE_SHIFT == 13)
arch/sparc/lib/copy_page.S:31:#define PAGE_SIZE_REM 0x80
arch/sparc/lib/copy_page.S-32-#elif (PAGE_SHIFT == 16)
arch/sparc/lib/copy_page.S:33:#define PAGE_SIZE_REM 0x100
arch/sparc/lib/copy_page.S-34-#else
]
|
| 525/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 40443
output: 38
thoughts: 21
Thoughts: Here's my take on the thought process, as if it were my own:
**Investigating Memory Management on x86**
Alright, time to dive into the nitty-gritty of memory management, x86-style. Where do I start? Let's begin at the core: `arch/x86/include/asm/page_types.h`. This is likely the crucial header file defining the fundamental data structures and constants that describe physical and virtual memory pages on the x86 architecture. I'm expecting to find declarations related to page sizes (4KB, 2MB, 1GB), page flags (present, writable, executable, dirty, etc.), and potentially even definitions for page table entries (PTEs) or page directory entries (PDEs). Understanding these types is absolutely foundational. From here, I can hopefully extrapolate how the kernel actually translates virtual addresses into physical addresses. This is the bedrock on which all memory management features sit. This'll be a key first step.
|
| 526/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SIZE PathPrefix:arch/x86/include/asm/page_types.h]
Results: map[Output:arch/x86/include/asm/page_types.h-20-#define HPAGE_SHIFT PMD_SHIFT
arch/x86/include/asm/page_types.h:21:#define HPAGE_SIZE (_AC(1,UL) << HPAGE_SHIFT)
arch/x86/include/asm/page_types.h:22:#define HPAGE_MASK (~(HPAGE_SIZE - 1))
arch/x86/include/asm/page_types.h-23-#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
]
|
| 527/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 40871
output: 41
thoughts: 24
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Diving into x86 Page Definitions**
Alright, time to get granular. When I'm working with memory management, especially within the x86 architecture, I *always* double-check the fundamental definitions. I need to make sure I'm crystal clear on the `PAGE_SIZE`, the `PAGE_SHIFT`, and all those crucial constants that underpin how the kernel handles physical and virtual memory. The user-space ABI is built on these. So, before I go any further, I'm heading over to the source of truth for the kernel's view on page types. Specifically, I'm going to take a look at `arch/x86/include/uapi/asm/page_types.h`. That's where I expect to find the authoritative definitions of page-related types and constants. I need to make sure there haven't been any subtle shifts or unexpected changes that could throw off my assumptions. Gotta keep those fundamentals rock solid!
|
| 528/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Error:
Args: map[Expression:PAGE_SIZE PathPrefix:arch/x86/include/uapi/asm/page_types.h]
Results:
|
| 529/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 41170
output: 32
thoughts: 17
Thoughts: Here's my thought process, as if I were thinking it:
**Finding the x86 `PAGE_SIZE` Definition**
Okay, so I need to track down the definition of `PAGE_SIZE` specifically for the x86 architecture. It's usually a pretty standard constant, but I want to be certain I'm getting the right value for this context. My instinct is to check the typical places: system headers, kernel source, or potentially a dedicated architecture-specific include file. I'll probably start with the system headers first. I'd imagine that `bits/mman.h` or something similar would be a likely candidate, or maybe `asm/page.h`. I'll want to quickly check the kernel source too, looking for definitions in `arch/x86/include/asm` or something similarly structured. I need to be careful, of course; this is fundamental, so I need to verify that I'm not accidentally using a value that is intended for another architecture. I might quickly cross-reference any relevant documentation on memory management for x86 to confirm my findings and make sure there aren't any subtle variations or platform-specific considerations I'm missing. Right, let's start digging!
|
| 530/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SIZE\b PathPrefix:arch/x86/include]
Results: map[Output:arch/x86/include/asm/boot.h-76-
arch/x86/include/asm/boot.h:77:#define TRAMPOLINE_32BIT_SIZE (2 * PAGE_SIZE)
arch/x86/include/asm/boot.h-78-
arch/x86/include/asm/boot.h:79:#define TRAMPOLINE_32BIT_CODE_OFFSET PAGE_SIZE
arch/x86/include/asm/boot.h-80-#define TRAMPOLINE_32BIT_CODE_SIZE 0xA0
--
arch/x86/include/asm/cpu_entry_area.h=41=struct cea_exception_stacks {
arch/x86/include/asm/cpu_entry_area.h:42: ESTACKS_MEMBERS(PAGE_SIZE, EXCEPTION_STKSZ)
arch/x86/include/asm/cpu_entry_area.h-43-};
--
arch/x86/include/asm/cpu_entry_area.h=48=enum exception_stack_ordering {
--
arch/x86/include/asm/cpu_entry_area.h-70-#define CEA_ESTACK_PAGES \
arch/x86/include/asm/cpu_entry_area.h:71: (sizeof(struct cea_exception_stacks) / PAGE_SIZE)
arch/x86/include/asm/cpu_entry_area.h-72-
--
arch/x86/include/asm/cpu_entry_area.h=76=struct doublefault_stack {
arch/x86/include/asm/cpu_entry_area.h:77: unsigned long stack[(PAGE_SIZE - sizeof(struct x86_hw_tss)) / sizeof(unsigned long)];
arch/x86/include/asm/cpu_entry_area.h-78- struct x86_hw_tss tss;
arch/x86/include/asm/cpu_entry_area.h:79:} __aligned(PAGE_SIZE);
arch/x86/include/asm/cpu_entry_area.h-80-#endif
--
arch/x86/include/asm/cpu_entry_area.h=90=struct cpu_entry_area {
arch/x86/include/asm/cpu_entry_area.h:91: char gdt[PAGE_SIZE];
arch/x86/include/asm/cpu_entry_area.h-92-
--
arch/x86/include/asm/cpu_entry_area.h-98-#ifdef CONFIG_X86_32
arch/x86/include/asm/cpu_entry_area.h:99: char guard_entry_stack[PAGE_SIZE];
arch/x86/include/asm/cpu_entry_area.h-100-#endif
--
arch/x86/include/asm/cpu_entry_area.h-103-#ifdef CONFIG_X86_32
arch/x86/include/asm/cpu_entry_area.h:104: char guard_doublefault_stack[PAGE_SIZE];
arch/x86/include/asm/cpu_entry_area.h-105- struct doublefault_stack doublefault_stack;
--
arch/x86/include/asm/desc.h=44=struct gdt_page {
arch/x86/include/asm/desc.h-45- struct desc_struct gdt[GDT_ENTRIES];
arch/x86/include/asm/desc.h:46:} __attribute__((aligned(PAGE_SIZE)));
arch/x86/include/asm/desc.h-47-
--
arch/x86/include/asm/fixmap.h=55=extern unsigned long __FIXADDR_TOP;
--
arch/x86/include/asm/fixmap.h-57-#else
arch/x86/include/asm/fixmap.h:58:#define FIXADDR_TOP (round_up(VSYSCALL_ADDR + PAGE_SIZE, 1<<PMD_SHIFT) - \
arch/x86/include/asm/fixmap.h:59: PAGE_SIZE)
arch/x86/include/asm/fixmap.h-60-#endif
--
arch/x86/include/asm/fpu/types.h=369=union fpregs_state {
--
arch/x86/include/asm/fpu/types.h-373- struct xregs_state xsave;
arch/x86/include/asm/fpu/types.h:374: u8 __padding[PAGE_SIZE];
arch/x86/include/asm/fpu/types.h-375-};
--
arch/x86/include/asm/intel_ds.h-5-
arch/x86/include/asm/intel_ds.h:6:#define BTS_BUFFER_SIZE (PAGE_SIZE << 4)
arch/x86/include/asm/intel_ds.h-7-#define PEBS_BUFFER_SHIFT 4
arch/x86/include/asm/intel_ds.h:8:#define PEBS_BUFFER_SIZE (PAGE_SIZE << PEBS_BUFFER_SHIFT)
arch/x86/include/asm/intel_ds.h-9-
--
arch/x86/include/asm/intel_ds.h-13- */
arch/x86/include/asm/intel_ds.h:14:#define ARCH_PEBS_THRESH_MULTI ((PEBS_BUFFER_SIZE - PAGE_SIZE) >> PEBS_BUFFER_SHIFT)
arch/x86/include/asm/intel_ds.h-15-#define ARCH_PEBS_THRESH_SINGLE 1
--
arch/x86/include/asm/intel_ds.h=28=struct debug_store {
--
arch/x86/include/asm/intel_ds.h-37- u64 pebs_event_reset[MAX_PEBS_EVENTS + MAX_FIXED_PEBS_EVENTS];
arch/x86/include/asm/intel_ds.h:38:} __aligned(PAGE_SIZE);
arch/x86/include/asm/intel_ds.h-39-
--
arch/x86/include/asm/kexec.h-24-
arch/x86/include/asm/kexec.h:25:# define KEXEC_CONTROL_PAGE_SIZE 4096
arch/x86/include/asm/kexec.h-26-# define KEXEC_CONTROL_CODE_MAX_SIZE 2048
--
arch/x86/include/asm/kfence.h=22=static inline bool arch_kfence_init_pool(void)
--
arch/x86/include/asm/kfence.h-26- for (addr = (unsigned long)__kfence_pool; is_kfence_address((void *)addr);
arch/x86/include/asm/kfence.h:27: addr += PAGE_SIZE) {
arch/x86/include/asm/kfence.h-28- unsigned int level;
--
arch/x86/include/asm/kvm_host.h-137-#define KVM_HPAGE_SHIFT(x) (PAGE_SHIFT + KVM_HPAGE_GFN_SHIFT(x))
arch/x86/include/asm/kvm_host.h:138:#define KVM_HPAGE_SIZE(x) (1UL << KVM_HPAGE_SHIFT(x))
arch/x86/include/asm/kvm_host.h:139:#define KVM_HPAGE_MASK(x) (~(KVM_HPAGE_SIZE(x) - 1))
arch/x86/include/asm/kvm_host.h:140:#define KVM_PAGES_PER_HPAGE(x) (KVM_HPAGE_SIZE(x) / PAGE_SIZE)
arch/x86/include/asm/kvm_host.h-141-
--
arch/x86/include/asm/page_32.h=26=static inline void clear_page(void *page)
arch/x86/include/asm/page_32.h-27-{
arch/x86/include/asm/page_32.h:28: memset(page, 0, PAGE_SIZE);
arch/x86/include/asm/page_32.h-29-}
--
arch/x86/include/asm/page_32.h=31=static inline void copy_page(void *to, void *from)
arch/x86/include/asm/page_32.h-32-{
arch/x86/include/asm/page_32.h:33: memcpy(to, from, PAGE_SIZE);
arch/x86/include/asm/page_32.h-34-}
--
arch/x86/include/asm/page_32_types.h-22-#define THREAD_SIZE_ORDER 1
arch/x86/include/asm/page_32_types.h:23:#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
arch/x86/include/asm/page_32_types.h-24-
--
arch/x86/include/asm/page_64.h=85=static inline void clear_pages(void *addr, unsigned int npages)
arch/x86/include/asm/page_64.h-86-{
arch/x86/include/asm/page_64.h:87: u64 len = npages * PAGE_SIZE;
arch/x86/include/asm/page_64.h-88- /*
--
arch/x86/include/asm/page_64.h=138=static __always_inline unsigned long task_size_max(void)
--
arch/x86/include/asm/page_64.h-144- "=r" (ret),
arch/x86/include/asm/page_64.h:145: [small] "i" ((1ul << 47)-PAGE_SIZE),
arch/x86/include/asm/page_64.h:146: [large] "i" ((1ul << 56)-PAGE_SIZE));
arch/x86/include/asm/page_64.h-147-
--
arch/x86/include/asm/page_64_types.h-15-#define THREAD_SIZE_ORDER (2 + KASAN_STACK_ORDER)
arch/x86/include/asm/page_64_types.h:16:#define THREAD_SIZE (PAGE_SIZE << THREAD_SIZE_ORDER)
arch/x86/include/asm/page_64_types.h-17-
arch/x86/include/asm/page_64_types.h-18-#define EXCEPTION_STACK_ORDER (1 + KASAN_STACK_ORDER)
arch/x86/include/asm/page_64_types.h:19:#define EXCEPTION_STKSZ (PAGE_SIZE << EXCEPTION_STACK_ORDER)
arch/x86/include/asm/page_64_types.h-20-
arch/x86/include/asm/page_64_types.h-21-#define IRQ_STACK_ORDER (2 + KASAN_STACK_ORDER)
arch/x86/include/asm/page_64_types.h:22:#define IRQ_STACK_SIZE (PAGE_SIZE << IRQ_STACK_ORDER)
arch/x86/include/asm/page_64_types.h-23-
--
arch/x86/include/asm/page_64_types.h-53-#define TASK_SIZE_MAX task_size_max()
arch/x86/include/asm/page_64_types.h:54:#define DEFAULT_MAP_WINDOW ((1UL << 47) - PAGE_SIZE)
arch/x86/include/asm/page_64_types.h-55-
--
arch/x86/include/asm/page_types.h-20-#define HPAGE_SHIFT PMD_SHIFT
arch/x86/include/asm/page_types.h:21:#define HPAGE_SIZE (_AC(1,UL) << HPAGE_SHIFT)
arch/x86/include/asm/page_types.h:22:#define HPAGE_MASK (~(HPAGE_SIZE - 1))
arch/x86/include/asm/page_types.h-23-#define HUGETLB_PAGE_ORDER (HPAGE_SHIFT - PAGE_SHIFT)
--
arch/x86/include/asm/pgtable_32_areas.h=17=extern bool __vmalloc_start_set; /* set once high_memory is set */
--
arch/x86/include/asm/pgtable_32_areas.h-26-
arch/x86/include/asm/pgtable_32_areas.h:27:#define CPU_ENTRY_AREA_PAGES (NR_CPUS * DIV_ROUND_UP(sizeof(struct cpu_entry_area), PAGE_SIZE))
arch/x86/include/asm/pgtable_32_areas.h-28-
--
arch/x86/include/asm/pgtable_32_areas.h-30-#define CPU_ENTRY_AREA_BASE \
arch/x86/include/asm/pgtable_32_areas.h:31: ((FIXADDR_TOT_START - PAGE_SIZE*(CPU_ENTRY_AREA_PAGES+1)) & PMD_MASK)
arch/x86/include/asm/pgtable_32_areas.h-32-
arch/x86/include/asm/pgtable_32_areas.h-33-#define LDT_BASE_ADDR \
arch/x86/include/asm/pgtable_32_areas.h:34: ((CPU_ENTRY_AREA_BASE - PAGE_SIZE) & PMD_MASK)
arch/x86/include/asm/pgtable_32_areas.h-35-
--
arch/x86/include/asm/pgtable_32_areas.h-38-#define PKMAP_BASE \
arch/x86/include/asm/pgtable_32_areas.h:39: ((LDT_BASE_ADDR - PAGE_SIZE) & PMD_MASK)
arch/x86/include/asm/pgtable_32_areas.h-40-
arch/x86/include/asm/pgtable_32_areas.h-41-#ifdef CONFIG_HIGHMEM
arch/x86/include/asm/pgtable_32_areas.h:42:# define VMALLOC_END (PKMAP_BASE - 2 * PAGE_SIZE)
arch/x86/include/asm/pgtable_32_areas.h-43-#else
arch/x86/include/asm/pgtable_32_areas.h:44:# define VMALLOC_END (LDT_BASE_ADDR - 2 * PAGE_SIZE)
arch/x86/include/asm/pgtable_32_areas.h-45-#endif
--
arch/x86/include/asm/pgtable_64.h=277=L3_START_KERNEL = pud_index(__START_KERNEL_map)
--
arch/x86/include/asm/pgtable_64.h-279-#define SYM_DATA_START_PAGE_ALIGNED(name) \
arch/x86/include/asm/pgtable_64.h:280: SYM_START(name, SYM_L_GLOBAL, .balign PAGE_SIZE)
arch/x86/include/asm/pgtable_64.h-281-
--
arch/x86/include/asm/pgtable_64_types.h=43=extern unsigned int ptrs_per_p4d;
--
arch/x86/include/asm/pgtable_64_types.h-190-
arch/x86/include/asm/pgtable_64_types.h:191:#define PGD_KERNEL_START ((PAGE_SIZE / 2) / sizeof(pgd_t))
arch/x86/include/asm/pgtable_64_types.h-192-
--
arch/x86/include/asm/pgtable_areas.h-9-#define CPU_ENTRY_AREA_RO_IDT CPU_ENTRY_AREA_BASE
arch/x86/include/asm/pgtable_areas.h:10:#define CPU_ENTRY_AREA_PER_CPU (CPU_ENTRY_AREA_RO_IDT + PAGE_SIZE)
arch/x86/include/asm/pgtable_areas.h-11-
--
arch/x86/include/asm/processor.h=379=struct entry_stack {
arch/x86/include/asm/processor.h:380: char stack[PAGE_SIZE];
arch/x86/include/asm/processor.h-381-};
--
arch/x86/include/asm/processor.h=383=struct entry_stack_page {
arch/x86/include/asm/processor.h-384- struct entry_stack stack;
arch/x86/include/asm/processor.h:385:} __aligned(PAGE_SIZE);
arch/x86/include/asm/processor.h-386-
--
arch/x86/include/asm/processor.h=418=struct tss_struct {
--
arch/x86/include/asm/processor.h-426- struct x86_io_bitmap io_bitmap;
arch/x86/include/asm/processor.h:427:} __aligned(PAGE_SIZE);
arch/x86/include/asm/processor.h-428-
--
arch/x86/include/asm/realmode.h=81=static __always_inline size_t real_mode_size_needed(void)
--
arch/x86/include/asm/realmode.h-85-
arch/x86/include/asm/realmode.h:86: return ALIGN(real_mode_blob_end - real_mode_blob, PAGE_SIZE);
arch/x86/include/asm/realmode.h-87-}
--
arch/x86/include/asm/sev.h=206=struct snp_guest_msg {
arch/x86/include/asm/sev.h-207- struct snp_guest_msg_hdr hdr;
arch/x86/include/asm/sev.h:208: u8 payload[PAGE_SIZE - sizeof(struct snp_guest_msg_hdr)];
arch/x86/include/asm/sev.h-209-} __packed;
--
arch/x86/include/asm/sev.h=327=struct svsm_ca {
--
arch/x86/include/asm/sev.h-331-
arch/x86/include/asm/sev.h:332: u8 svsm_buffer[PAGE_SIZE - 8];
arch/x86/include/asm/sev.h-333-};
--
arch/x86/include/asm/sev.h=582=static inline void sev_evict_cache(void *va, int npages)
--
arch/x86/include/asm/sev.h-594- for (page_idx = 0; page_idx < npages; page_idx++) {
arch/x86/include/asm/sev.h:595: val = bytes[page_idx * PAGE_SIZE];
arch/x86/include/asm/sev.h:596: val = bytes[page_idx * PAGE_SIZE + PAGE_SIZE - 1];
arch/x86/include/asm/sev.h-597- }
--
arch/x86/include/asm/shmparam.h-4-
arch/x86/include/asm/shmparam.h:5:#define SHMLBA PAGE_SIZE /* attach addr a multiple of this */
arch/x86/include/asm/shmparam.h-6-
--
arch/x86/include/asm/stacktrace.h=42=bool get_stack_guard_info(unsigned long *stack, struct stack_info *info)
--
arch/x86/include/asm/stacktrace.h-47- /* but if it is in the page below it, we hit a guard */
arch/x86/include/asm/stacktrace.h:48: return get_stack_info_noinstr((void *)stack + PAGE_SIZE, current, info);
arch/x86/include/asm/stacktrace.h-49-}
--
arch/x86/include/asm/svm.h=540=struct vmcb {
--
arch/x86/include/asm/svm.h-558-#define EXPECTED_VMCB_CONTROL_AREA_SIZE 1024
arch/x86/include/asm/svm.h:559:#define EXPECTED_GHCB_SIZE PAGE_SIZE
arch/x86/include/asm/svm.h-560-
--
arch/x86/include/asm/tlbflush.h=350=static inline void flush_tlb_page(struct vm_area_struct *vma, unsigned long a)
arch/x86/include/asm/tlbflush.h-351-{
arch/x86/include/asm/tlbflush.h:352: flush_tlb_mm_range(vma->vm_mm, a, a + PAGE_SIZE, PAGE_SHIFT, false);
arch/x86/include/asm/tlbflush.h-353-}
--
arch/x86/include/asm/uaccess_64.h=98=static inline bool __access_ok(const void __user *ptr, unsigned long size)
arch/x86/include/asm/uaccess_64.h-99-{
arch/x86/include/asm/uaccess_64.h:100: if (__builtin_constant_p(size <= PAGE_SIZE) && size <= PAGE_SIZE) {
arch/x86/include/asm/uaccess_64.h-101- return valid_user_address(ptr);
--
arch/x86/include/asm/vdso.h=13=struct vdso_image {
arch/x86/include/asm/vdso.h-14- void *data;
arch/x86/include/asm/vdso.h:15: unsigned long size; /* Always a multiple of PAGE_SIZE */
arch/x86/include/asm/vdso.h-16-
--
arch/x86/include/asm/vdso/vsyscall.h-7-#define VDSO_NR_VCLOCK_PAGES 2
arch/x86/include/asm/vdso/vsyscall.h:8:#define VDSO_VCLOCK_PAGES_START(_b) ((_b) + (__VDSO_PAGES - VDSO_NR_VCLOCK_PAGES) * PAGE_SIZE)
arch/x86/include/asm/vdso/vsyscall.h-9-#define VDSO_PAGE_PVCLOCK_OFFSET 0
--
arch/x86/include/asm/xen/page.h=25=typedef struct xpaddr {
--
arch/x86/include/asm/xen/page.h-47-
arch/x86/include/asm/xen/page.h:48:#define P2M_PER_PAGE (PAGE_SIZE / sizeof(unsigned long))
arch/x86/include/asm/xen/page.h-49-
--
arch/x86/include/uapi/asm/amd_hsmp.h=641=struct hsmp_telemetry_data {
--
arch/x86/include/uapi/asm/amd_hsmp.h-656- * Fetch the firmware metric (telemetry) table for a given socket via the
arch/x86/include/uapi/asm/amd_hsmp.h:657: * HSMP character device. This avoids the PAGE_SIZE limitation of the
arch/x86/include/uapi/asm/amd_hsmp.h-658- * sysfs binary attribute path for tables larger than one page (such as the
]
|
| 531/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 47623
output: 27
thoughts: 1321
Thoughts: **Analyzing Potential Integer Overflow and Comparison Issues in Kernel Code**
Okay, let's break this down. I'm looking at how `PAGE_SIZE` is defined, likely in a kernel header file – either `vdso/page.h` or `asm-generic/page.h`. It's defined as an unsigned long, which makes sense for representing memory sizes. My mind is immediately drawn to how this interacts with signed integer comparisons, particularly when a variable `size` (likely an `int`) is compared against `PAGE_SIZE`.
The core issue comes down to C's usual arithmetic conversions. If I'm comparing a signed `int` (like `size`) with an `unsigned long` (like `PAGE_SIZE`), the signed operand gets *converted* to an unsigned type. So, a negative `size` (e.g., -1) becomes a massive positive number (ULONG_MAX) on a 64-bit system.
So, let's say `size` is -1. Is `-1 < PAGE_SIZE`? No, because in the comparison, -1 is treated as the huge unsigned number `ULONG_MAX`. It's not. It's false.
But what about the condition `size > (PAGE_SIZE << MAX_PAGE_ORDER)`? Let's say `PAGE_SIZE` is 4096 (0x1000) and `MAX_PAGE_ORDER` is 10. Then `(PAGE_SIZE << MAX_PAGE_ORDER)` becomes 4MB (4194304). If size is -1, then the unsigned value is still the max value, ULONG_MAX. Is `ULONG_MAX > 4194304`? Yes, that is true, because of the unsigned conversion!
Now, the important part: Does the comparison catch a negative size value like -1 in an `if` statement? Let's look at a combined condition: `if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))`. If `size` is -1, then `size < PAGE_SIZE` evaluates to false, because -1 becomes `ULONG_MAX`. But, the second part of the `OR` statement then picks it up because `-1` which is converted to `ULONG_MAX`, is a massive number. Therefore, this statement will evaluate to true because of the unsigned conversion.
But, hang on – what about compiler warnings? This is where `-Wsign-compare` comes in. This is exactly the kind of comparison that flag is meant to catch: "comparison between signed and unsigned integer expressions". That's a huge red flag! The compiler is telling me this could be problematic, and I need to be careful.
Let's look at real-world examples in the kernel itself. Take `drivers/scsi/sg.c`: it has a check like `if (size < 0 || size > 1048576)`. This check *appears* to work. It's correctly catches negative values.
Now, look at how `init_sg()` handles a similar situation: `if (scatter_elem_sz < PAGE_SIZE)`. This appears to "work". However, a negative value (e.g., `-1`) would evaluate to false, because the comparison is done between an `int` and an `unsigned long`. That's a bit subtle. `-1 < PAGE_SIZE` is false because of the implicit unsigned conversion. That is an extremely common C trap!
To be absolutely sure, I have to test this. If I have `int a = -1;` and `unsigned long b = 4096;`, then `a < b` is false. Because `-1` is converted to `~0UL` (`0xFFFFFFFFFFFFFFFF`), which is not less than `4096UL`. The compiler *should* emit a `-Wsign-compare` warning.
So, I need to always be very conscious about signed/unsigned comparisons, especially when size values can be negative. I should be looking for `-Wsign-compare` warnings and reviewing those carefully to avoid subtle bugs in the kernel that result from integer conversion. Let's see if I can find out more about where `MAX_PAGE_ORDER` is defined to verify that assumptions are correct.
|
| 532/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Args: map[Expression:define MAX_PAGE_ORDER PathPrefix:include]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
]
|
| 533/6 |
2026/09/09 18:28 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 50017
output: 32
thoughts: 96
Thoughts: **My Thought Process on Page Order**
Okay, so `MAX_PAGE_ORDER` – that's defined in `include/linux/mmzone.h`, right? Now, I need to jog my memory... What's the *maximum* order I can feed into `alloc_pages`? Ah, right, it's `MAX_PAGE_ORDER`! That's the key. Now, let me think about the arguments for `alloc_pages(gfp_mask, order)`... The important part here is the `order`. Can `order` actually *be* `MAX_PAGE_ORDER`? It's time to confirm the details, so let's head over to the definition of `alloc_pages` in `include/linux/gfp.h`. Time to dig in and clarify my understanding.
|
| 534/6 |
2026/09/09 18:28 |
tool |
grepper |
0m
Args: map[Expression:alloc_pages\( PathPrefix:include/linux/gfp.h]
Results: map[Output:include/linux/gfp.h=295=static inline struct folio *vma_alloc_folio_noprof(gfp_t gfp, int order,
--
include/linux/gfp.h-301-
include/linux/gfp.h:302:#define alloc_pages(...) alloc_hooks(alloc_pages_noprof(__VA_ARGS__))
include/linux/gfp.h-303-#define folio_alloc(...) alloc_hooks(folio_alloc_noprof(__VA_ARGS__))
--
include/linux/gfp.h-306-
include/linux/gfp.h:307:#define alloc_page(gfp_mask) alloc_pages(gfp_mask, 0)
include/linux/gfp.h-308-
]
|
| 535/6 |
2026/09/09 18:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 50528
output: 27
thoughts: 21
Thoughts: Okay, let's dive into this. Here's how I'd approach this task, as if these were my internal thoughts:
**Investigating Memory Allocation Limits**
Right, let's get down to brass tacks. I need to understand the constraints on memory allocation. My immediate focus is on how `alloc_pages_noprof` and `alloc_pages` are behaving. I know these functions intimately, and understanding their individual limits is critical to diagnosing any performance bottlenecks or memory allocation failures I might be seeing. My expertise tells me that checking the limits in these particular allocators will give me insight into the larger memory landscape. This will require some deeper investigation...
|
| 536/6 |
2026/09/09 18:29 |
tool |
grepper |
0m
Args: map[Expression:MAX_PAGE_ORDER PathPrefix:mm/]
Results: map[Output:mm/Kconfig=319=config SHUFFLE_PAGE_ALLOCATOR
--
mm/Kconfig-329- allocations to compliment SLAB_FREELIST_RANDOM, but the
mm/Kconfig:330: default granularity of shuffling on the MAX_PAGE_ORDER i.e, 10th
mm/Kconfig-331- order of pages is selected based on cache utilization benefits
--
mm/Kconfig=697=config HUGETLB_PAGE_SIZE_VARIABLE
--
mm/Kconfig-703-
mm/Kconfig:704: Note that the pageblock_order cannot exceed MAX_PAGE_ORDER and will be
mm/Kconfig:705: clamped down to MAX_PAGE_ORDER.
mm/Kconfig-706-
--
mm/Kconfig=1100=config ARCH_FORCE_MAX_ORDER
--
mm/Kconfig-1104-# When ARCH_FORCE_MAX_ORDER is not defined,
mm/Kconfig:1105:# the default page block order is MAX_PAGE_ORDER (10) as per
mm/Kconfig-1106-# include/linux/mmzone.h.
--
mm/Kconfig=1108=config PAGE_BLOCK_MAX_ORDER
--
mm/Kconfig-1117- them. The maximum size of the page block order is at least limited by
mm/Kconfig:1118: ARCH_FORCE_MAX_ORDER/MAX_PAGE_ORDER.
mm/Kconfig-1119-
--
mm/Kconfig-1121- order when the page block order is required to be smaller than
mm/Kconfig:1122: ARCH_FORCE_MAX_ORDER/MAX_PAGE_ORDER or other limits
mm/Kconfig-1123- (see include/linux/pageblock-flags.h for details).
--
mm/compaction.c=575=static unsigned long isolate_freepages_block(struct compact_control *cc,
--
mm/compaction.c-619-
mm/compaction.c:620: if ((order <= MAX_PAGE_ORDER) &&
mm/compaction.c-621- (blockpfn + (1UL << order) <= end_pfn)) {
--
mm/compaction.c=855=isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
--
mm/compaction.c-976-
mm/compaction.c:977: if (order <= MAX_PAGE_ORDER) {
mm/compaction.c-978- low_pfn += (1UL << order) - 1;
--
mm/compaction.c-1035- */
mm/compaction.c:1036: if (freepage_order > 0 && freepage_order <= MAX_PAGE_ORDER) {
mm/compaction.c-1037- low_pfn += (1UL << freepage_order) - 1;
--
mm/compaction.c-1055- if (skip_isolation_on_order(order, cc->order)) {
mm/compaction.c:1056: if (order <= MAX_PAGE_ORDER) {
mm/compaction.c-1057- low_pfn += (1UL << order) - 1;
--
mm/debug_page_alloc.c=21=static int __init debug_guardpage_minorder_setup(char *buf)
--
mm/debug_page_alloc.c-24-
mm/debug_page_alloc.c:25: if (!buf || kstrtouint(buf, 10, &res) < 0 || res > MAX_PAGE_ORDER / 2) {
mm/debug_page_alloc.c-26- pr_err("Bad debug_guardpage_minorder value: %s\n", buf ?: "(missing)");
--
mm/debug_vm_pgtable.c=1046=debug_vm_pgtable_alloc_huge_page(struct pgtable_debug_args *args, int order)
--
mm/debug_vm_pgtable.c-1050-#ifdef CONFIG_CONTIG_ALLOC
mm/debug_vm_pgtable.c:1051: if (order > MAX_PAGE_ORDER) {
mm/debug_vm_pgtable.c-1052- page = alloc_contig_pages((1 << order), GFP_KERNEL,
--
mm/debug_vm_pgtable.c-1060-
mm/debug_vm_pgtable.c:1061: if (order <= MAX_PAGE_ORDER)
mm/debug_vm_pgtable.c-1062- page = alloc_pages(GFP_KERNEL, order);
--
mm/huge_memory.c=1051=static int __init hugepage_init(void)
--
mm/huge_memory.c-1063- */
mm/huge_memory.c:1064: MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER > MAX_PAGE_ORDER);
mm/huge_memory.c-1065-
--
mm/hugetlb.c=2746=int replace_free_hugepage_folios(unsigned long start_pfn, unsigned long end_pfn)
--
mm/hugetlb.c-2799-
mm/hugetlb.c:2800: if (order <= MAX_PAGE_ORDER)
mm/hugetlb.c-2801- nr = 1UL << order;
--
mm/hugetlb.c=3235=static void __init prep_and_add_bootmem_folios(struct hstate *h,
--
mm/hugetlb.c-3266- * Put bootmem huge pages into the standard lists after mem_map is up.
mm/hugetlb.c:3267: * Note: This only applies to gigantic (order > MAX_PAGE_ORDER) pages.
mm/hugetlb.c-3268- */
--
mm/hugetlb.c=4418=static int __init default_hugepagesz_setup(char *s)
--
mm/hugetlb.c-4450- * then default_hstate_max_huge_pages is set. If the default huge
mm/hugetlb.c:4451: * page size is gigantic (> MAX_PAGE_ORDER), then the pages must be
mm/hugetlb.c-4452- * allocated here from bootmem allocator.
--
mm/hugetlb_cma.c=211=void __init hugetlb_cma_reserve(void)
--
mm/hugetlb_cma.c-259- */
mm/hugetlb_cma.c:260: VM_WARN_ON(order <= MAX_PAGE_ORDER);
mm/hugetlb_cma.c-261- gigantic_page_size = PAGE_SIZE << order;
--
mm/kmsan/init.c=144=static struct smallstack collect = {
mm/kmsan/init.c-145- .index = 0,
mm/kmsan/init.c:146: .order = MAX_PAGE_ORDER,
mm/kmsan/init.c-147-};
--
mm/kmsan/init.c=203=static void kmsan_memblock_discard(void)
--
mm/kmsan/init.c-215- */
mm/kmsan/init.c:216: collect.order = MAX_PAGE_ORDER;
mm/kmsan/init.c:217: for (int i = MAX_PAGE_ORDER; i >= 0; i--) {
mm/kmsan/init.c-218- if (held_back[i].shadow)
--
mm/memblock.c=2329=static void __init __free_pages_memory(unsigned long start, unsigned long end)
--
mm/memblock.c-2337- * __ffs() behaviour is undefined for 0. start == 0 is
mm/memblock.c:2338: * MAX_PAGE_ORDER-aligned, set order to MAX_PAGE_ORDER for
mm/memblock.c-2339- * the case.
--
mm/memblock.c-2341- if (start)
mm/memblock.c:2342: order = min_t(int, MAX_PAGE_ORDER, __ffs(start));
mm/memblock.c-2343- else
mm/memblock.c:2344: order = MAX_PAGE_ORDER;
mm/memblock.c-2345-
--
mm/memory_hotplug.c=654=static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages)
--
mm/memory_hotplug.c-659- /*
mm/memory_hotplug.c:660: * Online the pages in MAX_PAGE_ORDER aligned chunks. The callback might
mm/memory_hotplug.c-661- * decide to not expose all pages to the buddy (e.g., expose them
--
mm/memory_hotplug.c-675- * __ffs() behaviour is undefined for 0. start == 0 is
mm/memory_hotplug.c:676: * MAX_PAGE_ORDER-aligned, Set order to MAX_PAGE_ORDER for
mm/memory_hotplug.c-677- * the case.
--
mm/memory_hotplug.c-679- if (pfn)
mm/memory_hotplug.c:680: order = min_t(int, MAX_PAGE_ORDER, __ffs(pfn));
mm/memory_hotplug.c-681- else
mm/memory_hotplug.c:682: order = MAX_PAGE_ORDER;
mm/memory_hotplug.c-683-
--
mm/mm_init.c=1586=static void __init alloc_node_mem_map(struct pglist_data *pgdat)
--
mm/mm_init.c-1597- /*
mm/mm_init.c:1598: * The zone's endpoints aren't required to be MAX_PAGE_ORDER
mm/mm_init.c-1599- * aligned but the node_mem_map endpoints must be in order
--
mm/mm_init.c=1915=static void __init deferred_free_pages(unsigned long pfn,
--
mm/mm_init.c-1929- if (nr_pages == MAX_ORDER_NR_PAGES && IS_MAX_ORDER_ALIGNED(pfn)) {
mm/mm_init.c:1930: __free_pages_core(page, MAX_PAGE_ORDER, MEMINIT_EARLY);
mm/mm_init.c-1931- return;
--
mm/mm_init.c-1933-
mm/mm_init.c:1934: /* Accept chunks smaller than MAX_PAGE_ORDER upfront */
mm/mm_init.c-1935- accept_memory(PFN_PHYS(pfn), nr_pages * PAGE_SIZE);
--
mm/mm_init.c=2307=void *__init alloc_large_system_hash(const char *tablename,
--
mm/mm_init.c-2377- SMP_CACHE_BYTES);
mm/mm_init.c:2378: } else if (get_order(size) > MAX_PAGE_ORDER || hashdist) {
mm/mm_init.c-2379- table = vmalloc_huge(size, gfp_flags);
--
mm/mm_init.c=2643=void __init mm_core_init(void)
--
mm/mm_init.c-2654- * page_ext requires contiguous pages,
mm/mm_init.c:2655: * bigger than MAX_PAGE_ORDER unless SPARSEMEM.
mm/mm_init.c-2656- */
--
mm/page_alloc.c=889=buddy_merge_likely(unsigned long pfn, unsigned long buddy_pfn,
--
mm/page_alloc.c-894-
mm/page_alloc.c:895: if (order >= MAX_PAGE_ORDER - 1)
mm/page_alloc.c-896- return false;
--
mm/page_alloc.c=940=static inline void __free_one_page(struct page *page,
--
mm/page_alloc.c-959-
mm/page_alloc.c:960: while (order < MAX_PAGE_ORDER) {
mm/page_alloc.c-961- int buddy_mt = migratetype;
--
mm/page_alloc.c=1600=void __meminit __free_pages_core(struct page *page, unsigned int order,
--
mm/page_alloc.c-1634- if (page_contains_unaccepted(page, order)) {
mm/page_alloc.c:1635: if (order == MAX_PAGE_ORDER && __free_unaccepted(page))
mm/page_alloc.c-1636- return;
--
mm/page_alloc.c-1664- * which contains a memory hole (i.e. there is no physical memory for a subset
mm/page_alloc.c:1665: * of the pfn range). For example, if the pageblock order is MAX_PAGE_ORDER, which
mm/page_alloc.c-1666- * will fall into 2 sub-sections, and the end pfn of the pageblock may be hole
--
mm/page_alloc.c=2055=static unsigned long find_large_buddy(unsigned long start_pfn)
--
mm/page_alloc.c-2062- */
mm/page_alloc.c:2063: int order = start_pfn ? __ffs(start_pfn) : MAX_PAGE_ORDER;
mm/page_alloc.c-2064- struct page *page;
--
mm/page_alloc.c-2068- /* Nothing found */
mm/page_alloc.c:2069: if (++order > MAX_PAGE_ORDER)
mm/page_alloc.c-2070- return start_pfn;
--
mm/page_alloc.c=2111=static bool __move_freepages_block_isolate(struct zone *zone,
--
mm/page_alloc.c-2128- /* No splits needed if buddies can't span multiple blocks */
mm/page_alloc.c:2129: if (pageblock_order == MAX_PAGE_ORDER)
mm/page_alloc.c-2130- goto move;
--
mm/page_alloc.c=2373=__rmqueue_claim(struct zone *zone, int order, int start_migratetype,
--
mm/page_alloc.c-2394- */
mm/page_alloc.c:2395: for (current_order = MAX_PAGE_ORDER; current_order >= min_order;
mm/page_alloc.c-2396- --current_order) {
--
mm/page_alloc.c=5330=static inline bool alloc_order_allowed(gfp_t gfp, unsigned int order,
--
mm/page_alloc.c-5339- */
mm/page_alloc.c:5340: return !(WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp));
mm/page_alloc.c-5341-}
--
mm/page_alloc.c=5599=static void *make_alloc_exact(unsigned long addr, unsigned int order,
--
mm/page_alloc.c-5626- *
mm/page_alloc.c:5627: * This function is also limited by MAX_PAGE_ORDER.
mm/page_alloc.c-5628- *
--
mm/page_alloc.c=6432=EXPORT_SYMBOL(adjust_managed_page_count);
--
mm/page_alloc.c-6442- * @page must be naturally aligned to the order and the order must not
mm/page_alloc.c:6443: * exceed MAX_PAGE_ORDER. All pages must be reserved.
mm/page_alloc.c-6444- */
mm/page_alloc.c=6445=void free_reserved_pages(struct page *page, unsigned int order)
--
mm/page_alloc.c-6450- VM_WARN_ON_ONCE(!IS_ALIGNED(page_to_pfn(page), nr_pages));
mm/page_alloc.c:6451: VM_WARN_ON_ONCE(order > MAX_PAGE_ORDER);
mm/page_alloc.c-6452-
--
mm/page_alloc.c=7021=static void free_prepared_contig_range(struct page *page,
--
mm/page_alloc.c-7029- /* We are limited by the largest buddy order. */
mm/page_alloc.c:7030: order = pfn ? __ffs(pfn) : MAX_PAGE_ORDER;
mm/page_alloc.c-7031- /* Don't exceed the number of pages to free. */
mm/page_alloc.c-7032- order = min_t(unsigned int, order, ilog2(nr_pages));
mm/page_alloc.c:7033: order = min_t(unsigned int, order, MAX_PAGE_ORDER);
mm/page_alloc.c-7034-
--
mm/page_alloc.c=7283=int alloc_contig_frozen_range_noprof(unsigned long start, unsigned long end,
--
mm/page_alloc.c-7305- * In contrast to the buddy, we allow for orders here that exceed
mm/page_alloc.c:7306: * MAX_PAGE_ORDER, so we must manually make sure that we are not
mm/page_alloc.c-7307- * exceeding the maximum folio order.
--
mm/page_alloc.c=7769=bool is_free_buddy_page(const struct page *page)
--
mm/page_alloc.c-7781-
mm/page_alloc.c:7782: return order <= MAX_PAGE_ORDER;
mm/page_alloc.c-7783-}
--
mm/page_alloc.c=7915=static void __accept_page(struct zone *zone, unsigned long *flags,
--
mm/page_alloc.c-7923-
mm/page_alloc.c:7924: accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
mm/page_alloc.c-7925-
mm/page_alloc.c:7926: __free_pages_ok(page, MAX_PAGE_ORDER, FPI_TO_TAIL);
mm/page_alloc.c-7927-}
--
mm/page_alloc.h=138=static inline bool page_is_buddy(struct page *page, struct page *buddy,
--
mm/page_alloc.h-173- *
mm/page_alloc.h:174: * Assumption: *_mem_map is contiguous at least up to MAX_PAGE_ORDER
mm/page_alloc.h-175- */
--
mm/page_isolation.c=223=static void unset_migratetype_isolate(struct page *page)
--
mm/page_isolation.c-244- order = buddy_order(page);
mm/page_isolation.c:245: if (order >= pageblock_order && order < MAX_PAGE_ORDER) {
mm/page_isolation.c-246- buddy = find_buddy_page_pfn(page, page_to_pfn(page),
--
mm/page_isolation.c=284=__first_valid_page(unsigned long pfn, unsigned long nr_pages)
--
mm/page_isolation.c-307- *
mm/page_isolation.c:308: * Free and in-use pages can be as big as MAX_PAGE_ORDER and contain more than one
mm/page_isolation.c-309- * pageblock. When not all pageblocks within a page are isolated at the same
mm/page_isolation.c-310- * time, free page accounting can go wrong. For example, in the case of
mm/page_isolation.c:311: * MAX_PAGE_ORDER = pageblock_order + 1, a MAX_PAGE_ORDER page has two
mm/page_isolation.c-312- * pageblocks.
mm/page_isolation.c:313: * [ MAX_PAGE_ORDER ]
mm/page_isolation.c-314- * [ pageblock0 | pageblock1 ]
--
mm/page_isolation.c=605=int test_pages_isolated(unsigned long start_pfn, unsigned long end_pfn,
--
mm/page_isolation.c-623- /*
mm/page_isolation.c:624: * Note: pageblock_nr_pages != MAX_PAGE_ORDER. Then, chunks of free
mm/page_isolation.c-625- * pages are not aligned to pageblock_nr_pages.
--
mm/page_owner.c=458=static inline bool skip_buddy_pages(unsigned long *pfn, struct page *page)
--
mm/page_owner.c-465- order = buddy_order_unsafe(page);
mm/page_owner.c:466: if (order <= MAX_PAGE_ORDER) {
mm/page_owner.c-467- unsigned long new_pfn = *pfn + (1UL << order);
--
mm/page_reporting.c=18=static int page_order_update_notify(const char *val, const struct kernel_param *kp)
--
mm/page_reporting.c-23- */
mm/page_reporting.c:24: return param_set_uint_minmax(val, kp, 0, MAX_PAGE_ORDER);
mm/page_reporting.c-25-}
--
mm/page_reporting.c=360=int page_reporting_register(struct page_reporting_dev_info *prdev)
--
mm/page_reporting.c-381- if (prdev->order != PAGE_REPORTING_ORDER_UNSPECIFIED &&
mm/page_reporting.c:382: prdev->order <= MAX_PAGE_ORDER)
mm/page_reporting.c-383- page_reporting_order = prdev->order;
--
mm/shuffle.h-8-
mm/shuffle.h:9:#define SHUFFLE_ORDER MAX_PAGE_ORDER
mm/shuffle.h-10-
--
mm/slub.c=7608=static inline int calculate_order(unsigned int size)
--
mm/slub.c-7665- order = get_order(size);
mm/slub.c:7666: if (order <= MAX_PAGE_ORDER)
mm/slub.c-7667- return order;
--
mm/slub.c=8248=static int __init setup_slub_max_order(const char *str, const struct kernel_param *kp)
--
mm/slub.c-8255-
mm/slub.c:8256: slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
mm/slub.c-8257-
--
mm/vmalloc.c=3668=vm_area_alloc_pages(gfp_t gfp, int nid,
--
mm/vmalloc.c-3672- unsigned long nr_remaining = nr_pages;
mm/vmalloc.c:3673: unsigned int max_attempt_order = MAX_PAGE_ORDER;
mm/vmalloc.c-3674- struct page *page;
--
mm/vmscan.c=6769=unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
--
mm/vmscan.c-6788- */
mm/vmscan.c:6789: BUILD_BUG_ON(MAX_PAGE_ORDER >= S8_MAX);
mm/vmscan.c-6790- BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
--
mm/vmstat.c=1114=static int __fragmentation_index(unsigned int order, struct contig_page_info *info)
--
mm/vmstat.c-1117-
mm/vmstat.c:1118: if (WARN_ON_ONCE(order > MAX_PAGE_ORDER))
mm/vmstat.c-1119- return 0;
]
|
| 537/6 |
2026/09/09 18:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 57031
output: 23
thoughts: 1548
Thoughts: **Analyzing Size Limits in Kernel Memory Allocation**
Okay, let's break this down. My initial thought was to quickly confirm the maximum allocatable size based on `mm/page_alloc.c`. I checked the `WARN_ON_ONCE_GFP` calls within `alloc_pages`, and it's clear the `order` parameter is constrained by `MAX_PAGE_ORDER`. So, `alloc_pages` can only handle sizes up to `PAGE_SIZE << MAX_PAGE_ORDER`. The minimum is, of course, `PAGE_SIZE`. Now I am confirming that `sg_build_indirect` confirms this limitation, so that the limits of `PAGE_SIZE << MAX_PAGE_ORDER` is the correct maximum size.
Now to the heart of the matter – the question about `scatter_elem_sz_set()`. The core of the problem is how to properly handle negative `size` values when comparing against `PAGE_SIZE` and the maximum allocation size.
The type of `PAGE_SIZE` is `unsigned long`. With a signed `int` for `size`, the compiler performs usual arithmetic conversions, meaning the comparison is between a signed `int` and an `unsigned long`. The negative value turns into `ULONG_MAX`. This makes the comparison `size < PAGE_SIZE` FALSE, because `ULONG_MAX` is definitely not less than `PAGE_SIZE`. However, the question says, if `size` is negative, then `size > (PAGE_SIZE << MAX_PAGE_ORDER)` IS TRUE by accident.
However, relying on this behavior is a terrible idea! Firstly, it generates compiler warnings, specifically `-Wsign-compare`, and that needs to be addressed. Second, it's semantically wrong. The intent is to catch values smaller than `PAGE_SIZE`, but it's only happening by a lucky accident.
I need to find a cleaner solution to handle the case of negative `size` values and get rid of the compiler warning.
I considered explicitly checking for negative values using `size < 0` or performing the casts correctly using something like `size < (int)PAGE_SIZE`. I thought about the possibility of `PAGE_SIZE` or `(PAGE_SIZE << MAX_PAGE_ORDER)` overflowing if cast to an `int`, but on most systems, this is not a concern, because `PAGE_SIZE << MAX_PAGE_ORDER` is, for the usual values, well within the `INT_MAX` limit.
I thought about checking `size < 0` FIRST, but then the compiler will still give `-Wsign-compare` due to the static type-checking of the comparison.
So, I need to see what the kernel already does! I will now grep for `PAGE_SIZE << MAX_PAGE_ORDER` and look at the surrounding code to understand how this is handled in practice.
|
| 538/6 |
2026/09/09 18:29 |
tool |
grepper |
0m
Args: map[Expression:PAGE_SIZE << MAX_PAGE_ORDER]
Results: map[Output:Documentation/networking/packet_mmap.rst=268=More precisely the limit can be calculated as::
Documentation/networking/packet_mmap.rst-269-
Documentation/networking/packet_mmap.rst:270: PAGE_SIZE << MAX_PAGE_ORDER
Documentation/networking/packet_mmap.rst-271-
--
arch/sparc/mm/tsb.c=396=void tsb_grow(struct mm_struct *mm, unsigned long tsb_index, unsigned long rss)
--
arch/sparc/mm/tsb.c-404-
arch/sparc/mm/tsb.c:405: if (max_tsb_size > PAGE_SIZE << MAX_PAGE_ORDER)
arch/sparc/mm/tsb.c:406: max_tsb_size = PAGE_SIZE << MAX_PAGE_ORDER;
arch/sparc/mm/tsb.c-407-
--
drivers/base/regmap/regmap-debugfs.c=216=static ssize_t regmap_read_debugfs(struct regmap *map, unsigned int from,
--
drivers/base/regmap/regmap-debugfs.c-229-
drivers/base/regmap/regmap-debugfs.c:230: if (count > (PAGE_SIZE << MAX_PAGE_ORDER))
drivers/base/regmap/regmap-debugfs.c:231: count = PAGE_SIZE << MAX_PAGE_ORDER;
drivers/base/regmap/regmap-debugfs.c-232-
--
drivers/base/regmap/regmap-debugfs.c=361=static ssize_t regmap_reg_ranges_read_file(struct file *file,
--
drivers/base/regmap/regmap-debugfs.c-376-
drivers/base/regmap/regmap-debugfs.c:377: if (count > (PAGE_SIZE << MAX_PAGE_ORDER))
drivers/base/regmap/regmap-debugfs.c:378: count = PAGE_SIZE << MAX_PAGE_ORDER;
drivers/base/regmap/regmap-debugfs.c-379-
--
drivers/infiniband/hw/irdma/hw.c=1497=static int irdma_create_aeq(struct irdma_pci_f *rf)
--
drivers/infiniband/hw/irdma/hw.c-1511- if (rf->rdma_ver >= IRDMA_GEN_3)
drivers/infiniband/hw/irdma/hw.c:1512: aeq_size = min(aeq_size, (u32)((PAGE_SIZE << MAX_PAGE_ORDER) /
drivers/infiniband/hw/irdma/hw.c-1513- sizeof(struct irdma_sc_aeqe)));
--
drivers/net/ethernet/amd/pds_core/core.h-26-
drivers/net/ethernet/amd/pds_core/core.h:27:/* Use fixed 4MB instead of PAGE_SIZE << MAX_PAGE_ORDER to avoid
drivers/net/ethernet/amd/pds_core/core.h-28- * cpu_to_le32() truncation on large-page configs
--
kernel/events/ring_buffer.c=684=int rb_alloc_aux(struct perf_buffer *rb, struct perf_event *event,
--
kernel/events/ring_buffer.c-733- * kcalloc_node() is unable to allocate buffer if the size is larger
kernel/events/ring_buffer.c:734: * than: PAGE_SIZE << MAX_PAGE_ORDER; directly bail out in this case.
kernel/events/ring_buffer.c-735- */
--
lib/test_kho.c-29-
lib/test_kho.c:30:static long max_mem = (PAGE_SIZE << MAX_PAGE_ORDER) * 2;
lib/test_kho.c-31-module_param(max_mem, long, 0644);
--
mm/page_alloc.c=7915=static void __accept_page(struct zone *zone, unsigned long *flags,
--
mm/page_alloc.c-7923-
mm/page_alloc.c:7924: accept_memory(page_to_phys(page), PAGE_SIZE << MAX_PAGE_ORDER);
mm/page_alloc.c-7925-
--
net/smc/smc_core.c=2427=static int __smc_buf_create(struct smc_sock *smc, bool is_smcd, bool is_rmb)
--
net/smc/smc_core.c-2445- if (!is_smcd && lgr->buf_type == SMCR_PHYS_CONT_BUFS)
net/smc/smc_core.c:2446: bufsize = min_t(int, bufsize, PAGE_SIZE << MAX_PAGE_ORDER);
net/smc/smc_core.c-2447-
--
tools/testing/vsock/vsock_test.c=1746=static void test_stream_msgzcopy_leak_zcskb_client(const struct test_opts *opts)
--
tools/testing/vsock/vsock_test.c-1776- ctl_len = optmem_max - 1;
tools/testing/vsock/vsock_test.c:1777: if (ctl_len > PAGE_SIZE << MAX_PAGE_ORDER) {
tools/testing/vsock/vsock_test.c-1778- fprintf(stderr, "Try with net.core.optmem_max = 100000\n");
]
|
| 539/6 |
2026/09/09 18:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 60663
output: 29
thoughts: 2765
Thoughts: **Analyzing `scatter_elem_sz_set` for Robustness and Clarity**
Okay, so I'm diving into the `scatter_elem_sz_set` function and I need to make sure the range check is solid. I was looking at how `bufsize` is handled and also how `def_reserved_size_set` handles similar inputs to determine proper bounds checking. I'm focusing on the condition: `if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))`. The key question is: does this work correctly if a negative value is entered, given that `size` is an integer?
My initial thought was that integer promotion would handle negative numbers, but I have to really think this through. And I noticed a potential problem in that comparison, because while `size` is a signed int, `PAGE_SIZE` is an `unsigned long`. I recall seeing that in `net/smc/smc_core.c` there's a min check as well.
Let's break down what happens when `size` is negative and compared with `PAGE_SIZE`. Because of integer promotion, `size` gets converted to an `unsigned long`. If `size` is -1, this becomes a very large positive number on a 64-bit system, which is way *bigger* than `PAGE_SIZE`. This means the intended check on the minimum size is completely bypassed. If the input is `-1`, then `-1 < PAGE_SIZE` evaluates to `false`. However, the second part of the check `-1 > (PAGE_SIZE << MAX_PAGE_ORDER)` may actually evaluate to `true` (and trigger a negative number range check), which would be an unintended result. I also realized that relying on this is just a recipe for confusion.
A bigger issue is that this comparison between signed and unsigned types triggers a compiler warning (`-Wsign-compare`). So I need to find a solution that's both correct and clean. I can't just ignore the warning. I know it's there for a reason, right?
I started thinking about ways to rewrite the check. Should I cast `PAGE_SIZE` to `int`? What about casting `size`? Should I check `size < 0` first? But that still leads to a potential `-Wsign-compare` warning if I then compare with the unsigned `PAGE_SIZE`.
I thought about the design of `def_reserved_size_set` and noticed the usage of `kstrtoint`. The size there is an int too, and there's a check for negative numbers. I also thought about using `kstrtouint`, but that is less applicable here since we need to cover the case of negative numbers.
So, here's the approach I think is best: I'll explicitly cast `PAGE_SIZE` and `(PAGE_SIZE << MAX_PAGE_ORDER)` to `int`. This avoids the signed/unsigned comparison issue, and it's safe. Since page sizes are always positive and within reasonable limits, casting to `int` is okay. Even with the maximum shift order, this fits within an int.
So, the preferred code will be: `if (size < (int)PAGE_SIZE || size > (int)(PAGE_SIZE << MAX_PAGE_ORDER))` No warnings, and negative numbers will hit the first check to be rejected. This explicitly deals with the potential for negative values and avoids the tricky behavior of unsigned comparisons. I can also do `if (size < 0 || size < (int)PAGE_SIZE || ...)`, but the former already takes care of the edge case of negative numbers. This is clean, safe, and avoids compiler warnings. I want to make sure I'm writing robust code that is easy for someone else to understand, and this approach hits that target.
|
| 540/6 |
2026/09/09 18:29 |
tool |
grepper |
0m
Args: map[Expression:module_param_cb PathPrefix:drivers/scsi]
Results: map[Output:drivers/scsi/sg.c=1646=static const struct kernel_param_ops def_reserved_size_ops = {
--
drivers/scsi/sg.c-1650-
drivers/scsi/sg.c:1651:module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
drivers/scsi/sg.c-1652- S_IRUGO | S_IWUSR);
]
|
| 541/6 |
2026/09/09 18:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 64405
output: 28
thoughts: 18
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating `module_param_cb` Usage**
Okay, so I'm thinking, let's dive into how `module_param_cb` is being used across other drivers in the kernel. I need to get a broader understanding of its common patterns and any potential edge cases or interesting implementations. We all know the basics, but I'm looking for subtle nuances, perhaps clever uses, or areas where someone might be employing it in a way that’s… well, unorthodox. Understanding these patterns is key to assessing how the tool is supposed to be used. I’ll be paying close attention to things like the callback function's signature, what it's *actually* doing inside, and whether there are any potential race conditions or locking issues that I can spot quickly by reading the code. This will help me assess the tool more broadly. I'm also looking for the "gotchas" – the common mistakes or pitfalls that developers might run into when using it. The goal is a comprehensive understanding of how `module_param_cb` fits into the overall driver landscape, and to see if I am missing something obvious that my own work might have missed.
|
| 542/6 |
2026/09/09 18:29 |
tool |
grepper |
0m
Args: map[Expression:module_param_cb PathPrefix:drivers/block]
Results: map[Output:drivers/block/loop.c=1833=static const struct kernel_param_ops max_loop_param_ops = {
--
drivers/block/loop.c-1837-
drivers/block/loop.c:1838:module_param_cb(max_loop, &max_loop_param_ops, &max_loop, 0444);
drivers/block/loop.c-1839-MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
--
drivers/block/rnbd/rnbd-srv.c=53=static const struct kernel_param_ops dev_search_path_ops = {
--
drivers/block/rnbd/rnbd-srv.c-57-
drivers/block/rnbd/rnbd-srv.c:58:module_param_cb(dev_search_path, &dev_search_path_ops,
drivers/block/rnbd/rnbd-srv.c-59- &dev_search_path_kparam_str, 0444);
--
drivers/block/ublk_drv.c=5957=static const struct kernel_param_ops ublk_max_unprivileged_ublks_ops = {
--
drivers/block/ublk_drv.c-5961-
drivers/block/ublk_drv.c:5962:module_param_cb(ublks_max, &ublk_max_unprivileged_ublks_ops,
drivers/block/ublk_drv.c-5963- &unprivileged_ublks_max, 0644);
]
|
| 543/6 |
2026/09/09 18:29 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 61740
output: 1397
thoughts: 3599
Thoughts: **Analysis of sg Driver Code: A Deep Dive**
Okay, let's process this meticulously, keeping in mind the restrictions on tool use. We have three specific areas of the `sg` driver's code to evaluate, and I must ensure accuracy and consider the nuances of kernel coding practices.
**Question 1: `scatter_elem_sz_set()` - Handling Negative Input**
My primary concern here is the safe and efficient handling of potential negative values for the `size` parameter. The critical issue is the implicit type conversion when comparing a signed `int` (`size`) with an `unsigned long` (`PAGE_SIZE`). This leads to incorrect results if `-1` is passed, because `-1` is promoted to the very large value `ULONG_MAX`, incorrectly evaluating the lower-bound check. This would then falsely report a value outside of the valid bounds.
The cleanest and most robust solution, and the best way to avoid compiler warnings is to cast either `PAGE_SIZE` and `PAGE_SIZE << MAX_PAGE_ORDER` to `int`, or to check `size < 0` first. Since the maximum allowed value, `PAGE_SIZE << MAX_PAGE_ORDER` is small enough to fit within an `int`, casting is perfectly safe. Therefore, I'd prefer Option A:
```c
if (size < (int)PAGE_SIZE || size > (int)(PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
```
This addresses two fundamental issues: it correctly handles negative numbers, and it eliminates the `-Wsign-compare` compiler warning. This approach ensures correct behavior and maintains code quality.
**Question 2: `sg_build_indirect()` - Simplifying the Logic**
The core of this question revolves around the elimination of `scatter_elem_sz_prev`. This variable was initially necessary due to the lack of validation for `scatter_elem_sz` (which was a module parameter that could be changed at runtime). Given the existence of `scatter_elem_sz_set()`, it guarantees that the value of `scatter_elem_sz` is within the valid range and validated by a `.set` callback. Therefore, it is now safe to refactor the loop, because the previous value is no longer necessary.
Now, we can get rid of all the extra checks:
```c
order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
}
```
This streamlined code leverages `min(rem_sz, ret_sz)` (or a similar construct) for logging, reflecting the actual data transferred within each allocation. This maintains the informational content of the debug messages. The loop is now cleaner, simpler, and more efficient.
**Question 3: `init_sg()` - Ensuring Minimum `PAGE_SIZE`**
The crucial aspect of `init_sg()` lies in ensuring that `scatter_elem_sz` is initialized to at least `PAGE_SIZE`. This is essential because, on some architectures, the default value of `SG_SCATTER_SZ` (32KB), could be smaller than the system's `PAGE_SIZE`. The removal of `scatter_elem_sz_prev` simplifies this even further.
Thus, the most concise and direct approach is:
```c
if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
```
This efficiently enforces the minimum size constraint, removing the unnecessary `scatter_elem_sz_prev = scatter_elem_sz;` assignment, which is no longer needed. This modification ensures correct initialization and behavior, regardless of the system's `PAGE_SIZE`.
|
| 544/4 |
2026/09/09 18:29 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 50154
output: 33
thoughts: 7227
Thoughts: **Refactoring the Scatter/Gather Element Size in the SCSI Driver**
Okay, so I've been carefully reviewing this code related to the scatter/gather element size (`scatter_elem_sz`) in the SCSI driver and thinking through the rationale behind these changes. My primary goal is to tighten up the validation, eliminate potential data races, and simplify the logic.
First, I examined the `scatter_elem_sz_set()` function. The old version had a somewhat convoluted check. My key insight was that by validating the size within the `scatter_elem_sz_set` function using `size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)` we can ensure that `scatter_elem_sz` always falls within a valid range. This means the check handles negative values, small values (below page size), and values too large which will all be rejected by the validation. Then, I leveraged `module_param_cb` and a custom `.set` callback, essentially enforcing that validation at the sysfs boundary. This approach, as the maintainer emphasized, avoids the anti-pattern of relying on signed/unsigned conversions to "work around" comparisons.
Next, I turned my attention to the `scatter_elem_sz_prev` variable, a global variable used for dynamic adjustment of `scatter_elem_sz` inside `sg_build_indirect()`. This part was the core of my refactoring. I saw that `scatter_elem_sz_prev` was only used for a comparison check and in a case where we were adjusting `scatter_elem_sz` when allocating large elements. The maintainer had commented that the dynamic adjustment introduced concurrency issues. By ensuring that the module parameter always falls within the valid range, we can remove `scatter_elem_sz_prev`.
Within `sg_build_indirect()`, the crucial change was simplifying the allocation loop. Originally, it adjusted `scatter_elem_sz` at runtime, which made the logic complex and prone to errors. With the sysfs validation in place, I was able to remove this logic and replace the calculations with `num = min(rem_sz, ret_sz);` making the code easier to understand and more efficient.
Finally, I confirmed that the boot parameter passing is protected by the `scatter_elem_sz_set()` so that we can reject invalid parameters upon boot and revert to default values. I also made sure that the module description was updated as well.
With this, I've eliminated a global variable used for synchronization, simplified the allocation logic, and made the code more robust and easier to maintain. This refactoring aligns perfectly with the maintainer's feedback, focusing on early validation and eliminating runtime data races.
|
| 545/4 |
2026/09/09 18:30 |
tool |
grepper |
0m
Error:
Args: map[Expression:MAX_PAGE_ORDER PathPrefix:drivers/scsi/sg.c]
Results:
|
| 546/4 |
2026/09/09 18:30 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 57997
output: 29
thoughts: 17
Thoughts: **Locating the Definition of MAX_PAGE_ORDER**
Okay, first things first, I need to pinpoint the definition of `MAX_PAGE_ORDER`. This constant is clearly important, so I'll start by checking the typical header files. Given my familiarity with the codebase, I'll begin with the headers most likely to contain system-level or platform-specific definitions. My initial guess would be something like a general configuration header, a memory management header, or potentially even a kernel-specific header, depending on the scope of `MAX_PAGE_ORDER`. I'll need to use my usual tools to quickly search and verify where this constant resides. It's time to dig in and find its location.
|
| 547/4 |
2026/09/09 18:30 |
tool |
grepper |
0m
Args: map[Expression:#define MAX_PAGE_ORDER PathPrefix:include/]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
]
|
| 548/4 |
2026/09/09 18:30 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 58304
output: 35
thoughts: 78
Thoughts: **Investigating the Dependency of sg.c on MAX_PAGE_ORDER**
Okay, so I need to figure out how `drivers/scsi/sg.c` is getting access to `MAX_PAGE_ORDER`. I know that `MAX_PAGE_ORDER` is defined in `include/linux/mmzone.h`. My immediate thought is to check if `sg.c` directly includes `mmzone.h`, or if it's being brought in transitively through some other header file. This is a common situation with kernel code, so a quick check of the `#include` directives at the beginning of `sg.c` should clear things up quickly. I'll focus on the first few lines of the file to see if `mmzone.h` is present. No need to overcomplicate this; let's start with a direct inspection and see what we find.
|
| 549/4 |
2026/09/09 18:30 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:50 LineCount:40]
Results: map[Contents: 50: #include <linux/cred.h> /* for sg_check_file_access() */
51:
52: #include <scsi/scsi.h>
53: #include <scsi/scsi_cmnd.h>
54: #include <scsi/scsi_dbg.h>
55: #include <scsi/scsi_device.h>
56: #include <scsi/scsi_driver.h>
57: #include <scsi/scsi_eh.h>
58: #include <scsi/scsi_host.h>
59: #include <scsi/scsi_ioctl.h>
60: #include <scsi/scsi_tcq.h>
61: #include <scsi/sg.h>
62:
63: #include "scsi_logging.h"
64:
65: #ifdef CONFIG_SCSI_PROC_FS
66: #include <linux/proc_fs.h>
67: static char *sg_version_date = "20140603";
68:
69: static int sg_proc_init(void);
70: #endif
71:
72: #define SG_ALLOW_DIO_DEF 0
73:
74: #define SG_MAX_DEVS (1 << MINORBITS)
75:
76: /* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type
77: * of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater
78: * than 16 bytes are "variable length" whose length is a multiple of 4
79: */
80: #define SG_MAX_CDB_SIZE 252
81:
82: #define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
83:
84: /* N.B. This variable is readable and writeable via
85: * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
86: * of this size (or less if there is not enough memory) will be reserved
87: * for use by this file descriptor.
88: */
89:
]
|
| 550/4 |
2026/09/09 18:30 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 59273
output: 34
thoughts: 25
Thoughts: Okay, here's my take on those lines of `drivers/scsi/sg.c`:
**Analyzing `drivers/scsi/sg.c` (Lines 1-50)**
Alright, so I'm diving into the SCSI Generic driver code again. Let's see what's happening at the very beginning of `sg.c`, specifically the first fifty lines. Immediately, I'm expecting to see the standard include directives and likely some license information, like the GPL header. It's almost guaranteed to include the necessary kernel headers related to SCSI, block devices, and potentially some device-specific stuff. I'm looking for the standard structures and function prototypes that define the core of the driver; the structures like `scsi_device`, `scsi_cmnd`, and maybe some `sg_io_hdr` or similar structures related to the generic SCSI interface. Knowing the include files will give me a better understanding of how the code interacts with other parts of the SCSI subsystem, the block layer, and, potentially, user space. I'm also glancing at the initial comments to get a feel for the author's intention and the module's general purpose. I'll make a mental note of any early function declarations or global variables that stand out, as these are likely crucial for the overall driver architecture. It's a quick skim for context; the initial lines will set the stage.
|
| 551/4 |
2026/09/09 18:30 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1 LineCount:50]
Results: map[Contents: 1: // SPDX-License-Identifier: GPL-2.0-or-later
2: /*
3: * History:
4: * Started: Aug 9 by Lawrence Foard (entropy@world.std.com),
5: * to allow user process control of SCSI devices.
6: * Development Sponsored by Killy Corp. NY NY
7: *
8: * Original driver (sg.c):
9: * Copyright (C) 1992 Lawrence Foard
10: * Version 2 and 3 extensions to driver:
11: * Copyright (C) 1998 - 2014 Douglas Gilbert
12: */
13:
14: static int sg_version_num = 30536; /* 2 digits for each component */
15: #define SG_VERSION_STR "3.5.36"
16:
17: /*
18: * D. P. Gilbert (dgilbert@interlog.com), notes:
19: * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
20: * the kernel/module needs to be built with CONFIG_SCSI_LOGGING
21: * (otherwise the macros compile to empty statements).
22: *
23: */
24: #include <linux/module.h>
25:
26: #include <linux/fs.h>
27: #include <linux/kernel.h>
28: #include <linux/sched.h>
29: #include <linux/string.h>
30: #include <linux/mm.h>
31: #include <linux/errno.h>
32: #include <linux/mtio.h>
33: #include <linux/ioctl.h>
34: #include <linux/major.h>
35: #include <linux/slab.h>
36: #include <linux/fcntl.h>
37: #include <linux/init.h>
38: #include <linux/poll.h>
39: #include <linux/moduleparam.h>
40: #include <linux/cdev.h>
41: #include <linux/idr.h>
42: #include <linux/seq_file.h>
43: #include <linux/blkdev.h>
44: #include <linux/delay.h>
45: #include <linux/blktrace_api.h>
46: #include <linux/mutex.h>
47: #include <linux/atomic.h>
48: #include <linux/ratelimit.h>
49: #include <linux/uio.h>
50: #include <linux/cred.h> /* for sg_check_file_access() */
]
|
| 552/4 |
2026/09/09 18:30 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 60414
output: 31
thoughts: 54
Thoughts: **Examining the Memory Management Headers**
Okay, so I'm diving into this code and the very first thing that jumps out is the `#include <linux/mm.h>` on line 30. That's a good sign; it's the core memory management header for Linux. Now, I need to understand the relationship it has to other crucial memory structures. Specifically, I'm betting that `linux/mmzone.h` is either directly or indirectly included by `mm.h`. Given my experience, it's almost certain it's involved in some way. Time to quickly pull up the definition of `linux/mm.h` and confirm whether it contains the inclusion directive of `mmzone.h` or, if not directly, the definitions within it rely on definitions from `mmzone.h`. I'll focus on the preprocessor directives, or perhaps a chain of include files to trace the dependency. I need to be sure; memory zones are fundamental.
|
| 553/4 |
2026/09/09 18:30 |
tool |
grepper |
0m
Args: map[Expression:mmzone.h PathPrefix:include/linux/mm.h]
Results: map[Output:include/linux/mm.h-11-#include <linux/list.h>
include/linux/mm.h:12:#include <linux/mmzone.h>
include/linux/mm.h-13-#include <linux/rbtree.h>
]
|
| 554/4 |
2026/09/09 18:30 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 60779
output: 35
thoughts: 5746
Thoughts: **Analysis of `scatter_elem_sz_set` and Related Code**
Okay, so I've been diving deep into the `linux/mm.h` include and how `MAX_PAGE_ORDER` plays into this. I see that `linux/mm.h` includes `linux/mmzone.h` on line 12, so the definition of `MAX_PAGE_ORDER` is already available, which is good. That eliminates the need for any new header includes within `drivers/scsi/sg.c`, specifically for this context.
Now, checking for potential integer overflows when calculating `PAGE_SIZE << MAX_PAGE_ORDER` is important. Given `PAGE_SHIFT` (typically 12, 14, or 16) and `MAX_PAGE_ORDER` (usually 10, up to 13 on some architectures), the maximum shift sum would be 16 + 13 = 29. `1UL << 29` results in 512MB, which fits comfortably within the bounds of both `int` and `unsigned int`, even on x86_64 where it is typically 4MB.
I'm focused on the `scatter_elem_sz_set` function and its input validation. The core question is, how do we correctly handle and validate the size parameter? Considering that if the input is a negative value like `"-1"`, `kstrtoint` parses it correctly, resulting in a signed integer that will require a comparison with `unsigned long` when using `< PAGE_SIZE`.
I recall that if this code were compiled with the `-Wsign-compare` flag, a warning would be generated due to the signed/unsigned comparison when the integer `size` is compared to `PAGE_SIZE`, as they have differing signedness. This warning highlights the importance of choosing the correct data type for `size` to avoid unexpected behavior.
An alternative is to use `unsigned int size` with `kstrtouint`, which avoids the sign comparison issue and correctly handles the parameter conversion and validation. However, if the code were modified such that we're using `unsigned int`, negative input values provided to `kstrtouint` will be rejected by returning -`EINVAL`.
Let's also look at using `param_set_uint_minmax`. It uses `kstrtouint` to convert the string value to an unsigned integer, and then checks if the resulting integer falls within a specified min/max range. This function is useful for validating the scatter element size to ensure it aligns with the expected bounds. In this case, `param_set_uint_minmax` would also return `-EINVAL` for any negative input, as `kstrtouint` does.
Based on the maintainer's feedback, the code should validate that `scatter_elem_sz` is within the range `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]` using either a custom `.set` callback or `param_set_uint_minmax` to return `-EINVAL` or `-ERANGE` for invalid input. The wording of the feedback emphasizes the importance of returning either `-EINVAL` or `-ERANGE`. `param_set_uint_minmax` would return `-EINVAL` if the user enters a negative value or invalid string. A custom set callback gives the flexibility to specify the return value.
Now, let's circle back to what codeexpert suggested. Codeexpert's "Option 1" appears to align well with existing SCSI/sg conventions. However, let's explore this approach and its implications in relation to signed and unsigned integer comparisons.
Using `int size`, with `kstrtoint` and a comparison such as `size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)` with `-1`. When the input value is `-1`, then the first condition will evaluate to `false` and the second condition will evaluate to `true`. And in C, the result is well-defined. The current logic that we are reviewing with `int size` is correct in preventing the parameter from taking any value less than `PAGE_SIZE`, including negative values.
I've also checked `def_reserved_size_set` in `sg.c`, where both `kstrtoint` and range checks are used, and this is another example of validation that aligns with the intention of parameter validation. The key here is that the lower bound in `scatter_elem_sz` is `PAGE_SIZE`, whereas it's `0` for `def_reserved_size`. This explains why there's an explicit check for `size < 0` in `def_reserved_size_set`, and only `size < PAGE_SIZE` is required in the `scatter_elem
|
| 555/4 |
2026/09/09 18:31 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:90 LineCount:25]
Results: map[Contents: 90: /* picks up init parameter */
91: static int def_reserved_size = SG_DEF_RESERVED_SIZE;
92: static int sg_allow_dio = SG_ALLOW_DIO_DEF;
93:
94: static int scatter_elem_sz = SG_SCATTER_SZ;
95: static int scatter_elem_sz_prev = SG_SCATTER_SZ;
96:
97: #define SG_SECTOR_SZ 512
98:
99: static int sg_add_device(struct device *);
100: static void sg_remove_device(struct device *);
101:
102: static DEFINE_IDR(sg_index_idr);
103: static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
104: file descriptor list for device */
105:
106: static struct class_interface sg_interface = {
107: .add_dev = sg_add_device,
108: .remove_dev = sg_remove_device,
109: };
110:
111: typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
112: unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */
113: unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
114: unsigned bufflen; /* Size of (aggregate) data buffer */
]
|
| 556/4 |
2026/09/09 18:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 68011
output: 37
thoughts: 64
Thoughts: **Analyzing the Impact of a Code Removal**
Okay, so I just ripped out line 95, the one that sets `scatter_elem_sz_prev`. It looks like it's a bit of initialization, probably related to scatter/gather lists within the SCSI subsystem. Now, the real question is: what's the fallout? I need to understand what this variable was used for, and if removing its initialization will cause any regressions. To do this properly, I'm going to jump into `drivers/scsi/sg.c`, specifically lines 1620 through 1675. This is where the core logic of the scatter/gather code is, and it's highly likely that `scatter_elem_sz_prev`, or something that depends on it, will be in there. Time to see if I broke anything. I need to understand how the code handles scatter/gather element sizes now, with this initialization removed. Let's dig in.
|
| 557/4 |
2026/09/09 18:31 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1620 LineCount:55]
Results: map[Contents:1620:
1621: kref_put(&sdp->d_ref, sg_device_destroy);
1622: }
1623:
1624: module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
1655: MODULE_DESCRIPTION("SCSI generic (sg) driver");
1656: MODULE_LICENSE("GPL");
1657: MODULE_VERSION(SG_VERSION_STR);
1658: MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
1659:
1660: MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
1662: MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1663: MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
1664:
1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
]
|
| 558/4 |
2026/09/09 18:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 69169
output: 37
thoughts: 505
Thoughts: **Refining the Scatter/Gather Element Size Parameter**
Okay, let's dive into this `scatter_elem_sz` parameter in the `sg` module. I see in lines 1660-1661 of the code, it's described as the scatter-gather element size, defaulting to the maximum of `SG_SCATTER_SZ` and `PAGE_SIZE`. The next few lines include a check and a correction, line 1670: if `scatter_elem_sz` is less than `PAGE_SIZE`, it's forced to be `PAGE_SIZE`. This seems reasonable, as we wouldn't want it smaller than a page.
Looking at lines 1624-1626, we see the parameter is defined using `module_param_named`. I'm thinking we can tighten up the validation and control here. Instead of relying solely on the implicit clamping within the `init_sg()` function (and the earlier check), I'm going to replace the simple `module_param_named` with a callback-based approach.
I'll define a custom `scatter_elem_sz_set` function. This will give me fine-grained control over how the parameter value is set. Inside, I'll parse the input string using `kstrtoint` and add some robust bounds checking. Specifically, I'll ensure the size is *at least* `PAGE_SIZE` and doesn't exceed `PAGE_SIZE << MAX_PAGE_ORDER`. This upper bound seems prudent to prevent egregious memory allocations. This approach handles setting the parameter to an invalid value and providing a clear error message. The `param_get_int` will be used for retrieving the parameter's value as before.
Finally, in the `init_sg()` function, I would no longer need the conditional check since the validation is now performed during the parameter setting phase. I could remove it or leave it.
This revised approach gives me better control over the `scatter_elem_sz` parameter, enforces stricter bounds checking, and ensures that invalid values are rejected with proper error reporting. This is important for system stability and preventing unexpected behavior.
Now, let's examine lines 1870 to 1915 of `drivers/scsi/sg.c` to see how this change might impact the larger context...
|
| 559/4 |
2026/09/09 18:31 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1870 LineCount:45]
Results: map[Contents:1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
]
|
| 560/4 |
2026/09/09 18:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 70982
output: 33
thoughts: 1072
Thoughts: **Analyzing the Impact of the `min()` Function in `sg_build_indirect`**
Okay, let's dissect this change in `sg_build_indirect`, specifically focusing on lines 1876-1910. The original code was a bit clunky. We had this check and adjustment:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
```
And now it's simplified with the introduction of `min()`:
```c
order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
```
The key is `num = min(rem_sz, ret_sz);`. We're replacing that conditional with a direct call to the `min()` function. My first thought is: are there any potential type mismatches or implicit conversions that could cause issues? Let's check the definitions: in line 1858 both `rem_sz` and `ret_sz` are defined as `int`. So, that's clean.
Now, let's verify how `num` is used. Looking inside the loop, `num` is assigned the result of `min()` and used only in the `SCSI_LOG_TIMEOUT` call, which takes it as an argument. No other uses within the function. Then `scatter_elem_sz` is read to compute `order`.
The major concern with changes like this, especially in a driver, is concurrency. Could `scatter_elem_sz` change while the function is running? Let's consider that. `scatter_elem_sz` is read *once* at the beginning to compute the `order`. The value is then used to determine the allocation size. Even if another process *does* change `/sys/module/sg/parameters/scatter_elem_sz` mid-execution, we're guaranteed a valid value (within the `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]` range). And, critically, the code *doesn't* modify `scatter_elem_sz` or any other global state inside the loop. No need to worry about races.
Finally, I'll do a quick sanity check with `grepper` across the `sg.c` file to ensure that I haven't missed any other
|
| 561/4 |
2026/09/09 18:31 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 562/4 |
2026/09/09 18:31 |
llm |
patch-generator-compressor |
0m
Model:
Reply: ### Summary of Investigation and Workspace State
#### 1. Approaches Tried and Results (Including Dead-Ends)
- **Initial Approach by Prior Developer (Dead-End / Rejected by Senior Maintainer):**
- Added `num = PAGE_SIZE;` inside `sg_build_indirect()`.
- Cast `(int)PAGE_SIZE` in `init_sg()` and `sg_build_indirect()` to force signed comparisons against negative values.
- Clamped allocation order with `order = min_t(int, order, MAX_PAGE_ORDER);` inside `sg_build_indirect()`.
- **Maintainer Rejection:**
- Boundary validation failure: Sanitizing invalid parameter values inside fast path I/O (`sg_build_indirect()`) rather than rejecting at sysfs boundary violates architectural caller/callee invariants.
- Lack of subsystem idiom alignment: Did not follow recent precedent in `drivers/scsi/sg.c` set by commit `d06a310b45e1` (`def_reserved_size`) using `module_param_cb()`.
- Concurrency/data races: Silently mutating global variables (`scatter_elem_sz` and `scatter_elem_sz_prev`) without synchronization inside `sg_build_indirect()`.
- Anti-patterns and state divergence: Casting `(int)PAGE_SIZE` is an anti-pattern; clamping `order` in data path leaves sysfs parameter diverged (e.g. `INT_MAX`) from actual driver allocation behavior.
- **Design Evaluation for Validation (`param_set_uint_minmax` vs. Custom `.set` Callback):**
- Consulted `codeexpert` regarding Option 1 (custom `.set` callback matching `def_reserved_size_set`) vs. Option 2 (`param_set_uint_minmax`).
- Result: Option 1 (custom callback using `kstrtoint` returning `-ERANGE` on range error and `-EINVAL` on format error) directly mirrors the exact precedent in `drivers/scsi/sg.c` (commit `d06a310b45e1`).
- Confirmed: `scatter_elem_sz_prev` is completely obsolete and must be removed; the `sg_build_indirect()` loop must be simplified to eliminate all global state mutations.
#### 2. Current Hypotheses and Planned Architecture
- **Root Cause of Crash:**
- Writing `0` to `/sys/module/sg/parameters/scatter_elem_sz` allowed `scatter_elem_sz = 0`.
- In `sg_build_indirect()`, `num` was set to `0`, updated globals, but left `num = 0`.
- `get_order(0)` underflows `size--` to `~0UL`, returning `52` on 64-bit systems.
- `1 << (PAGE_SHIFT + order)` shifts 32-bit `1` by `12 + 52 = 64`, triggering UBSAN shift-out-of-bounds panic.
- **Architectural Solution:**
1. **Sysfs Parameter Validation:**
Replace `module_param_named(scatter_elem_sz, ...)` with `module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, S_IRUGO | S_IWUSR)` using a custom callback `scatter_elem_sz_set()`:
- Null check (`!val`) -> `-EINVAL`.
- Parse with `kstrtoint(val, 0, &size)` -> error on parse failure.
- Validate bounds: `if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)) return -ERANGE;`.
- Update `scatter_elem_sz = size;`.
- Ops table: `.set = scatter_elem_sz_set`, `.get = param_get_int`.
2. **Eliminate Global State Mutation and Data Races:**
- Delete `static int scatter_elem_sz_prev = SG_SCATTER_SZ;` completely from line 95.
- In `init_sg()`, remove `scatter_elem_sz_prev = scatter_elem_sz;`, keeping only `if (scatter_elem_sz < PAGE_SIZE) scatter_elem_sz = PAGE_SIZE;` (needed for systems where `PAGE_SIZE > SG_SCATTER_SZ` such as 64KB pages).
3. **Simplify `sg_build_indirect()`:**
- Remove the entire `unlikely(num != scatter_elem_sz_prev)` block.
- Simply compute `order = get_order(scatter_elem_sz);`. Since `scatter_elem_sz >= PAGE_SIZE` and `<= (PAGE_SIZE << MAX_PAGE_ORDER)`, `order` is strictly within `[0, MAX_PAGE_ORDER]`.
- Inside the allocation loop, set `num = min(rem_sz, ret_sz);` for `SCSI_LOG_TIMEOUT`.
- Remove the conditional global mutation block (`if (num == scatter_elem_sz_prev) { ... scatter_elem_sz = ret_sz; ... }`).
#### 3. Specific File Paths, Code Locations, and Code Snippets
- **Target File:** `drivers/scsi/sg.c`
- **Declaration (line 94-95):**
```c
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
```
- **Sysfs Parameter Definition (replacing line 1624):**
```c
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
```
- **`init_sg()` (lines 1670-1674):**
```c
- if (scatter_elem_sz < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
+ if (scatter_elem_sz < PAGE_SIZE)
+ scatter_elem_sz = PAGE_SIZE;
```
- **`sg_build_indirect()` (lines 1876-1906):**
```c
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
```
#### 4. Watch-Outs and Potential Pitfalls
- Check header inclusion for `MAX_PAGE_ORDER`: need to confirm `<linux/mmzone.h>` or `<linux/mm.h>` is already available in `drivers/scsi/sg.c` (or indirectly included via `<linux/gfp.h>` / `<linux/scatterlist.h>`).
- Avoid running into `codeexpert` iteration limits (reached limit on earlier multi-part query; all design decisions are now resolved).
- Do not keep any dangling references or declarations of `scatter_elem_sz_prev` to avoid compilation warnings.
Tokens:
input: 57727
output: 2315
thoughts: 0
|
| 563/4 |
2026/09/09 18:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 27718
output: 27
thoughts: 834
Thoughts: **Eliminating `scatter_elem_sz_prev` and Validating `scatter_elem_sz`**
Okay, I've confirmed that `scatter_elem_sz_prev` is only used in those specific lines: 95, 1672, 1877, 1880, 1882, 1892, 1893, 1899, 1900, and 1902. That's it, every single instance accounted for and eliminated. I can proceed with confidence.
Now, let's circle back and examine `init_sg()`. Specifically, that `if (scatter_elem_sz < PAGE_SIZE) scatter_elem_sz = PAGE_SIZE;` check is critical. My concern is, what if someone provides a crazy value for `scatter_elem_sz` at boot time through the kernel command line? Like, what if they set it to zero or a ridiculously large number?
Then I remembered, `module_param_cb`'s `.set` callback *does* get called during kernel boot when command-line parameters are parsed! The `parse_args()` function calls the parameter's `.set` callback. If the user provides an invalid value at boot, `scatter_elem_sz_set` will return `-ERANGE` (or `-EINVAL`). This will cause the module param parsing during boot to report an error, and `scatter_elem_sz` will be left at the default `SG_SCATTER_SZ` (32768). Then, the `init_sg()` function ensures that if `PAGE_SIZE > SG_SCATTER_SZ` (like on ARM64 or PowerPC with a 64KB page size), the value of `scatter_elem_sz` gets bumped up to `PAGE_SIZE`.
I quickly thought, what if `PAGE_SIZE` is greater than `(PAGE_SIZE << MAX_PAGE_ORDER)`? Obviously not. What if someone tries to override it at boot? It's validated by `scatter_elem_sz_set`. What if they write to `/sys/module/sg/parameters/scatter_elem_sz` at runtime? That also calls `scatter_elem_sz_set`, and it will return `-ERANGE` if the value is invalid. Great, that's what I want.
Finally, let's quickly double-check the permissions for `module_param_cb`:
```c
module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
S_IRUGO | S_IWUSR);
```
Let's do a quick scan of other module parameters in `drivers/scsi/sg.c` and other places. In `drivers/scsi/sg.c`, I see `module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);` and `module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size, S_IRUGO | S_IWUSR);`. Looks like lines 1625 and 1652 use `S_IRUGO | S_IWUSR` (which is `0644`). Perfect, it's consistent with what I'm doing.
Okay, just a final check on the `def_reserved_size` commit. Let me pull up commit `d06a310b45e1`.
|
| 564/4 |
2026/09/09 18:31 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 565/4 |
2026/09/09 18:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 30680
output: 37
thoughts: 1167
Thoughts: **Analyzing the Parameter Implementation and Placement**
Okay, so I'm looking at this recent commit, `d06a310b45e1`, and it's fresh, from just a few days ago, specifically January 27th, 2026. Perfect timing for seeing an example of the desired implementation style. The senior maintainer made it clear that we're supposed to follow this precedent in the `sg.c` driver. Specifically, they want us to use `module_param_cb()` with a custom `.set` callback to validate the `scatter_elem_sz` parameter, ensuring it stays within the `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]` range at configuration time. Return `-EINVAL` or `-ERANGE` on bad input; I understand that.
Looking at the code, it's clear: they're using a `.set` function to validate, which is good practice. Now, where does this new code go in `drivers/scsi/sg.c`? Let's take a look. They have `module_param_named` for `scatter_elem_sz` right next to the current `def_reserved_size` code. I need to make the same implementation style. It looks like I have two options: I can place my new `scatter_elem_sz_set`, `scatter_elem_sz_ops`, and `module_param_cb` right next to the existing `def_reserved_size` code, or I can put it right after the `def_reserved_size_cb`. The snippet I'm looking at is for comparison:
```c
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
scatter_elem_sz = size;
return 0;
}
static const struct kernel_param_ops scatter_elem_sz_ops = {
.set = scatter_elem_sz_set,
.get = param_get_int,
};
module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
S_IRUGO | S_IWUSR);
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
...
```
I'll check the current implementation to see where `scatter_elem_sz_set`, `scatter_elem_sz_ops`, and `module_param_cb` should be placed in `drivers/scsi/sg.c`, I need to make the correct placement and will need to update the build. I'll read through lines 1850-1925 very carefully.
|
| 566/4 |
2026/09/09 18:31 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1850 LineCount:60]
Results: map[Contents:1850: return tablesize; /* number of scat_gath elements allocated */
1851: }
1852:
1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
]
|
| 567/4 |
2026/09/09 18:31 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 33656
output: 37
thoughts: 54
Thoughts: Okay, let's dissect this.
**Analyzing the `alloc_pages` Failure Path**
Alright, so the code's hit a point where `alloc_pages` has potentially failed. We're jumping to the `out` label on line 1896. Now, I need to understand the consequences of this failure – what cleanup, error handling, or alternative procedures are initiated. I need to get a firm grasp on the flow. I know better than to assume, so let's jump over to lines 1910 to 1950 and see precisely what's happening at that `out:` label. It's time to follow the trail and see where we end up.
|
| 568/4 |
2026/09/09 18:32 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1910 LineCount:40]
Results: map[Contents:1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
1931: static void
1932: sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
1933: {
1934: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1935: "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
1936: if (schp->pages && schp->sglist_len > 0) {
1937: if (!schp->dio_in_use) {
1938: int k;
1939:
1940: for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
1941: SCSI_LOG_TIMEOUT(5,
1942: sg_printk(KERN_INFO, sfp->parentdp,
1943: "sg_remove_scat: k=%d, pg=0x%p\n",
1944: k, schp->pages[k]));
1945: __free_pages(schp->pages[k], schp->page_order);
1946: }
1947:
1948: kfree(schp->pages);
1949: }
]
|
| 569/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 34566
output: 10
thoughts: 2541
Thoughts: **Analyzing and Simplifying `sg_build_indirect`**
Okay, let's break this down. The core issue revolves around how `sg_build_indirect` handles page allocation, particularly when dealing with the `scatter_elem_sz` variable, which appears to have a history of causing headaches. The original code's logic, specifically the `if (num == scatter_elem_sz_prev) { ... }` block, is a relic of older kernel versions. It was designed to adjust `scatter_elem_sz` in case a user supplied a size that was not a power of two, forcing an allocation for the smallest power of two which included it. This had the unfortunate side effect of mutating global variables (`scatter_elem_sz` and `scatter_elem_sz_prev`) within the I/O path without any locking, leading to potential data races in concurrent scenarios.
The aim is to remove the global variable mutation. So, first, I need to understand how the code works now. After page allocation fails at a given `order`, it frees the allocated pages, decrements the `order`, and retries. At the `retry:` label, it calculates the allocation size (`ret_sz = 1 << (PAGE_SHIFT + order);`). The critical loop attempts to allocate pages, reducing the size of the allocation at each iteration. My main focus is the removal of the old adjustment of the variables within this critical loop.
The solution seems straightforward: replace the conditional update of `scatter_elem_sz` and `scatter_elem_sz_prev` with a direct calculation of `num = min(rem_sz, ret_sz);`. This simplifies the logic by allocating the smaller size needed to complete the scatter gather. Removing the global variable update eliminates the race condition and the global state mutation.
Before making the change, let's verify all the components involved. The global `scatter_elem_sz` is initialized and checked, and is now managed through a sysfs/module parameter with validation to ensure it's within the valid range [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]. The `sg_build_indirect` function now directly uses this size.
Now, let's consider potential edge cases. `ret_sz = 1 << (PAGE_SHIFT + order);` looks safe, even with the change. The `get_order()` function ensures `order` is within a reasonable range, preventing integer overflows or underflows, and the module parameter validation ensures `scatter_elem_sz` is not too large that `1 << (PAGE_SHIFT + MAX_PAGE_ORDER)` overflows.
Finally, confirm a clean tree with `git diff`, and I'm confident this simplification resolves the concurrency issue and aligns with the best practices for the kernel code.
|
| 570/4 |
2026/09/09 18:32 |
tool |
patch-diff |
0m
Error:
|
| 571/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 37722
output: 15
thoughts: 22
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating Potential Changes with `patch-diff`**
Okay, so I'm thinking, let's leverage `patch-diff` here. My gut tells me there might be some underlying changes we need to account for, even if they aren't immediately obvious from the surface. A crucial diagnostic technique I often use is to call `patch-diff` with an empty file argument, explicitly, for `File: ""`. This is to make sure we're getting a clear view of the potential diffing of all of the relevant underlying files. By running it this way, I'm expecting to either see an empty output, confirming no modifications (and thus, my initial hunch is correct), or, more importantly, a detailed report of any underlying differences. This approach is fairly efficient and can eliminate a large class of potential issues quickly. It's a fundamental sanity check before getting too deep into debugging. I use it all the time to quickly establish a baseline.
|
| 572/4 |
2026/09/09 18:32 |
tool |
patch-diff |
0m
Args:
Results:
|
| 573/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 37990
output: 35
thoughts: 31
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Checking SCSI Driver Sanitation**
Alright, that initial sweep confirmed the codebase looks clean, no immediate red flags. Good. Now, I need to zoom in on a specific area, something I was looking at earlier. Let's revisit lines 90 through 100 of `drivers/scsi/sg.c`. Specifically, I want to make sure the sanity checks within that region are still up to snuff and catch edge cases in that code's interaction.
|
| 574/4 |
2026/09/09 18:32 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:90 LineCount:10]
Results: map[Contents: 90: /* picks up init parameter */
91: static int def_reserved_size = SG_DEF_RESERVED_SIZE;
92: static int sg_allow_dio = SG_ALLOW_DIO_DEF;
93:
94: static int scatter_elem_sz = SG_SCATTER_SZ;
95: static int scatter_elem_sz_prev = SG_SCATTER_SZ;
96:
97: #define SG_SECTOR_SZ 512
98:
99: static int sg_add_device(struct device *);
]
|
| 575/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 38343
output: 37
thoughts: 26
Thoughts: Here's a summary of my thought process, as if I were the one thinking it:
**Diving into the `sg.c` Driver**
Okay, time to get my hands dirty. I need to understand this SCSI generic driver behavior, so I'm going to pinpoint the relevant code. Let's start with a focused investigation. I'm going to zero in on lines 1620-1655 of the `drivers/scsi/sg.c` file. This specific section likely handles a particular aspect or function. I'll need to analyze what's going on within that block to further my understanding of the larger picture. From here, I'll identify the flow of data or the control path within this area of code.
|
| 576/4 |
2026/09/09 18:32 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1620 LineCount:35]
Results: map[Contents:1620:
1621: kref_put(&sdp->d_ref, sg_device_destroy);
1622: }
1623:
1624: module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
]
|
| 577/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 39094
output: 37
thoughts: 26
Thoughts: Here's a summary of my thought process, as if I were the one thinking it:
**Diving into the `sg.c` Driver**
Okay, time to get my hands dirty. Let's zero in on the `drivers/scsi/sg.c` code. My immediate concern is probably related to SCSI Generic (sg) device handling, and I need to understand what's happening in a specific section. Specifically, I'm going to carefully review lines 1665 through 1678. I'm hoping to quickly identify a particular function or set of operations. I'll be looking for any potential interaction with devices or resources that may be causing a performance bottleneck or other interesting behavior I want to understand better. I'll keep an eye out for any obvious candidates related to error handling, command queuing, or device access control. Let's see what gems are hidden in those lines.
|
| 578/4 |
2026/09/09 18:32 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1665 LineCount:15]
Results: map[Contents:1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
1675: rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1676: SG_MAX_DEVS, "sg");
1677: if (rc)
1678: return rc;
1679: rc = class_register(&sg_sysfs_class);
]
|
| 579/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 39576
output: 37
thoughts: 26
Thoughts: Here's my summary, as if I were the one thinking these thoughts, geared towards an expert:
**Diving into sg.c for a Specific Block of Code**
Okay, I need to get into the weeds of `drivers/scsi/sg.c`. Specifically, I want to zero in on lines 1870 through 1910. I know this module like the back of my hand, but I'm looking at a particular issue and I remember that code block as being relevant. I'm probably looking for a specific data structure, an error condition, or perhaps a locking mechanism that's interacting in a way I hadn't quite foreseen. Time to refresh my memory and pinpoint the exact logic being executed there. I'm hoping to quickly grasp the interaction between the user space and the SCSI layer, or whatever the relevant context happens to be for those specific lines. Let's see what's going on!
|
| 580/4 |
2026/09/09 18:32 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1870 LineCount:40]
Results: map[Contents:1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
]
|
| 581/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 40506
output: 83
thoughts: 33
Thoughts: Okay, here's my take on those instructions, thinking through them as I would in practice:
**Applying the Code Changes**
Alright, time to execute these edits using `codeeditor`. Let's see, the first change is straightforward: I need to eliminate the `scatter_elem_sz_prev` declaration. I know exactly where that is, line 95. No need to overthink it; just a simple removal of that variable. Let's get that done, and then we can move on to the next instruction. This should be a quick one.
|
| 582/4 |
2026/09/09 18:32 |
tool |
codeeditor |
0m
Args: map[CurrentCode:static int scatter_elem_sz = SG_SCATTER_SZ;
static int scatter_elem_sz_prev = SG_SCATTER_SZ; NewCode:static int scatter_elem_sz = SG_SCATTER_SZ; SourceFile:drivers/scsi/sg.c]
Results:
|
| 583/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 40749
output: 335
thoughts: 67
Thoughts: Here's my thinking process:
**Refactoring `module_param_named` for Enhanced Control**
Okay, so I'm looking at this `module_param_named` call: `module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);`. It's perfectly functional, but I see an opportunity here to exert more granular control over the parameter and its interactions with the module. I want to transition away from the simple, built-in parameter handling and towards a custom callback mechanism for greater flexibility.
Essentially, I want to replace the single line with something more sophisticated. This allows fine-tuning how the parameter is set, validated, and potentially even how it affects other module components.
The first step is to declare a new variable named `scatter_elem_sz_set` to hold the value of the integer and use a custom structure `scatter_elem_sz_ops` to define functions that provide callback functionality to set this value and ensure it is valid. Then, I need to use `module_param_cb`, which, as a callback, provides me with that control. The `module_param_cb` function takes this custom function for setting the parameter along with other information about the parameter.
|
| 584/4 |
2026/09/09 18:32 |
tool |
codeeditor |
0m
Args: map[CurrentCode:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR); NewCode:module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
scatter_elem_sz = size;
return 0;
}
static const struct kernel_param_ops scatter_elem_sz_ops = {
.set = scatter_elem_sz_set,
.get = param_get_int,
};
module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
S_IRUGO | S_IWUSR); SourceFile:drivers/scsi/sg.c]
Results:
|
| 585/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 41430
output: 105
thoughts: 105
Thoughts: **Refactoring a Scatter/Gather Initialization**
Okay, let's take a look at this code snippet. We're in the `init_sg()` function, and I see a redundant assignment. The original code checks if `scatter_elem_sz` is less than `PAGE_SIZE`. If it is, it sets `scatter_elem_sz` to `PAGE_SIZE` and then *also* sets `scatter_elem_sz_prev` to the *same* value. While not functionally incorrect, the `scatter_elem_sz_prev = scatter_elem_sz;` line is superfluous. If `scatter_elem_sz` *wasn't* smaller than `PAGE_SIZE`, this second line does nothing. The more concise, and clearer, way to handle this is to eliminate that second assignment, making the `if` statement more streamlined. So, I will remove that line, leaving only the direct assignment to `scatter_elem_sz`. It's a minor change, but it removes unnecessary clutter and improves readability. Time to make that change!
|
| 586/4 |
2026/09/09 18:32 |
tool |
codeeditor |
0m
Args: map[CurrentCode: if (scatter_elem_sz < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = scatter_elem_sz;
} NewCode: if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE; SourceFile:drivers/scsi/sg.c]
Results:
|
| 587/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 41874
output: 600
thoughts: 603
Thoughts: **Refactoring `sg_build_indirect` for Improved Memory Allocation**
Okay, so I'm looking at this `sg_build_indirect` function, specifically how it allocates pages for scatter-gather lists. The original version had some logic to try and dynamically adjust `scatter_elem_sz` which determined the size of the allocation, but it felt a little clunky and possibly inefficient. It seems to have a few checks to ensure it doesn't allocate smaller than a page and has some logic to change the order based on the `scatter_elem_sz` which wasn't as straightforward as it could be.
The new version simplifies things considerably. The key is in calculating `ret_sz`, which is the actual amount of memory that needs to be allocated based on the `order`. I've now directly used `scatter_elem_sz` to derive the `order` using `get_order()`, avoiding the prior conditional logic.
Within the loop that iterates through the blocks, I'm now just taking the minimum between the remaining size `rem_sz` and `ret_sz` to get the allocation size (`num`). This ensures that the allocated size is the right amount, and doesn't get messed up if the blocks requested are slightly smaller. It then attempts to allocate a page of the specified order, or size, using `alloc_pages()`. The rest of the loop remains pretty much the same: it iterates, calculates the allocation size, allocates the page, and logs some information.
The main intent is to simplify the allocation process and potentially optimize it by removing the dynamic adjustment of the allocation size within the function, while also maintaining the correct order based on the initial `scatter_elem_sz` value. It should lead to more predictable memory usage and slightly cleaner code, and less unnecessary code.
|
| 588/4 |
2026/09/09 18:32 |
tool |
codeeditor |
0m
Args: map[CurrentCode: num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */ NewCode: order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */ SourceFile:drivers/scsi/sg.c]
Results:
|
| 589/4 |
2026/09/09 18:32 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 43463
output: 23
thoughts: 13
Thoughts: Okay, here's my attempt at summarizing the thought process, as if I were a skilled professional, and in the first person:
**Analyzing the Code Changes with `patch-diff`**
Alright, time to get into the details. I need to understand what's been changed, and `patch-diff` is usually my go-to for this kind of quick analysis. Let's see... I'll run the diff command and then... *[The user would then imagine the output of the diff, and react in their mind]* ...Okay, good. Now I'm mentally parsing the changes. I'm focusing on the context lines first, to get the broad picture of what files and functions are involved. Are we talking a minor tweak or some kind of significant refactor? And the context lines give me that first important overview. Then I'm zeroing in on the "hunks" of code, mentally highlighting the added and deleted lines. I'm looking for patterns, potential bugs introduced, areas where optimization might be needed, and also checking for anything that could break existing functionality. I'm also cross-referencing with any related documentation or other parts of the codebase that I know are relevant to these changes. With this quick pass, I'm mentally identifying any areas that will require more in-depth investigation.
|
| 590/4 |
2026/09/09 18:33 |
tool |
patch-diff |
0m
Args: map[File:drivers/scsi/sg.c]
Results: map[Output:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..71e1adea0 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -85,21 +85,20 @@ static int sg_proc_init(void);
* /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
* of this size (or less if there is not enough memory) will be reserved
* for use by this file descriptor.
*/
/* picks up init parameter */
static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
static int sg_add_device(struct device *);
static void sg_remove_device(struct device *);
static DEFINE_IDR(sg_index_idr);
static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
file descriptor list for device */
@@ -1614,23 +1613,48 @@ sg_remove_device(struct device *cl_dev)
read_unlock_irqrestore(&sdp->sfd_lock, iflags);
sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
device_destroy(&sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));
cdev_del(sdp->cdev);
sdp->cdev = NULL;
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
@@ -1660,35 +1684,33 @@ MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
"size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
static int __init
init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
if (rc)
return rc;
rc = class_register(&sg_sysfs_class);
if (rc)
goto err_out;
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
return 0;
}
class_unregister(&sg_sysfs_class);
err_out:
unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
return rc;
}
@@ -1854,76 +1876,59 @@ static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
int blk_size = buff_size, order;
gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
if (blk_size < 0)
return -EFAULT;
if (0 == blk_size)
++blk_size; /* don't know why */
/* round request up to next highest SG_SECTOR_SZ byte boundary */
blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: buff_size=%d, blk_size=%d\n",
buff_size, blk_size));
/* N.B. ret_sz carried into this block ... */
mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
k, rem_sz));
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
return 0;
out:
for (i = 0; i < k; i++)
__free_pages(schp->pages[i], order);
if (--order >= 0)
goto retry;
return -ENOMEM;
}
]
|
| 591/4 |
2026/09/09 18:33 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 46143
output: 646
thoughts: 339
Thoughts: **My Assessment of the Code Diff**
Okay, this is *much* better. This diff is exactly what I was hoping to see. It's clean, well-structured, and methodically addresses every single concern I raised in the initial review. Let me break it down:
1. **Boundary Validation - Nailed it.** Replacing that band-aid approach with validation at the sysfs boundary using `module_param_cb()` is precisely what was needed. Rejecting invalid values like zero, negatives, or anything exceeding page size limits with the proper error codes (`-ERANGE` and `-EINVAL`) is perfect. That handles all the edge cases properly.
2. **Subsystem Idiom - Spot On.** Aligning this with the precedent set by that `scsi: sg` commit for `def_reserved_size` is the best approach for consistency and maintainability. Using `module_param_cb()` with the `.set` and `.get` functions is the right idiom here.
3. **Concurrency and State - Solved.** Getting rid of `scatter_elem_sz_prev` entirely and removing those runtime mutations in `sg_build_indirect()` completely eliminates any risk of those uncoordinated concurrent data races. The code is much simpler, which is always good.
4. **Typing and State Divergence - Excellent.** No ad-hoc casts to `(int)PAGE_SIZE` - thank goodness. Validating this at configuration time means the driver's allocation behavior and sysfs parameter state will always be in sync. That divergence issue is gone.
Alright, I can go ahead and give this the thumbs up. This is now fully addresses all the concerns. I'm satisfied.
|
| 592/3 |
2026/09/09 18:33 |
action |
test-patch |
12m
Results: map[PatchDiff:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..71e1adea0 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,34 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1691,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1895,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
TestError:]
|
| 593/3 |
2026/09/09 18:46 |
action |
If |
24m
Args:
|
| 594/4 |
2026/09/09 18:46 |
agent |
patch-reviewer |
24m
Model:
Results: map[ReviewApproved:true ReviewComments:[]]
Instruction: You are an experienced Linux kernel maintainer reviewing a proposed patch that compiles and passes reproducer tests.
Evaluate the patch diff against the crash report, root cause, and the architectural design guidelines below.
Scope Constraint (Single-Patch Submissions):
We only generate single, standalone patches (not patch series). If a comprehensive architectural redesign would require a multi-patch series touching many files, accept a localized single-patch fix as long as it correctly fixes the bug, does not introduce new issues, and avoids sentinel band-aids within its local scope.
Evaluation:
- Set ReviewApproved=true (and leave ReviewComments empty) if the patch is acceptable for upstream submission as a single-patch fix.
- Set ReviewApproved=false and list concise, actionable feedback in ReviewComments if the patch contains fixable "Kernel Architectural Design & Maintainer Taste" violations.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
---
# Kernel Architectural Design & Maintainer Taste
Evaluate kernel patches and fix proposals beyond binary bug presence. Enforce **maintainer taste**, **lifecycle symmetry**, **typestate soundness**, and **topological graph simplicity**.
---
## 1. Core Philosophy: Band-Aid vs. Architectural Design
Naive patches often introduce **defensive sentinel guards** (e.g., ad-hoc `if (!ptr) return;` checks, status flags, or suppressed warnings) directly at the point of failure. While locally avoiding crashes, they degrade subsystem architecture by leaving uninitialized states reachable.
Maintainer "good taste" solves the root cause by **shifting invariants** (making invalid states unrepresentable) and moving dynamic runtime checks into static typestate guarantees.
```
HACKY BAND-AID FIX (Monolithic Cleanup) ARCHITECTURAL DESIGN (Scoped RAII / Invariant Shift)
─────────────────────────────────────── ────────────────────────────────────────────────────
[ Init / Entry ] [ Init / Entry ]
│ │
(Register Global Cleanup) (Allocate Resource A)
│ │
[ Init Sub-B ] ──fail──┐ [ Init Sub-B ] ──fail──┐
│ (success) │ │ (success) │
▼ │ ▼ ▼
[ Setup Complete ] │ (Arm B Cleanup / RAII) (Unwind A Only:
│ │ │ B never armed)
(Deferred Teardown) │ ▼ │
│ │ [ Setup Complete ] ▼
▼ ▼ │ [ Error Exit ]
[ release_all ] ◄───────┘ (LIFO Scope Teardown)
│ │
(if (!ctx->b) return;) <-- Defensive guard! ▼
│ [ Clean Destruction ]
[ Unsafe State ] (Zero sentinel checks needed)
```
```c
// ANTI-PATTERN (Defensive Sentinel Guard): Teardown called on partial init -> callee needs guard
void driver_cleanup(struct ctx *ctx) {
if (!ctx->buf) return; // <-- Sentinel band-aid
free_buffer(ctx->buf);
}
// CANONICAL SHIFT (Granular Scoped Action): Registered only upon complete initialization
ctx->buf = alloc_buffer();
if (!ctx->buf) return -ENOMEM;
devm_add_action_or_reset(dev, free_buffer_action, ctx->buf);
```
---
## 2. Maintainer Taste as Graph Topology & Structural Simplicity
Software design quality maps directly to graph-theoretic properties across the Control-Flow Graph (CFG), Data-Flow Graph (DFG), and Object Lifecycle DAG:
### A. Control-Flow Graph (CFG) Simplification
* **Branch Minimization & Path Explosion (McCabe 1976):** Every defensive check added to a compound destructor or callback (`if (!ctx->buffer) return;`) adds a predicate node ($\pi$), increases cyclomatic complexity $v(G) = |E| - |V| + 2$, causes exponential path explosion ($O(2^k)$ paths), and enlarges explicit state spaces ($|S| = \prod |D_i|$). Good taste eliminates the branch by guaranteeing destructors are invoked only on initialized typestates. *(Note: Standard idempotent leaf deallocators like `kfree(NULL)` and public API input sanitizers are exempt).*
* **Single-Entry Single-Exit (SESE) Symmetry (Ferrante 1987, Johnson 1994, Dijkstra 1972):** Resource acquisition and release must form strict **nested dominator trees**. If resource $R_i$ is acquired at node $A$, the set of release actions $\{B_1, \dots, B_m\}$ must form a strict **post-dominating cut** relative to $A$ across all maximal exit paths.
* **Pointer Uniformity (Linus's "Good Taste" Rule):** Eliminate special-case conditional branches by operating on address indirection (e.g., indirect pointers `**curr` in linked list unlinking) to unify edge and interior cases into a branchless invariant.
* **Lexical Scope Invariants & Affine Lifecycles (Wadler 1990, RAII):** Enforce SESE symmetry and "consumed exactly once" affine invariants using compiler-backed scoped cleanup (`<linux/cleanup.h>` `guard()`, `scoped_guard()`, `__free()`).
### B. Ownership & Lifetime DAGs
* **Acyclic Lifecycles & Topological Teardown (Tarjan 1972, Kahn 1962):** Resource ownership must form a strict Directed Acyclic Graph (DAG) $G = (R, E)$. Teardown order must strictly follow reverse topological sort $\text{toposort}(G)^R$. Mixing conflicting lifetime paradigms (e.g., embedding a dynamic refcounted `kref`/socket struct inside a device-managed `devres` buffer or parent container) violates DAG acyclicity, creating synchronous blocking hacks (`wait_for_completion`), circular pins, and Use-After-Free hazards.
* **Three-Phase Concurrent Quiescence:** Multi-threaded and asynchronous teardown (networking, block layer, RCU) must strictly sequence: (1) **Deactivation/Delisting** (make unreachable) -> (2) **Quiescence & Draining** (`synchronize_rcu()`, `cancel_work_sync()`, `napi_disable()`) -> (3) **Physical Reclamation** (`kfree()`, `kmem_cache_destroy()`).
* **Typestate Validity (Strom & Yemini 1986, Aldrich et al. 2009):** A struct with $N$ fields should not use runtime boolean flags (`ctx->is_initialized`) to model incomplete typestates. Sub-resources must transition as a deterministic typestate automaton ($S_{uninit} \xrightarrow{\text{alloc}} S_{init} \xrightarrow{\text{publish}} S_{registered}$), and registration functions must accept only fully initialized typestates.
---
## 3. Deterministic Decision Trigger Matrix
| Code Symptom / Trigger (When you see X) | Anti-Pattern Band-Aid (DO NOT DO Z) | Canonical Invariant Shift (DO Y) |
| :--- | :--- | :--- |
| **Null deref in compound destructor / cleanup callback** | Add `if (!priv->buf) return;` in composite cleanup handler | Register granular cleanup immediately upon allocation via `devm_add_action_or_reset()`, `<linux/cleanup.h>` `__free()`, or discrete reverse LIFO labels |
| **UAF on dynamic object after container unbind** | Allocate with `devm_kzalloc()` and block on `wait_for_completion()` | Allocate with `kzalloc()`, manage lifetime via `kref_get()`/`kref_put()`, call unbind/delist on unbind, free in `kref` release callback |
| **Goto ladder lock leaks on early error exit** | Sprinkle manual `mutex_unlock()` across error returns | Use `guard(mutex)(&lock)` or `scoped_guard(spinlock, &lock)` from `<linux/cleanup.h>` |
| **Callback / IRQ / timer fires before full init** | Add `if (!priv->ready)` check inside IRQ/timer handler | Move `request_irq()`, `timer_setup()`, or `napi_enable()` strictly to the end of setup after all state structures are fully initialized |
| **Multi-step setup failure leaks resources** | Route all errors to a single `err:` label calling a monolithic `cleanup(priv)` with NULL checks | Use `cleanup.h` RAII, granular `devm` actions, or a strict reverse LIFO goto ladder (`err_free_b:` -> `err_free_a:`) |
| **Mixed ownership / asymmetric refcount drops** | Conditionally call `kref_put()` in caller based on error code | Enforce unconditional callee-cleans or caller-cleans ownership convention across all paths |
| **Ad-hoc state flag polling during teardown** | Add `priv->stopping = true` and spin/poll in callbacks | Use atomic typestate transitions and synchronous flush/drain APIs (`cancel_work_sync()`, `drain_workqueue()`) |
---
## 4. The Architectural Review Checklist
Before finalizing any kernel fix or review, audit against the following four criteria:
1. **The Sentinel Test (Caller vs. Callee Responsibility):**
* *Smell:* Adding a defensive guard (`if (!ptr)` or `if (flags & INITIALIZED)`) inside a compound teardown callback or destructor to mask partial initialization.
* *Invariant:* If a destructor executes on uninitialized data, the defect is at the **caller's registration/invocation point**, not the callee.
* *Note:* Standard C allocator no-ops (`kfree(NULL)`) and public API parameter validators (`if (WARN_ON(!ptr)) return -EINVAL;`) are exempt; this rule targets *internal subsystem lifecycle pipelines and teardown paths*.
* *Action:* Move registration to the point of complete initialization (`devm_add_action_or_reset()`, RAII/`__free()`, or discrete caller unwinding).
2. **LIFO Stack Unwinding Symmetry:**
* *Smell:* Releasing resources in arbitrary order or invoking destructors for partially initialized subsystems.
* *Invariant:* Resource release must strictly mirror acquisition order in reverse (LIFO) without monolithic cleanup guards.
* *Action:* Verify that partial setup/initialization failures (e.g., `probe()`, `mount()`, `open()`, `alloc_pool()`) unwind only already-allocated resources in reverse order via strict LIFO labels or `cleanup.h` scope exit.
3. **Ownership Decoupling:**
* *Smell:* Embedding dynamically refcounted objects (`kref`, `struct sock`, `struct inode`, `struct file`) directly inside hardware device-bound allocations (`devres`) or parent containers (`super_block`, `net_device`).
* *Invariant:* Dynamic consumer references must outlive parent unregistration without use-after-free, circular pins, or blocking hacks.
* *Action:* Decouple the refcounted core object from the container binding; container teardown must unbind/delist the object, but memory is freed exclusively by the final `kref_put()`.
4. **Codebase Idiom Alignment:**
* *Smell:* Using legacy custom rollback ladders, ad-hoc state flags, or manual lock unlocking on error paths.
* *Invariant:* Prefer standard, modern kernel abstractions with compiler-enforced safety guarantees.
* *Action (Modern >= 6.6):* Replace manual boilerplate with `cleanup.h` (`guard()`, `scoped_guard()`, `__free()`), `devm_add_action_or_reset()`, `refcount_t`, and standard `kref` helpers.
* *Action (Legacy / LTS / No-RAII Subsystems):* Enforce clean, branchless reverse LIFO goto ladders (`err_free_b:` -> `err_free_a:`).
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:
Bug title:
UBSAN: shift-out-of-bounds in sg_build_indirect
The crash report:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
The root cause explanation:
An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
The proposed patch diff:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..71e1adea0 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,34 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1691,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1895,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
Review this patch diff against the crash report, root cause explanation, and kernel architectural design guidelines.
|
| 595/5 |
2026/09/09 18:46 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 10332
output: 37
thoughts: 147
Thoughts: **Analyzing a Linux Kernel Patch: A Systematic Approach**
Okay, so the user wants me to take a look at a proposed patch for the Linux kernel. My process always starts the same way: let's dive into the core of the problem. First up, I need to understand the crash report and the proposed fix.
Alright, the report highlights a shift-out-of-bounds error, specifically in `drivers/scsi/sg.c` at line 1887. The error message clearly indicates a shift exponent of 64 is exceeding the bounds for a 32-bit integer, and the stack trace, `sg_build_indirect -> sg_build_reserve -> sg_add_sfp -> sg_open`, provides a great starting point for understanding the call chain.
Now, it's time to get my hands dirty. I'll zero in on `drivers/scsi/sg.c` around line 1887. Time to leverage the code search and file reading tools to get a direct view of the offending code and its context. With the crash report and code at hand, I can thoroughly analyze the problem and evaluate the patch with an informed perspective.
|
| 596/5 |
2026/09/09 18:46 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1860 LineCount:80]
Results: map[Contents:1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
1930:
1931: static void
1932: sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
1933: {
1934: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1935: "sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
1936: if (schp->pages && schp->sglist_len > 0) {
1937: if (!schp->dio_in_use) {
1938: int k;
1939:
]
|
| 597/5 |
2026/09/09 18:46 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 12107
output: 35
thoughts: 35
Thoughts: Okay, here's my take on those lines of `drivers/scsi/sg.c`, framed as my own thought process, as requested:
**Digging into the `sg.c` Driver**
Alright, let's get down to brass tacks. I've been asked to review a specific section of the SCSI generic driver, `drivers/scsi/sg.c`, and I know from experience that pinpointing potential issues requires a targeted approach. My first move will be to zero in on lines 80-120. This usually is a region in the file dealing with initialization or setup routines. Often, driver initialization is where we will find common gotchas. This area is crucial for understanding how the device presents itself to the system and handles basic setup. Any subtle errors here can cascade into significant problems later on, so I'll be meticulously examining the interactions with the SCSI layer and the device itself. I'll be looking for resource allocation issues, potential race conditions during initial probe and attach, and anything that might be out of spec regarding SCSI standards.
Beyond the initial setup, I'm also instructed to review lines 1600-1700. This is a significantly different region. Judging by the line numbers, I'd wager it's likely a critical section dealing with command execution, data transfer, or interrupt handling. Given my understanding of SCSI architecture, that range suggests it could be responsible for something like command queuing, the handling of scatter-gather lists, or even dealing with device errors. This part warrants a deeper dive, potentially focusing on the intricate dance between user-space requests and the low-level hardware. I'll be paying close attention to any atomic operations or locking mechanisms used, as these can easily become bottlenecks or sources of contention. I'll be looking for possible deadlocks, and areas where error handling might be weak. My goal is to determine if data is handled correctly and efficiently, and if the driver can recover gracefully from SCSI bus errors or hardware failures. I'll also check for any obvious vulnerabilities.
|
| 598/5 |
2026/09/09 18:46 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:80 LineCount:40]
Results: map[Contents: 80: #define SG_MAX_CDB_SIZE 252
81:
82: #define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
83:
84: /* N.B. This variable is readable and writeable via
85: * /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
86: * of this size (or less if there is not enough memory) will be reserved
87: * for use by this file descriptor.
88: */
89:
90: /* picks up init parameter */
91: static int def_reserved_size = SG_DEF_RESERVED_SIZE;
92: static int sg_allow_dio = SG_ALLOW_DIO_DEF;
93:
94: static int scatter_elem_sz = SG_SCATTER_SZ;
95: static int scatter_elem_sz_prev = SG_SCATTER_SZ;
96:
97: #define SG_SECTOR_SZ 512
98:
99: static int sg_add_device(struct device *);
100: static void sg_remove_device(struct device *);
101:
102: static DEFINE_IDR(sg_index_idr);
103: static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
104: file descriptor list for device */
105:
106: static struct class_interface sg_interface = {
107: .add_dev = sg_add_device,
108: .remove_dev = sg_remove_device,
109: };
110:
111: typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
112: unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */
113: unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
114: unsigned bufflen; /* Size of (aggregate) data buffer */
115: struct page **pages;
116: int page_order;
117: char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
118: unsigned char cmd_opcode; /* first byte of command */
119: } Sg_scatter_hold;
]
|
| 599/5 |
2026/09/09 18:46 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 13286
output: 37
thoughts: 28
Thoughts: Okay, here's my interpretation of what's going through my mind, delivered as a first-person summary, and targeted at a fellow expert:
**Diving into the `sg.c` Details**
Alright, so we're talking about SCSI generic device interaction, and that means we *need* to understand the `sg` driver. My immediate focus is on lines 1610 to 1700 of `drivers/scsi/sg.c`. I'm assuming we're dealing with a specific interaction point or a particular code block. Given the line range, this likely involves something substantial: perhaps a crucial error-handling routine, some significant data transfer manipulation, or maybe a vital part of command execution flow. I need to figure out *what* within that range is of interest. Are we debugging a specific issue, or are we just trying to get a better handle on the driver's internals? I'm going to start by quickly scanning that section to build a mental map of the surrounding code and the function calls. I'll be looking for any hints or key variables that could illuminate the intent and the specific operations at hand. Keep an eye out for how this section relates to the overall scsi operation. I expect to be able to use my broad knowledge of the SCSI subsystem to quickly understand the nuances. I'm hoping that specific function calls or variable names will quickly highlight the areas to examine in depth. This should give me the context necessary to formulate effective questions or identify potential problem areas.
|
| 600/5 |
2026/09/09 18:46 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1610 LineCount:90]
Results: map[Contents:1610: wake_up_interruptible_all(&sfp->read_wait);
1611: kill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP);
1612: }
1613: wake_up_interruptible_all(&sdp->open_wait);
1614: read_unlock_irqrestore(&sdp->sfd_lock, iflags);
1615:
1616: sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
1617: device_destroy(&sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));
1618: cdev_del(sdp->cdev);
1619: sdp->cdev = NULL;
1620:
1621: kref_put(&sdp->d_ref, sg_device_destroy);
1622: }
1623:
1624: module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
1655: MODULE_DESCRIPTION("SCSI generic (sg) driver");
1656: MODULE_LICENSE("GPL");
1657: MODULE_VERSION(SG_VERSION_STR);
1658: MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
1659:
1660: MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
1662: MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1663: MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
1664:
1665: static int __init
1666: init_sg(void)
1667: {
1668: int rc;
1669:
1670: if (scatter_elem_sz < PAGE_SIZE) {
1671: scatter_elem_sz = PAGE_SIZE;
1672: scatter_elem_sz_prev = scatter_elem_sz;
1673: }
1674:
1675: rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1676: SG_MAX_DEVS, "sg");
1677: if (rc)
1678: return rc;
1679: rc = class_register(&sg_sysfs_class);
1680: if (rc)
1681: goto err_out;
1682: sg_sysfs_valid = 1;
1683: rc = scsi_register_interface(&sg_interface);
1684: if (0 == rc) {
1685: #ifdef CONFIG_SCSI_PROC_FS
1686: sg_proc_init();
1687: #endif /* CONFIG_SCSI_PROC_FS */
1688: return 0;
1689: }
1690: class_unregister(&sg_sysfs_class);
1691: err_out:
1692: unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
1693: return rc;
1694: }
1695:
1696: static void __exit
1697: exit_sg(void)
1698: {
1699: #ifdef CONFIG_SCSI_PROC_FS
]
|
| 601/5 |
2026/09/09 18:46 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 15104
output: 20
thoughts: 17
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating `SG_SCATTER_SZ`**
Okay, time to get to the bottom of this. My initial thought is to dive right in and understand the definition of `SG_SCATTER_SZ`. It's a critical macro, likely related to scatter/gather operations. I need to know its value to assess its impact on performance, memory usage, or any potential limitations in the current context. This could be a tunable parameter, a fixed system constant, or derived based on some other system characteristic. Knowing its definition will provide critical insight.
|
| 602/5 |
2026/09/09 18:46 |
tool |
grepper |
0m
Args: map[Expression:SG_SCATTER_SZ]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1660=MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c:1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
drivers/scsi/sg.c-1662-MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
--
include/scsi/sg.h=175=typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
--
include/scsi/sg.h-249-
include/scsi/sg.h:250:#define SG_SCATTER_SZ (8 * 4096)
include/scsi/sg.h-251-/* Largest size (in bytes) a single scatter-gather list element can have.
include/scsi/sg.h:252: The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
include/scsi/sg.h-253- This value should be a power of 2 (and may be rounded up internally).
--
include/scsi/sg.h-261-#define SG_DEF_KEEP_ORPHAN 0
include/scsi/sg.h:262:#define SG_DEF_RESERVED_SIZE SG_SCATTER_SZ /* load time option */
include/scsi/sg.h-263-
]
|
| 603/5 |
2026/09/09 18:46 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 15767
output: 24
thoughts: 2032
Thoughts: **Analyzing the scatter_elem_sz in drivers/scsi/sg.c**
Alright, let's break this down. My initial thought was to quickly check the `def_reserved_size_set` function in `drivers/scsi/sg.c`, which seems to have a validation check. That's straightforward enough. But then, I noticed something about the `scatter_elem_sz` variable, which is a module parameter, and root can write to it directly. That's a red flag!
Originally, `scatter_elem_sz` was directly set using `param_set_int`. The code then uses this `scatter_elem_sz` within `sg_build_indirect()`. The code attempts to adjust `scatter_elem_sz` based on certain conditions, ensuring it's at least `PAGE_SIZE`, but it still presents a potential issue due to its writeable nature and how it's used to allocate pages.
Now, looking at the proposed patch, I see a significant change. They've replaced the direct use of `module_param_named` with `module_param_cb` for `scatter_elem_sz`. This is a good move because it introduces a custom `scatter_elem_sz_set` function. This custom setter adds a critical range check. The patch now restricts writes to `scatter_elem_sz` to be between `PAGE_SIZE` and `PAGE_SIZE << MAX_PAGE_ORDER`. They've also removed the need for `scatter_elem_sz_prev`. The change modifies the logic within `sg_build_indirect()` to use `scatter_elem_sz` directly, simplifying the allocation and validation.
My assessment is that this patch is a definite improvement. It addresses the potential vulnerability of an uncontrolled module parameter by adding validation and limiting the possible values.
|
| 604/5 |
2026/09/09 18:46 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:def_reserved_size_ops]
Results:
|
| 605/5 |
2026/09/09 18:56 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 18252
output: 38
thoughts: 19
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and presented as if it were my own internal monologue:
**Adding a Specific Path for Context**
Right, so I'm looking at this code and immediately I see a need for better context. A simple, but effective, way to achieve this is by providing a precise path identifier. I need to make it incredibly clear where in the file system this code resides. Let's make sure everyone understands *exactly* where this piece of the kernel lives. The immediate thought is to add `PathPrefix: "drivers/scsi/sg.c"`. That prefix should give anyone, myself included, a quick and clear understanding of the module we are examining and will allow me to easily reference the relevant file in the future. It's a small change, but it's a huge help in maintaining and navigating this codebase, isn't it?
|
| 606/5 |
2026/09/09 18:56 |
tool |
git-log |
0m
Args: map[CodeRegexp:def_reserved_size_ops PathPrefix:drivers/scsi/sg.c]
Results: map[Output:d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
]
|
| 607/5 |
2026/09/09 18:56 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 18545
output: 27
thoughts: 20
Thoughts: Okay, let's dive into commit `d06a310b45e1`. I need to understand what changed, and how it impacts the existing codebase. My initial assessment is that I need to quickly grasp the context. What problem was this commit trying to solve? What were the previous limitations? Are there any potential ripple effects I should be immediately aware of?
Now, I'm going to look at the diffs. I need to pay particular attention to:
* **Significant code blocks:** Any major function changes, new classes, or substantial modifications to existing structures immediately grab my attention.
* **API modifications:** Did this commit change any public interfaces? That's critical for compatibility. I need to check for any deprecation notices or, worse, breaking changes.
* **Performance implications:** Does the change introduce any new algorithms or data structures that could affect performance, particularly in critical paths? I'll be looking for changes in time or space complexity.
* **Error handling and logging:** Are there any improvements in these areas? Robust error handling and good logging are essential, especially in production environments.
* **Testing:** Did the commit include new unit tests or integration tests? The presence of tests is a strong indicator of the author's confidence in the changes and gives me confidence in the quality. If there are no tests, that’s a red flag.
* **Dependencies:** Did the commit introduce any new dependencies or version changes to existing dependencies?
I'll quickly scan the code to identify potential edge cases that I need to investigate in more detail. I'm going to leverage my existing knowledge of the codebase, the domain, and any related architectural principles to rapidly synthesize the changes. My goal is to determine if this commit is sound, well-designed, and aligns with the project's overall goals. I need to assess how seamlessly this change integrates with my existing mental model of the system.
|
| 608/5 |
2026/09/09 18:56 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 609/5 |
2026/09/09 18:56 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 20312
output: 36
thoughts: 89
Thoughts: Okay, here's my assessment of this code snippet, expressed as if it's my own thought process:
**A Familiar Pattern Emerges**
Hmm, let's see. My initial thought is to examine commit `d06a310b45e1`. *Aha!* It looks like they've done precisely what I suspected might be the correct approach. They've essentially converted a `module_param_named` into a `module_param_cb` setup for `def_reserved_size`. And crucially, this includes a setter function that performs *validation* of the bounds. That's precisely the kind of robust design I'm looking for here to ensure the parameter's integrity. Good show!
Now, I'm getting a hunch and I think I'll go further and look through the commit history for `scatter_elem_sz` in the `drivers/scsi/sg.c` directory as well. I want to see if this pattern is re-used, and if I can glean anything more from the history.
|
| 610/5 |
2026/09/09 18:56 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 611/5 |
2026/09/09 18:56 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 20727
output: 27
thoughts: 52
Thoughts: Okay, here's my interpretation of those commands, presented as my own thought process, assuming I'm well-versed in version control:
**Investigating Recent Code Changes**
Right, let's dive in. I need to get a clear picture of what's been happening in the codebase recently. My immediate focus is on understanding the impact of specific commits. To that end, I want to take a look at the changes introduced by commit `6460e75a104d`. I could use `git show 6460e75a104d` to view the commit's metadata (author, date, message) alongside the diff, or perhaps just the changes themselves. Also, since I'm here, I might as well check out the state of commit `10db10d144c0` as well. Seeing these two commits side-by-side should provide a useful frame of reference, so I'll probably look at them in that order. I want to build a narrative of the history here, not just see diffs in isolation. Gotta get a good grip on the context, so I'll be sure to inspect the message of the first commit before I go to the next.
|
| 612/5 |
2026/09/09 18:56 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 613/5 |
2026/09/09 18:56 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 25479
output: 26
thoughts: 1497
Thoughts: **Analyzing the sg Driver's Scatter-Gather Element Size Logic**
Okay, let's break this down. That commit 6460e75a104d, it's the key. I see `scatter_elem_sz` and `scatter_elem_sz_prev` were introduced way back in 2006. My first thought is, why the `_prev` variable? I need to understand that.
Looking at the code, it's immediately clear that there's a check: `if (unlikely(num != scatter_elem_sz_prev))`. That's the core. If they're different, it means the user's tweaked something through sysfs (`/sys/module/sg/parameters/scatter_elem_sz`). Then, it's either setting `scatter_elem_sz` to `PAGE_SIZE` (if the new value is less), or just updating `scatter_elem_sz_prev`. The second snippet appears to automatically adjust `scatter_elem_sz` to be the power-of-two allocation size that was actually allocated. This is due to the `alloc_pages` call rounding the requested size up.
The commit description confirms this: the driver's rounding up to the max of the user's value and `PAGE_SIZE`, ensuring it's a power of two. So, `scatter_elem_sz_prev` is essentially caching the *last* valid value of `scatter_elem_sz`, and this is how it detects changes. Clever.
However, a red flag immediately pops up. `scatter_elem_sz` is global, and it looks like multiple threads are accessing it simultaneously – through the /dev/sg* device files and sysfs – with *no locks*. That is a serious concurrency issue; it's practically a race condition waiting to happen!
Now, digging deeper into `sg_build_indirect`, I see that the code uses `get_order(num)` to calculate `ret_sz`. This calculates the order for `alloc_pages`. The critical point is that, even if `order` is decremented on retry, which recalculates `ret_sz`, the code still *subtracts* this `ret_sz` from `rem_sz` in the main loop. So, it seems to allocate pages of order ( `ret_sz = PAGE_SIZE << order`).
The original code's behavior: I'm tracing the value of `num`. It's used in the `if (num == scatter_elem_sz_prev)` condition and for logging, but crucially, it was also used as the argument to the old `sg_page_malloc` function, *before* commit `10db10d144c0` replaced it. I need to go back and examine that older version to fully understand what's changed.
|
| 614/5 |
2026/09/09 18:57 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 615/5 |
2026/09/09 18:57 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 37271
output: 21
thoughts: 2979
Thoughts: **Analyzing the SG Driver's Indirect Scatter-Gather Build**
Okay, so I've been diving into this `sg_build_indirect` function and trying to wrap my head around this UBSAN issue. It looks like commit `10db10d144c0` was the pivotal moment, rewriting the allocation strategy. Before that, we had page allocation per element, but now we're dealing with a single `page_order` for the whole scatter-gather list (`schp`). That `ret_sz` calculation based on the single `order` looks suspicious, especially given the `rem_sz` decrement within the loop.
The initial fix suggested, updating the local `num` and bounding the `order`, feels like a band-aid. But, based on the `scatter_elem_sz_prev` logic, it looks vestigial, as `ret_sz` already encapsulates the page size calculation!
The root cause, as I understand it, is that setting `scatter_elem_sz` to `0` leads to a massive shift (1 << 64) due to `get_order(0)` underflowing and causing a shift-out-of-bounds error. The user is able to change this through `/sys/module/sg/parameters/scatter_elem_sz`
The critical bit now is to analyze the proposed patch diff, and ensure we're getting a true fix, and not a band-aid.
The proposed patch diff removes `scatter_elem_sz_prev` entirely, which is good. However, I have to ensure that removing that variable is sound, and that the new `scatter_elem_sz_set` implementation doesn't introduce any new issues.
The `scatter_elem_sz_set` function seems good. It introduces a `kstrtoint` which is also valid and is in the correct range, but I need to make sure this prevents the crash. What is `PAGE_SIZE << MAX_PAGE_ORDER`? What's the maximum page order? I need to check the kernel definitions to be certain. The range check in `scatter_elem_sz_set` looks like it's guarding against the shift-out-of-bounds problem. It prevents the `order` from becoming excessively large. The old approach did not prevent large values! This is a much better, architectural fix than the proposed fix in the root cause explanation.
|
| 616/5 |
2026/09/09 18:57 |
tool |
grepper |
0m
Args: map[Expression:#define MAX_PAGE_ORDER]
Results: map[Output:include/linux/mmzone.h-30-#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h:31:#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
--
tools/perf/builtin-kmem.c=284=static struct perf_session *kmem_session;
--
tools/perf/builtin-kmem.c-286-#define MAX_MIGRATE_TYPES 6
tools/perf/builtin-kmem.c:287:#define MAX_PAGE_ORDER 11
tools/perf/builtin-kmem.c-288-
--
tools/testing/memblock/linux/mmzone.h=16=enum zone_type {
--
tools/testing/memblock/linux/mmzone.h-20-#define MAX_NR_ZONES __MAX_NR_ZONES
tools/testing/memblock/linux/mmzone.h:21:#define MAX_PAGE_ORDER 10
tools/testing/memblock/linux/mmzone.h-22-#define MAX_ORDER_NR_PAGES (1 << MAX_PAGE_ORDER)
--
tools/testing/vma/linux/mmzone.h=16=enum zone_type {
--
tools/testing/vma/linux/mmzone.h-20-#define MAX_NR_ZONES __MAX_NR_ZONES
tools/testing/vma/linux/mmzone.h:21:#define MAX_PAGE_ORDER 10
tools/testing/vma/linux/mmzone.h-22-#define MAX_ORDER_NR_PAGES (1 << MAX_PAGE_ORDER)
--
tools/testing/vsock/vsock_test.c=1661=static void test_stream_msgzcopy_leak_errq_server(const struct test_opts *opts)
--
tools/testing/vsock/vsock_test.c-1741- */
tools/testing/vsock/vsock_test.c:1742:#define MAX_PAGE_ORDER 10 /* usually */
tools/testing/vsock/vsock_test.c-1743-#define PAGE_SIZE 4096
]
|
| 617/5 |
2026/09/09 18:57 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 41370
output: 34
thoughts: 51
Thoughts: Okay, here's my thought process on that:
**Investigating SCSI SG Driver Memory Management**
Alright, time to dig into the SCSI generic driver (`drivers/scsi/sg.c`). I need to quickly determine whether it's directly using memory management structures from the kernel. Specifically, I want to confirm if it includes either `<linux/mmzone.h>` or `<linux/mm.h>`. It's a fundamental part of understanding how this driver interacts with system memory and how it handles potential memory-related issues. So, step one, let's just go straight to the file and look at the includes. It's the fastest way to get a quick answer. Then I'll have a clear starting point for any deeper analysis if I need it.
|
| 618/5 |
2026/09/09 18:57 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1 LineCount:60]
Results: map[Contents: 1: // SPDX-License-Identifier: GPL-2.0-or-later
2: /*
3: * History:
4: * Started: Aug 9 by Lawrence Foard (entropy@world.std.com),
5: * to allow user process control of SCSI devices.
6: * Development Sponsored by Killy Corp. NY NY
7: *
8: * Original driver (sg.c):
9: * Copyright (C) 1992 Lawrence Foard
10: * Version 2 and 3 extensions to driver:
11: * Copyright (C) 1998 - 2014 Douglas Gilbert
12: */
13:
14: static int sg_version_num = 30536; /* 2 digits for each component */
15: #define SG_VERSION_STR "3.5.36"
16:
17: /*
18: * D. P. Gilbert (dgilbert@interlog.com), notes:
19: * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
20: * the kernel/module needs to be built with CONFIG_SCSI_LOGGING
21: * (otherwise the macros compile to empty statements).
22: *
23: */
24: #include <linux/module.h>
25:
26: #include <linux/fs.h>
27: #include <linux/kernel.h>
28: #include <linux/sched.h>
29: #include <linux/string.h>
30: #include <linux/mm.h>
31: #include <linux/errno.h>
32: #include <linux/mtio.h>
33: #include <linux/ioctl.h>
34: #include <linux/major.h>
35: #include <linux/slab.h>
36: #include <linux/fcntl.h>
37: #include <linux/init.h>
38: #include <linux/poll.h>
39: #include <linux/moduleparam.h>
40: #include <linux/cdev.h>
41: #include <linux/idr.h>
42: #include <linux/seq_file.h>
43: #include <linux/blkdev.h>
44: #include <linux/delay.h>
45: #include <linux/blktrace_api.h>
46: #include <linux/mutex.h>
47: #include <linux/atomic.h>
48: #include <linux/ratelimit.h>
49: #include <linux/uio.h>
50: #include <linux/cred.h> /* for sg_check_file_access() */
51:
52: #include <scsi/scsi.h>
53: #include <scsi/scsi_cmnd.h>
54: #include <scsi/scsi_dbg.h>
55: #include <scsi/scsi_device.h>
56: #include <scsi/scsi_driver.h>
57: #include <scsi/scsi_eh.h>
58: #include <scsi/scsi_host.h>
59: #include <scsi/scsi_ioctl.h>
60: #include <scsi/scsi_tcq.h>
]
|
| 619/5 |
2026/09/09 18:57 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 42582
output: 35
thoughts: 964
Thoughts: **Analyzing Scatter Element Size in the Linux Kernel**
Okay, so I'm diving into this code, and it starts by including `<linux/mm.h>`, which pulls in `<linux/mmzone.h>`. Hmm, what's `MAX_PAGE_ORDER` in `<linux/mmzone.h>`? Ah, it's usually 10, meaning `PAGE_SIZE << MAX_PAGE_ORDER` is typically 4MB (4096 << 10). But wait, I need to be absolutely sure about the range here.
Let's see, can `PAGE_SIZE << MAX_PAGE_ORDER` potentially cause an integer overflow? `PAGE_SIZE` is at least 4096 (12 bits), and `MAX_PAGE_ORDER` is around 10. That's 12 + 10 = 22 bits. Even if we consider a 64KB page size (16 bits) and keep `MAX_PAGE_ORDER` at 10, we're at 26 bits. Since `int` has 31 positive bits, this looks safe.
Now, what if `size` is larger than `PAGE_SIZE << MAX_PAGE_ORDER`? And what if `size` is an `int`? What if it's negative, even? I see `kstrtoint(val, 0, &size);` being used. Okay, if `size < PAGE_SIZE`, it returns `-ERANGE`. So negative values will be caught by `size < PAGE_SIZE` and handled correctly.
What about `size == 0`? The same logic applies: `0 < PAGE_SIZE` also triggers `-ERANGE`. Good, so we're covered for that.
If `size` is positive, greater than or equal to `PAGE_SIZE`, and less than or equal to `PAGE_SIZE << MAX_PAGE_ORDER`, then `scatter_elem_sz = size;`. But wait, what if the user passes `scatter_elem_sz` on the kernel command line or when loading a module? We need to verify that!
Okay, it looks like `module_param_cb` is used here. Does `scatter_elem_sz_set` get called for module parameters passed at boot or module load time? Yes, it seems so! `module_param_cb` registers kernel_param_ops whose `.set` callback is invoked by `parse_args` at boot/load time when `sg.scatter_elem_sz=...` is passed!
Now, what if the user *doesn't* pass `scatter_elem_sz`? What's the initial value? I see `static int scatter_elem_sz = SG_SCATTER_SZ;` on line 94. What is `SG_SCATTER_SZ` defined as? It's `#define SG_SCATTER_SZ (8 * 4096)` = 32768.
Hold on, what if `PAGE_SIZE` is *larger* than `SG_SCATTER_SZ`? E.g., on a 64KB page size system like ARM64 or PowerPC? Let's look at `init_sg`:
```c
if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
```
Ah, right! If `PAGE_SIZE` is 64KB, and `SG_SCATTER_SZ` (32KB) is indeed less than `PAGE_SIZE` (64KB), then `init_sg` adjusts `scatter_elem_sz` to be equal to `PAGE_SIZE`.
Okay, but what if the user loaded the module or booted with `sg.scatter_elem_sz=8192` on a 64KB page system?
`scatter_elem_sz_set` checks:
```c
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
```
On a 64KB page system, 8192 is indeed less than 65536, so `-ERANGE` is returned, and it's rejected. So, that's taken care of.
What about a user booting with `sg.scatter_elem_sz=131072`? That falls within the valid range: `>= PAGE_SIZE` and `<= (PAGE_SIZE << MAX_PAGE_ORDER)`.
Wait! What if size is NOT a power of 2? Let's check! What does `get_order(scatter_elem_sz)` do if `scatter_elem_sz`
|
| 620/5 |
2026/09/09 18:57 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c Name:get_order]
Results: map[SourceCode: 10: /**
11: * get_order - Determine the allocation order of a memory size
12: * @size: The size for which to get the order
13: *
14: * Determine the allocation order of a particular sized block of memory. This
15: * is on a logarithmic scale, where:
16: *
17: * 0 -> 2^0 * PAGE_SIZE and below
18: * 1 -> 2^1 * PAGE_SIZE to 2^0 * PAGE_SIZE + 1
19: * 2 -> 2^2 * PAGE_SIZE to 2^1 * PAGE_SIZE + 1
20: * 3 -> 2^3 * PAGE_SIZE to 2^2 * PAGE_SIZE + 1
21: * 4 -> 2^4 * PAGE_SIZE to 2^3 * PAGE_SIZE + 1
22: * ...
23: *
24: * The order returned is used to find the smallest allocation granule required
25: * to hold an object of the specified size.
26: *
27: * The result is undefined if the size is 0.
28: */
29: static __always_inline __attribute_const__ int get_order(unsigned long size)
30: {
31: if (__builtin_constant_p(size)) {
32: if (!size)
33: return BITS_PER_LONG - PAGE_SHIFT;
34:
35: if (size < (1UL << PAGE_SHIFT))
36: return 0;
37:
38: return ilog2((size) - 1) - PAGE_SHIFT + 1;
39: }
40:
41: size--;
42: size >>= PAGE_SHIFT;
43: #if BITS_PER_LONG == 32
44: return fls(size);
45: #else
46: return fls64(size);
47: #endif
48: }
SourceFile:include/asm-generic/getorder.h]
|
| 621/5 |
2026/09/09 18:57 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 45198
output: 36
thoughts: 356
Thoughts: **Analyzing the `get_order(size)` Function**
Okay, let's break down how this `get_order` function works. I need to really understand the implications here. First, let's consider the simplest cases. If `size` is equal to `PAGE_SIZE`, after decrementing, shifting, and taking the floor of the logarithm base 2, the order should be 0. Makes sense. If `size` is `PAGE_SIZE + 1`, after the same operations, the order ends up as 1. So far, so good.
Now, let's look at the edge case when `size` is equal to `PAGE_SIZE` shifted left by `MAX_PAGE_ORDER`. Let's say, for example, `PAGE_SIZE` is 4096 and `MAX_PAGE_ORDER` is 10. That makes `size` 4MB. Decrementing `size`, we get 4MB - 1, and then right-shifting by `PAGE_SHIFT` we are left with 1023. `fls(1023)` then gives us 10, which matches `MAX_PAGE_ORDER`. But, what if the input `size` exactly equals `PAGE_SIZE` shifted left by `MAX_PAGE_ORDER`? Does `get_order` return `MAX_PAGE_ORDER`? Yes, it does.
This leads to a key question: can `alloc_pages(gfp_mask, MAX_PAGE_ORDER)` ever actually succeed? Intuitively, it should, because the valid orders supported by the page allocator are `0` through `MAX_PAGE_ORDER`. Let's confirm that by searching the kernel for places where `alloc_pages` is used, or where `MAX_PAGE_ORDER` is referenced, probably in `mm/page_alloc.c` to see if that's indeed the case. I need to make sure this is all consistent with the underlying memory management structure.
|
| 622/5 |
2026/09/09 18:57 |
tool |
grepper |
0m
Args: map[Expression:WARN_ON_ONCE\(order > MAX_PAGE_ORDER PathPrefix:mm/]
Results: map[Output:mm/page_alloc.c=6445=void free_reserved_pages(struct page *page, unsigned int order)
--
mm/page_alloc.c-6450- VM_WARN_ON_ONCE(!IS_ALIGNED(page_to_pfn(page), nr_pages));
mm/page_alloc.c:6451: VM_WARN_ON_ONCE(order > MAX_PAGE_ORDER);
mm/page_alloc.c-6452-
--
mm/vmstat.c=1114=static int __fragmentation_index(unsigned int order, struct contig_page_info *info)
--
mm/vmstat.c-1117-
mm/vmstat.c:1118: if (WARN_ON_ONCE(order > MAX_PAGE_ORDER))
mm/vmstat.c-1119- return 0;
]
|
| 623/5 |
2026/09/09 18:57 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 46251
output: 33
thoughts: 27
Thoughts: Okay, let's dive into this. Here's how I'd approach this, thinking out loud:
**Deconstructing `alloc_pages` Order Limits in `mm/page_alloc.c`**
Alright, I'm digging into `mm/page_alloc.c` again. I need to refresh my memory, or maybe confirm a hunch, about the maximum order `alloc_pages` allows. I know it's a critical parameter influencing memory allocation granularity, which directly impacts fragmentation and overall system performance, so I should know this cold. I want to be certain about the largest block size `alloc_pages` can hand out. I'll need to go spelunking in the source code to get the answer, or at least confirm what I already know. Let me see where I left off last time I reviewed it...
|
| 624/5 |
2026/09/09 18:57 |
tool |
grepper |
0m
Args: map[Expression:> MAX_PAGE_ORDER PathPrefix:mm/page_alloc.c]
Results: map[Output:mm/page_alloc.c=2055=static unsigned long find_large_buddy(unsigned long start_pfn)
--
mm/page_alloc.c-2068- /* Nothing found */
mm/page_alloc.c:2069: if (++order > MAX_PAGE_ORDER)
mm/page_alloc.c-2070- return start_pfn;
--
mm/page_alloc.c=5330=static inline bool alloc_order_allowed(gfp_t gfp, unsigned int order,
--
mm/page_alloc.c-5339- */
mm/page_alloc.c:5340: return !(WARN_ON_ONCE_GFP(order > MAX_PAGE_ORDER, gfp));
mm/page_alloc.c-5341-}
--
mm/page_alloc.c=6445=void free_reserved_pages(struct page *page, unsigned int order)
--
mm/page_alloc.c-6450- VM_WARN_ON_ONCE(!IS_ALIGNED(page_to_pfn(page), nr_pages));
mm/page_alloc.c:6451: VM_WARN_ON_ONCE(order > MAX_PAGE_ORDER);
mm/page_alloc.c-6452-
]
|
| 625/5 |
2026/09/09 18:57 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 46824
output: 21
thoughts: 362
Thoughts: **Analyzing Potential Overflow in `sg_build_indirect`**
Okay, so the initial check `alloc_order_allowed` tells me that we're good as long as `order` is less than or equal to `MAX_PAGE_ORDER`. That's the baseline.
Now, I'm digging into `sg_build_indirect`. I see `order = get_order(scatter_elem_sz);` and then, the crucial line: `ret_sz = 1 << (PAGE_SHIFT + order);`. Hold on a second... what's going on here with that left shift? Specifically, I'm thinking about integer overflow here. Could `1 << (PAGE_SHIFT + order)` result in something that's too big?
Let's break this down. First, what's `PAGE_SHIFT + order`? On x86_64, `PAGE_SHIFT` is 12, and we know that the maximum allowed `order` is, well, `MAX_PAGE_ORDER`, which is 10. So, 12 + 10 = 22. That means we're doing `1 << 22`, which is 4MB. That fits *easily* in a signed 32-bit integer, and I know from working with similar code that this is a safe operation here.
But what about other architectures? Suppose `PAGE_SHIFT` is 16 (64KB pages) and `MAX_PAGE_ORDER` is still 10? Then we have 16 + 10 = 26, which is `1 << 26`, and that's 64MB. Still good, still fits in a 32-bit int.
But, I'd like to be certain there's no way this overflows on *any* architecture. To be totally safe, I need to know the largest possible value of `PAGE_SHIFT + MAX_PAGE_ORDER` across all Linux architectures. I'll need to check the Kconfig files or the arch headers for `CONFIG_ARCH_FORCE_MAX_ORDER` to ensure it can't overflow. It's a question I can quickly check, so let's get that done.
|
| 626/5 |
2026/09/09 18:57 |
tool |
grepper |
0m
Args: map[Expression:ARCH_FORCE_MAX_ORDER]
Results: map[Output:arch/arc/Kconfig=555=endmenu # "ARC Architecture Configuration"
arch/arc/Kconfig-556-
arch/arc/Kconfig:557:config ARCH_FORCE_MAX_ORDER
arch/arc/Kconfig-558- int "Maximum zone order"
--
arch/arm/Kconfig=1275=config ARM_MODULE_PLTS
--
arch/arm/Kconfig-1292-
arch/arm/Kconfig:1293:config ARCH_FORCE_MAX_ORDER
arch/arm/Kconfig-1294- int "Order of maximal physically contiguous allocations"
--
arch/arm/configs/imx_v6_v7_defconfig=33=CONFIG_HIGHMEM=y
arch/arm/configs/imx_v6_v7_defconfig:34:CONFIG_ARCH_FORCE_MAX_ORDER=13
arch/arm/configs/imx_v6_v7_defconfig-35-CONFIG_CMDLINE="noinitrd console=ttymxc0,115200"
--
arch/arm/configs/milbeaut_m10v_defconfig=28=CONFIG_HIGHMEM=y
arch/arm/configs/milbeaut_m10v_defconfig:29:CONFIG_ARCH_FORCE_MAX_ORDER=11
arch/arm/configs/milbeaut_m10v_defconfig-30-CONFIG_SECCOMP=y
--
arch/arm/configs/pxa_defconfig=18=CONFIG_ARCH_PXA=y
arch/arm/configs/pxa_defconfig:19:CONFIG_ARCH_FORCE_MAX_ORDER=8
arch/arm/configs/pxa_defconfig-20-CONFIG_CMDLINE="root=/dev/ram0 ro"
--
arch/arm/configs/sama7_defconfig=17=CONFIG_ATMEL_CLOCKSOURCE_TCB=y
--
arch/arm/configs/sama7_defconfig-20-# CONFIG_CPU_SW_DOMAIN_PAN is not set
arch/arm/configs/sama7_defconfig:21:CONFIG_ARCH_FORCE_MAX_ORDER=14
arch/arm/configs/sama7_defconfig-22-CONFIG_UACCESS_WITH_MEMCPY=y
--
arch/arm/configs/sp7021_defconfig=19=CONFIG_THUMB2_KERNEL=y
arch/arm/configs/sp7021_defconfig:20:CONFIG_ARCH_FORCE_MAX_ORDER=11
arch/arm/configs/sp7021_defconfig-21-CONFIG_VFP=y
--
arch/arm64/Kconfig=1731=config XEN
--
arch/arm64/Kconfig-1749-# 64K | 29 | 16 | 13 | 13 |
arch/arm64/Kconfig:1750:config ARCH_FORCE_MAX_ORDER
arch/arm64/Kconfig-1751- int
--
arch/loongarch/Kconfig=563=config NODES_SHIFT
--
arch/loongarch/Kconfig-567-
arch/loongarch/Kconfig:568:config ARCH_FORCE_MAX_ORDER
arch/loongarch/Kconfig-569- int "Maximum zone order"
--
arch/m68k/Kconfig.cpu=400=config SINGLE_MEMORY_CHUNK
--
arch/m68k/Kconfig.cpu-411-
arch/m68k/Kconfig.cpu:412:config ARCH_FORCE_MAX_ORDER
arch/m68k/Kconfig.cpu-413- int "Order of maximal physically contiguous allocations" if ADVANCED
--
arch/mips/Kconfig=2106=config ZBOOT_LOAD_ADDRESS
--
arch/mips/Kconfig-2115-
arch/mips/Kconfig:2116:config ARCH_FORCE_MAX_ORDER
arch/mips/Kconfig-2117- int "Maximum zone order"
--
arch/nios2/Kconfig=48=source "kernel/Kconfig.hz"
arch/nios2/Kconfig-49-
arch/nios2/Kconfig:50:config ARCH_FORCE_MAX_ORDER
arch/nios2/Kconfig-51- int "Order of maximal physically contiguous allocations"
--
arch/powerpc/Kconfig=897=config DATA_SHIFT
--
arch/powerpc/Kconfig-918-
arch/powerpc/Kconfig:919:config ARCH_FORCE_MAX_ORDER
arch/powerpc/Kconfig-920- int "Order of maximal physically contiguous allocations"
--
arch/powerpc/configs/85xx/ge_imp3a_defconfig=31=CONFIG_MATH_EMULATION=y
arch/powerpc/configs/85xx/ge_imp3a_defconfig:32:CONFIG_ARCH_FORCE_MAX_ORDER=16
arch/powerpc/configs/85xx/ge_imp3a_defconfig-33-CONFIG_PCI=y
--
arch/powerpc/configs/fsl-emb-nonhw.config=41=CONFIG_FONTS=y
arch/powerpc/configs/fsl-emb-nonhw.config:42:CONFIG_ARCH_FORCE_MAX_ORDER=12
arch/powerpc/configs/fsl-emb-nonhw.config-43-CONFIG_FRAMEBUFFER_CONSOLE=y
--
arch/sh/configs/ecovec24_defconfig=9=CONFIG_CPU_SUBTYPE_SH7724=y
arch/sh/configs/ecovec24_defconfig:10:CONFIG_ARCH_FORCE_MAX_ORDER=11
arch/sh/configs/ecovec24_defconfig-11-CONFIG_MEMORY_SIZE=0x10000000
--
arch/sh/mm/Kconfig=28=config PAGE_OFFSET
--
arch/sh/mm/Kconfig-32-
arch/sh/mm/Kconfig:33:config ARCH_FORCE_MAX_ORDER
arch/sh/mm/Kconfig-34- int "Order of maximal physically contiguous allocations"
--
arch/sparc/Kconfig=276=config ARCH_SPARSEMEM_DEFAULT
--
arch/sparc/Kconfig-278-
arch/sparc/Kconfig:279:config ARCH_FORCE_MAX_ORDER
arch/sparc/Kconfig-280- int "Order of maximal physically contiguous allocations"
--
arch/xtensa/Kconfig=775=config HIGHMEM
--
arch/xtensa/Kconfig-794-
arch/xtensa/Kconfig:795:config ARCH_FORCE_MAX_ORDER
arch/xtensa/Kconfig-796- int "Order of maximal physically contiguous allocations"
--
include/linux/mmzone.h-29-/* Free memory management - zoned buddy allocator. */
include/linux/mmzone.h:30:#ifndef CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-31-#define MAX_PAGE_ORDER 10
include/linux/mmzone.h-32-#else
include/linux/mmzone.h:33:#define MAX_PAGE_ORDER CONFIG_ARCH_FORCE_MAX_ORDER
include/linux/mmzone.h-34-#endif
--
mm/Kconfig=1084=config CMA_AREAS
--
mm/Kconfig-1099-#
mm/Kconfig:1100:config ARCH_FORCE_MAX_ORDER
mm/Kconfig-1101- int
--
mm/Kconfig-1103-#
mm/Kconfig:1104:# When ARCH_FORCE_MAX_ORDER is not defined,
mm/Kconfig-1105-# the default page block order is MAX_PAGE_ORDER (10) as per
--
mm/Kconfig=1108=config PAGE_BLOCK_MAX_ORDER
mm/Kconfig-1109- int "Page Block Order Upper Limit"
mm/Kconfig:1110: range 1 10 if ARCH_FORCE_MAX_ORDER = 0
mm/Kconfig:1111: default 10 if ARCH_FORCE_MAX_ORDER = 0
mm/Kconfig:1112: range 1 ARCH_FORCE_MAX_ORDER if ARCH_FORCE_MAX_ORDER != 0
mm/Kconfig:1113: default ARCH_FORCE_MAX_ORDER if ARCH_FORCE_MAX_ORDER != 0
mm/Kconfig-1114- help
--
mm/Kconfig-1117- them. The maximum size of the page block order is at least limited by
mm/Kconfig:1118: ARCH_FORCE_MAX_ORDER/MAX_PAGE_ORDER.
mm/Kconfig-1119-
--
mm/Kconfig-1121- order when the page block order is required to be smaller than
mm/Kconfig:1122: ARCH_FORCE_MAX_ORDER/MAX_PAGE_ORDER or other limits
mm/Kconfig-1123- (see include/linux/pageblock-flags.h for details).
--
scripts/gdb/linux/constants.py.in=150=if IS_BUILTIN(CONFIG_ARM64):
--
scripts/gdb/linux/constants.py.in-152- LX_VALUE(CONFIG_ARM64_VA_BITS)
scripts/gdb/linux/constants.py.in:153: LX_VALUE(CONFIG_ARCH_FORCE_MAX_ORDER)
scripts/gdb/linux/constants.py.in-154-LX_VALUE(CONFIG_PAGE_SHIFT)
--
scripts/gdb/linux/mm.py=203=class aarch64_page_ops():
--
scripts/gdb/linux/mm.py-234-
scripts/gdb/linux/mm.py:235: if str(constants.LX_CONFIG_ARCH_FORCE_MAX_ORDER).isdigit():
scripts/gdb/linux/mm.py:236: self.MAX_ORDER = constants.LX_CONFIG_ARCH_FORCE_MAX_ORDER
scripts/gdb/linux/mm.py-237- else:
]
|
| 627/5 |
2026/09/09 18:57 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 50231
output: 37
thoughts: 483
Thoughts: **Analyzing Potential Integer Overflow in `sg_build_indirect`**
Okay, let's break this down. `MAX_PAGE_ORDER` is capped at 16, and on powerpc with 4k pages, that means 28 bits total. Since the text says it never exceeds 30, that's fine. Therefore, `(PAGE_SIZE << MAX_PAGE_ORDER)` definitely fits in an `int`, no problem there. And because `order = get_order(scatter_elem_sz)` will always be less than or equal to `MAX_PAGE_ORDER`, then `ret_sz = 1 << (PAGE_SHIFT + order)` is also guaranteed to not overflow an `int`. So far, so good.
But wait a minute... I need to look closely at the loop, specifically this line: `num = min(rem_sz, ret_sz);`. That `num` variable... what's it used for? Before any patches, let's see how `num` was handled.
Looking at the original code block...
```c
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
scatter_elem_sz = ret_sz;
scatter_elem_sz_prev = ret_sz;
}
}
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
```
... it seems `num` was used in two places:
1. It checked if `num` was equal to `scatter_elem_sz_prev`, and if so it potentially updated `scatter_elem_sz` and `scatter_elem_sz_prev`.
2. It printed the values of `k`, `num`, and `ret_sz` inside of the `SCSI_LOG_TIMEOUT` statement.
Okay, that's it! `num` wasn't being used in any allocation calculations or anything like that. However, this requires a deeper check: I need to verify that `num` isn't used *anywhere else* in `sg_build_indirect`. I need to review the entire `sg_build_indirect` function to be absolutely sure.
|
| 628/5 |
2026/09/09 18:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c Name:sg_build_indirect]
Results: map[SourceCode:1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
SourceFile:drivers/scsi/sg.c]
|
| 629/5 |
2026/09/09 18:58 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 52692
output: 21
thoughts: 165
Thoughts: **Understanding the Variable 'num'**
Okay, so I was looking at this code and initially thought `num` was just used for a single purpose, a bit simplistic. But hang on, let's zoom in... Ah, the key is right here: `num = min(rem_sz, ret_sz);`. That makes perfect sense! `num` isn't just a generic counter; it *specifically* represents the useful byte length within each chunk. It's the minimum of the remaining size (`rem_sz`) and the current chunk size (`ret_sz`). So, in the log statement, `SCSI_LOG_TIMEOUT`, when it prints `num`, it's providing the *actual* amount of data being processed in this particular segment. That's good, clear, and relevant information for debugging timeouts.
Now, let's step back a bit and consider `scatter_elem_sz_prev`. I need to figure out how this is used, whether there's some connection with `num` or it's completely separate. Let's go ahead and quickly use `grepper` to see where `scatter_elem_sz_prev` is referenced in the whole kernel, which should paint the whole picture.
|
| 630/5 |
2026/09/09 18:58 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz_prev]
Results: map[Output:drivers/scsi/sg.c=94=static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1671- scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1876- num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c-1879- scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1901- scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 631/5 |
2026/09/09 18:58 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 53807
output: 33
thoughts: 713
Thoughts: **Analyzing the Impact of Removing `scatter_elem_sz_prev`**
Okay, so I'm looking at this patch and it completely removes `scatter_elem_sz_prev`, which I know was only used in `sg.c`, specifically around those lines. My first instinct is to confirm the scope, so let's dig into the code.
In `sg.c`, I see `static int scatter_elem_sz = SG_SCATTER_SZ;` and, indeed, the immediate next line is `-static int scatter_elem_sz_prev = SG_SCATTER_SZ;`. So it's precisely where I thought it was.
Looking at `init_sg`, the code had this logic:
```diff
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
```
My brain is immediately jumping to a potential corner case: what if `scatter_elem_sz` *somehow* ended up being greater than `(PAGE_SIZE << MAX_PAGE_ORDER)` within `init_sg`? That's the first question I need to answer.
Let's do some quick math: `SG_SCATTER_SZ` is 32768, `PAGE_SIZE` is at least 4096, and `MAX_PAGE_ORDER` is at least 8. So `4096 << 8` gives me 1048576, which is way larger than 32768. Hmm, that seems unlikely as the default, but I need to consider all the possibilities.
Now I'm thinking about module parameters and kernel boot parameters. Could someone set `sg.scatter_elem_sz` to some crazy value as a boot parameter?
Wait, yes! Module parameters are parsed with a callback, `module_param_cb`. Let me verify this. When I boot the kernel with something like `sg.scatter_elem_sz=999999999`, the parameters will be parsed by `parse_args` which calls `parse_one` and then calls `param_ops->set(...)`. Now, if the `scatter_elem_sz_set` function detects an error, such as `-ERANGE`, then `parse_one` and the kernel will see this error!
So, the next question is: if it's initialized to `SG_SCATTER_SZ`, which is 32KB, what happens in `init_sg()`? It checks `if (scatter_elem_sz < PAGE_SIZE) scatter_elem_sz = PAGE_SIZE;`.
This eliminates the potential of ever having `scatter_elem_sz > (PAGE_SIZE << MAX_PAGE_ORDER)` at the `init_sg` function! This is because, either it's initialized to the default value, or the parameter was validated by `scatter_elem_sz_set`:
```c
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)) return -ERANGE;
```
Okay, so I'm feeling a bit better, but I'm not done. I should absolutely check: Can `scatter_elem_sz` be modified anywhere *else* in `sg.c`? Gotta be thorough. So, let's look at every single occurrence of `scatter_elem_sz` in `drivers/scsi/sg.c` to be completely certain.
|
| 632/5 |
2026/09/09 18:58 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz PathPrefix:drivers/scsi/sg.c]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 633/5 |
2026/09/09 18:58 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 56362
output: 19
thoughts: 34
Thoughts: Okay, here's my interpretation of those thoughts, summarized from my perspective as a SCSI expert:
**Investigating `scatter_elem_sz` Usage in the procfs Context**
Hmm, I'm trying to figure out if `scatter_elem_sz` is actually utilized within the procfs interface in the SCSI subsystem. The first place I'd look is probably within the `sg_proc_init` function, or any related initialization routines. Beyond that, I need to thoroughly search the `drivers/scsi/` directory to see if this variable plays a role anywhere else in the code. I need to understand its scope and function to evaluate its impact, particularly within the context of reporting SCSI data through the procfs filesystem. I need to ensure my understanding of this field is correct. This is key to ensuring proper implementation within the kernel.
|
| 634/5 |
2026/09/09 18:58 |
tool |
grepper |
0m
Args: map[Expression:scatter_elem_sz]
Results: map[Output:drivers/scsi/sg.c=92=static int sg_allow_dio = SG_ALLOW_DIO_DEF;
drivers/scsi/sg.c-93-
drivers/scsi/sg.c:94:static int scatter_elem_sz = SG_SCATTER_SZ;
drivers/scsi/sg.c:95:static int scatter_elem_sz_prev = SG_SCATTER_SZ;
drivers/scsi/sg.c-96-
--
drivers/scsi/sg.c=1590=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1623-
drivers/scsi/sg.c:1624:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1625-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1658=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1659-
drivers/scsi/sg.c:1660:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1661- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1666=init_sg(void)
--
drivers/scsi/sg.c-1669-
drivers/scsi/sg.c:1670: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1671: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1672: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1673- }
--
drivers/scsi/sg.c=1854=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1875-
drivers/scsi/sg.c:1876: num = scatter_elem_sz;
drivers/scsi/sg.c:1877: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1878- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1879: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1880: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1881- } else
drivers/scsi/sg.c:1882: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1883- }
--
drivers/scsi/sg.c-1891-
drivers/scsi/sg.c:1892: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1893: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1894-
--
drivers/scsi/sg.c-1898-
drivers/scsi/sg.c:1899: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1901: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1902: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1903- }
]
|
| 635/5 |
2026/09/09 18:58 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 57615
output: 34
thoughts: 624
Thoughts: **Analyzing the Implementation of `scatter_elem_sz` in `drivers/scsi/sg.c`**
Okay, so I see that `scatter_elem_sz` is only used in a few specific locations within `drivers/scsi/sg.c`. That's good to know, narrows down the scope of impact.
Now, I need to understand how it's handled, particularly given the context of the recent commit. Let's see... I'm going to look at how `def_reserved_size` was handled in commit `d06a310b45e1`. Right. Okay, here's the code: the `def_reserved_size_set` function is used for setting the value via `kstrtoint`, with range checks (0 to 1MB) and the `def_reserved_size` variable is then assigned. The structure with the operations `def_reserved_size_ops` is also defined using `module_param_cb`.
Now, let's look at `scatter_elem_sz` in the patch. *Aha!* It looks structurally identical to the `def_reserved_size` code. There's a `scatter_elem_sz_set` function, `kstrtoint` conversion, range checks using `PAGE_SIZE` and `MAX_PAGE_ORDER`, and finally assignment to `scatter_elem_sz`. And, just like before, the operations are set up with `scatter_elem_sz_ops` and `module_param_cb`.
Interesting. Now, a key point: how does this `.get` actually work? I need to check `scatter_elem_sz_ops`. The `.set` is `scatter_elem_sz_set`, but the `.get` is `param_get_int`. Does `param_get_int` read from `kp->arg`? I need to go look at `kernel/params.c` and see what `param_get_int` actually does. I'm going to do that before I jump to any conclusions.
|
| 636/5 |
2026/09/09 18:58 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/params.c Name:param_get_int]
Results: map[SourceCode: 237: STANDARD_PARAM_DEF(int, int, "%i", kstrtoint);
SourceFile:kernel/params.c]
|
| 637/5 |
2026/09/09 18:58 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 58776
output: 32
thoughts: 11
Thoughts: Okay, I'm ready. Let's do this. I'll summarize those thoughts as if they were my own, assuming I'm an expert and presenting it in a fulsome manner.
**Navigating `STANDARD_PARAM_DEF`**
Alright, here we go. My mind is immediately drawn to the line "Let's see `STANDARD_PARAM_DEF`". This tells me that the focus is on a definition, probably a key one within a particular system or codebase. "STANDARD" suggests a widely accepted or fundamental set, implying a potential benchmark or reference point. The capitalization of `PARAM_DEF` clearly highlights this is a formal definition related to parameters. I'm going to quickly parse and analyse this line. I need to understand what 'STANDARD_PARAM_DEF' is and how it is being used here. My focus will be on quickly extracting the intent behind this. What's the context? What problem are we solving? It is highly likely the next few lines will reveal exactly that.
|
| 638/5 |
2026/09/09 18:58 |
tool |
grepper |
0m
Args: map[Expression:#define STANDARD_PARAM_DEF PathPrefix:kernel/params.c]
Results: map[Output:kernel/params.c=161=char *parse_args(const char *doing,
--
kernel/params.c-214-/* Lazy bastard, eh? */
kernel/params.c:215:#define STANDARD_PARAM_DEF(name, type, format, strtolfn) \
kernel/params.c-216- int param_set_##name(const char *val, const struct kernel_param *kp) \
]
|
| 639/5 |
2026/09/09 18:58 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 59151
output: 33
thoughts: 21
Thoughts: Here's my summary, as though I'm reading and processing the kernel code:
**Diving into `kernel/params.c`**
Okay, let's zero in on lines 215 through 235 of `kernel/params.c`. Given the context, I'm expecting this section to deal with *something* parameter-related, likely configuration or initialization. I'll be looking for clues as to whether we're parsing command-line arguments, reading from a configuration file, or perhaps even dynamically adjusting kernel parameters based on hardware or system conditions. Understanding *how* these parameters are handled is key. I'll be paying attention to data structures used, error handling, and any interactions with related modules. Are we using a standard library for parsing, or is there a custom implementation? The details will tell me a lot about the design choices and potential performance implications. Let's see what we've got. I'm especially keen to see how the system handles invalid parameters or out-of-range values - that's often where the subtle bugs lurk! Hopefully there's decent logging and error reporting as well.
|
| 640/5 |
2026/09/09 18:58 |
tool |
read-file |
0m
Args: map[File:kernel/params.c FirstLine:215 LineCount:25]
Results: map[Contents: 215: #define STANDARD_PARAM_DEF(name, type, format, strtolfn) \
216: int param_set_##name(const char *val, const struct kernel_param *kp) \
217: { \
218: return strtolfn(val, 0, (type *)kp->arg); \
219: } \
220: int param_get_##name(char *buffer, const struct kernel_param *kp) \
221: { \
222: return scnprintf(buffer, PAGE_SIZE, format "\n", \
223: *((type *)kp->arg)); \
224: } \
225: const struct kernel_param_ops param_ops_##name = { \
226: .set = param_set_##name, \
227: .get = param_get_##name, \
228: }; \
229: EXPORT_SYMBOL(param_set_##name); \
230: EXPORT_SYMBOL(param_get_##name); \
231: EXPORT_SYMBOL(param_ops_##name)
232:
233:
234: STANDARD_PARAM_DEF(byte, unsigned char, "%hhu", kstrtou8);
235: STANDARD_PARAM_DEF(short, short, "%hi", kstrtos16);
236: STANDARD_PARAM_DEF(ushort, unsigned short, "%hu", kstrtou16);
237: STANDARD_PARAM_DEF(int, int, "%i", kstrtoint);
238: STANDARD_PARAM_DEF(uint, unsigned int, "%u", kstrtouint);
239: STANDARD_PARAM_DEF(long, long, "%li", kstrtol);
]
|
| 641/5 |
2026/09/09 18:58 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 59970
output: 32
thoughts: 2556
Thoughts: **Analysis of Scatter Gather Element Size Parameter**
Okay, let's break this down. My initial thought was that reading `scatter_elem_sz` through `param_get_int` works as expected, using the underlying `kp->arg` pointing to the `scatter_elem_sz` variable, which is good. But, I had to dig deeper.
The `scatter_elem_sz_set` function seems sound on the surface, validating the size against `PAGE_SIZE` and the maximum page order. My first concern was what happens if the input is not a power of 2, or exceeds the maximum. But then I looked deeper.
Then I checked `sg_build_indirect`, and that's when it got interesting. The initial code had the old code, which was incredibly problematic. It had this logic to mutate `scatter_elem_sz` if `ret_sz` (the calculated allocation size based on the order) was larger than the current `scatter_elem_sz`. This was clearly an attempt to "round up" to a power of two, but it was done in the *worst* possible place: inside an I/O path. This led to potential data races and inconsistencies if multiple threads were writing to the module parameter. The commit message from 2006 confirms this, mentioning the rounding-up behavior. It also had a bug where it forgot to update a `num` when setting `scatter_elem_sz` to `PAGE_SIZE`.
The new patch's logic is vastly simplified, and now I'm trying to see if there are side effects. The new code uses `get_order(scatter_elem_sz)` to determine the allocation order, and `ret_sz` is based on the result. The key thing is that `scatter_elem_sz` is only used once to determine the `order`, and that order is used to allocate pages. The driver then subtracts based on `ret_sz`, allocating pages in the loop. Even if allocation fails and it retries with a smaller order, it will still work as long as it has to round the allocation.
I'm now trying to confirm if `scatter_elem_sz` itself *needs* to be a power of two with the current code. If the user sets `scatter_elem_sz` to a non-power-of-two value like 5000 (when `PAGE_SIZE` is 4096), `get_order` will return `1`, resulting in allocation of 8192 bytes (order 1), which is fine for the allocator.
I'm checking if `scatter_elem_sz` is used anywhere else in the code, to ensure that the initial value, and its potential changes, don't affect anything else. My search of the code confirms that it's only used for the initial `order` calculation.
Finally, I'm checking to see if there's a race condition. Since the read of `scatter_elem_sz` is atomic (being an `int`), and the value is validated in `scatter_elem_sz_set` to be between `PAGE_SIZE` and `PAGE_SIZE << MAX_PAGE_ORDER`, there's no way a race condition could lead to an out-of-bounds order value.
I'm also double-checking initialization. `scatter_elem_sz` is initialized to `SG_SCATTER_SZ` and then updated in `init_sg()` to be at least `PAGE_SIZE`. So, it seems safe from the get-go. I'm also confirming what happens with kernel parameters. If someone specifies an invalid value like `sg.scatter_elem_sz=123`, `scatter_elem_sz_set()` returns an error. I'm verifying the error handling behavior from the kernel during boot.
In conclusion, the new patch is vastly improved over the old one, and it is correct.
|
| 642/5 |
2026/09/09 18:59 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/params.c Name:parse_one]
Results: map[SourceCode: 117: static int parse_one(char *param,
118: char *val,
119: const char *doing,
120: const struct kernel_param *params,
121: unsigned num_params,
122: s16 min_level,
123: s16 max_level,
124: void *arg, parse_unknown_fn handle_unknown)
125: {
126: unsigned int i;
127: int err;
128:
129: /* Find parameter */
130: for (i = 0; i < num_params; i++) {
131: if (parameq(param, params[i].name)) {
132: if (params[i].level < min_level
133: || params[i].level > max_level)
134: return 0;
135: /* No one handled NULL, so do it here. */
136: if (!val &&
137: !(params[i].ops->flags & KERNEL_PARAM_OPS_FL_NOARG))
138: return -EINVAL;
139: pr_debug("handling %s with value '%s'\n", param,
140: val ? val : "no-arg");
141: kernel_param_lock(params[i].mod);
142: if (param_check_unsafe(¶ms[i]))
143: err = params[i].ops->set(val, ¶ms[i]);
144: else
145: err = -EPERM;
146: kernel_param_unlock(params[i].mod);
147: return err;
148: }
149: }
150:
151: if (handle_unknown) {
152: pr_debug("doing %s: %s='%s'\n", doing, param, val);
153: return handle_unknown(param, val, doing, arg);
154: }
155:
156: pr_debug("Unknown argument '%s'\n", param);
157: return -ENOENT;
158: }
SourceFile:kernel/params.c]
|
| 643/5 |
2026/09/09 18:59 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 64049
output: 24
thoughts: 477
Thoughts: **Analyzing the `scatter_elem_sz` Parameter and Potential Range Issues**
Okay, so if `scatter_elem_sz_set` returns `-ERANGE`, the function errors out, meaning the new value isn't applied, and `scatter_elem_sz` just stays at its default, `SG_SCATTER_SZ`. Makes sense. Now, let's look at sysfs writes. If I try something like `echo 0 > /sys/module/sg/parameters/scatter_elem_sz`, that goes through `param_attr_store`, which in turn calls `ops->set`. If `ops->set` hits `-ERANGE`, the `write()` syscall errors with `-ERANGE` (or -34), which will show the user a "Numerical result out of range!" error. The value, as expected, remains unchanged.
But wait, I need to check something related to `MAX_PAGE_ORDER`. Is there anything in `scatter_elem_sz_set` that could be causing issues there? Let me quickly look at `include/linux/mmzone.h`. Yep, line 29 shows that `#define MAX_PAGE_ORDER 10`.
Now, is `MAX_PAGE_ORDER` always defined, or is it potentially conditional? Line 30: Ah, the `#ifndef CONFIG_ARCH_FORCE_MAX_ORDER` shows that it's defined unless `CONFIG_ARCH_FORCE_MAX_ORDER` is defined, in which case it is equal to `CONFIG_ARCH_FORCE_MAX_ORDER`. So, it *is* always defined. Good.
Hang on... What was `MAX_PAGE_ORDER` called previously, in older kernels? It used to be called `MAX_ORDER`, which was equal to 11. The maximum order was then one less, which means the order before was 10. And I seem to recall that commit 23baf831a32c ("mm, treewide: switch CONFIG_FORCE_MAX_ZONEORDER to CONFIG_ARCH_FORCE_MAX_ORDER") / commit bb06eb5635c3 ("mm: rename MAX_ORDER to MAX_PAGE_ORDER") renamed `MAX_ORDER` to `MAX_PAGE_ORDER`. I really should verify that with a quick `git log` search for `MAX_PAGE_ORDER` just to be certain.
|
| 644/5 |
2026/09/09 18:59 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:#define MAX_PAGE_ORDER]
Results:
|
| 645/5 |
2026/09/09 19:09 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 65097
output: 38
thoughts: 17
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into the `mmzone.h` History**
Okay, so I need to understand the evolution of the memory zone definitions in the Linux kernel. The best place to start, as always, is the Git log for `include/linux/mmzone.h`. I want to quickly grasp the significant changes, the reasoning behind them, and who the key contributors are. Specifically, I'm looking for things like major refactorings of the zone structures, changes to the NUMA integration, modifications related to memory hotplug or memory compaction, and any relevant patches dealing with slab or page allocator interactions. Getting a solid grasp of the historical context here will provide a strong foundation to proceed with the more focused questions I have. I anticipate there will be a handful of key commits and contributors to focus on.
|
| 646/5 |
2026/09/09 19:09 |
tool |
git-log |
0m
Args: map[CodeRegexp:#define MAX_PAGE_ORDER PathPrefix:include/linux/mmzone.h]
Results: map[Output:5e0a760b4441 mm, treewide: rename MAX_ORDER to MAX_PAGE_ORDER
]
|
| 647/5 |
2026/09/09 19:09 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 65378
output: 33
thoughts: 132
Thoughts: **Analyzing a Recent Code Change**
Okay, so commit `5e0a760b4441` renames `MAX_ORDER` to `MAX_PAGE_ORDER`. Seems straightforward; `MAX_PAGE_ORDER` is a pretty standard naming convention in this codebase, which is a good sign.
But hold on a second... let's not be too quick to assume everything's perfect. The more I think about it, I need to verify something critical. Is there a potential integer overflow when calculating `PAGE_SIZE << MAX_PAGE_ORDER`? This calculation is fundamental to the memory management, and an overflow here would be disastrous.
Let's break this down. `PAGE_SIZE` is defined as `(1UL << PAGE_SHIFT)`. Okay, that's clear enough. Now, what's the underlying type of `PAGE_SIZE`? I need to know the bit width involved to accurately assess the potential for overflow when it gets left-shifted. I need to trace this definition now. Let's see where `PAGE_SIZE` is actually defined. The type information is key to determine the validity of this change.
|
| 648/5 |
2026/09/09 19:09 |
tool |
grepper |
0m
Error:
Args: map[Expression:#define PAGE_SIZE PathPrefix:arch/x86/include/]
Results:
|
| 649/5 |
2026/09/09 19:09 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 65804
output: 29
thoughts: 11
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating `PAGE_SIZE`**
Alright, let's get down to brass tacks. I'm hitting a point where I need the explicit definition of `PAGE_SIZE`. This is probably to optimize something—likely memory allocation or access patterns, or perhaps I'm looking at how virtual memory is managed by the underlying OS for a particular platform. I know the general concept, of course: it's the fundamental unit of memory mapping, the granularity at which the MMU operates. But I need the actual *value* in bytes. I'm not just after a generic understanding; I need the concrete number. The specific page size can dramatically influence performance in a whole host of areas, from cache utilization to the efficiency of TLB lookups. So, I need the precise definition for this current task.
|
| 650/5 |
2026/09/09 19:09 |
tool |
grepper |
0m
Args: map[Expression:#define PAGE_SIZE\b PathPrefix:include/]
Results: map[Output:include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
]
|
| 651/5 |
2026/09/09 19:09 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 66102
output: 24
thoughts: 1556
Thoughts: **Deep Dive into a Potential Integer Comparison Bug**
Okay, so I'm looking at this `scatter_elem_sz_set` function and immediately something jumps out at me. We have an integer `size` being compared to `PAGE_SIZE`, which is an `unsigned long`. The code's checking if `size` is outside a valid range: `if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))`. My initial thought is, "Hang on, could there be a signed/unsigned comparison issue here?"
Let's break this down. If `size` is negative, we have a problem. C's type promotion rules kick in. In this case (64-bit systems like x86_64, arm64, or riscv64), a signed 32-bit `int` will be converted to `long` (sign extension: -1 becomes `0xffffffffffffffffL`) and then to `unsigned long`. This means `-1` becomes `0xffffffffffffffffUL`.
The code checks if `size` is `< PAGE_SIZE` and if it is `> PAGE_SIZE << MAX_PAGE_ORDER`. But if `size` is -1, then the unsigned comparison is `0xffffffffffffffffUL < 4096UL` which is FALSE. And `0xffffffffffffffffUL > (PAGE_SIZE << MAX_PAGE_ORDER)`? That's TRUE because `ULONG_MAX` (18446744073709551615) is so much larger than anything we'd get from `PAGE_SIZE` shifted left. *This is critical*. The conditional is designed to reject sizes outside the allowed range, but negative numbers will *always* trigger the second condition!
Let's test it: rank of `unsigned long` is higher than `int`, so `size` (int) is converted to `unsigned long`. A negative `int` becomes `ULONG_MAX`. If size is -1, it becomes `0xFFFFFFFFFFFFFFFFUL`. This value is always greater than any reasonable result from `PAGE_SIZE << MAX_PAGE_ORDER`. So, for any negative `size` on 64-bit systems, `size > (PAGE_SIZE << MAX_PAGE_ORDER)` *will* be true. That's a bug! It makes `size < PAGE_SIZE` and `size > PAGE_SIZE << MAX_PAGE_ORDER` a test which will only be triggered for `size == 0`.
What about 32-bit systems? Then, both `int` and `unsigned long` are 32-bit. If `size == -1`, it becomes `0xFFFFFFFFUL`, still a very large number, and still greater than a reasonable `PAGE_SIZE << MAX_PAGE_ORDER`. On a 32-bit system the comparison is still vulnerable.
But if `size` is 0, the check *works*. 0 is smaller than `PAGE_SIZE`, and therefore is `-ERANGE`.
This comparison is a disaster! Why would someone write this comparison between signed `int` and `unsigned long` in the first place? I need to check if the compiler is supposed to warn me of these kind of errors! I have to look for compiler warnings, like `-Wsign-compare`, which I don't see in the kernel's global settings, so the potential bug is *silent*. The `-Wsign-compare` flag must be set!
|
| 652/5 |
2026/09/09 19:09 |
tool |
grepper |
0m
Error:
Args: map[Expression:sign-compare PathPrefix:Makefile]
Results:
|
| 653/5 |
2026/09/09 19:09 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 68459
output: 30
thoughts: 13
Thoughts: Here's a summary of my immediate thought process:
**Diving into the Build Configuration**
Okay, time to get started. My first instinct is to zero in on the build process and how it handles warnings. Let's see... I'll start by checking the `scripts/Makefile.extrawarn` file. I'm expecting this file to hold the specific flags and settings that control the extra warning level in the build process. I'm looking for the definitions related to compile-time warnings, not just the general makefile structure itself. Knowing how warnings are treated is crucial, and `Makefile.extrawarn` is the most logical starting point for that investigation. Let's see what's in there.
|
| 654/5 |
2026/09/09 19:09 |
tool |
grepper |
0m
Error:
Args: map[Expression:sign-compare PathPrefix:scripts/Makefile.extrawarn]
Results:
|
| 655/5 |
2026/09/09 19:09 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 68668
output: 17
thoughts: 17
Thoughts: Here's my thought process, as if I were considering this search:
**Diving Deep into the Codebase**
Okay, so I need to find all instances of `sign-compare` within the code. Given my expertise, I know a basic text search might not be sufficient. I need to be thorough. I don't want to miss anything, especially if it's used in a contextually obscure way or with variable names that are close enough to be relevant. Therefore, a simple `grep` won't cut it. I need to run a full tree search, making sure I am not missing anything that might be critical to my current task. I'll need to make sure I am looking at every file and directory in this project.
|
| 656/5 |
2026/09/09 19:09 |
tool |
grepper |
0m
Args: map[Expression:sign-compare]
Results: map[Output:arch/alpha/kernel/Makefile=7=asflags-y := $(KBUILD_CFLAGS)
arch/alpha/kernel/Makefile:8:ccflags-y := -Wno-sign-compare
arch/alpha/kernel/Makefile-9-
--
arch/s390/Makefile=116=KBUILD_CFLAGS += -mpacked-stack -mbackchain -msoft-float $(cflags-y)
arch/s390/Makefile:117:KBUILD_CFLAGS += -pipe -Wno-sign-compare
arch/s390/Makefile-118-KBUILD_CFLAGS += -fno-asynchronous-unwind-tables $(cfi)
--
arch/s390/purgatory/Makefile=17=KBUILD_CFLAGS := $(CC_FLAGS_DIALECT) -fno-strict-aliasing -Wall -Wstrict-prototypes
arch/s390/purgatory/Makefile:18:KBUILD_CFLAGS += -Wno-pointer-sign -Wno-sign-compare
arch/s390/purgatory/Makefile-19-KBUILD_CFLAGS += -fno-zero-initialized-in-bss -fno-builtin -ffreestanding
--
arch/sparc/Makefile=47=KBUILD_CFLAGS += -m64 -pipe -mno-fpu -mcpu=ultrasparc -mcmodel=medlow
arch/sparc/Makefile:48:KBUILD_CFLAGS += -ffixed-g4 -ffixed-g5 $(call cc-option,-fcall-used-g7) -Wno-sign-compare
arch/sparc/Makefile-49-KBUILD_CFLAGS += -Wa,--undeclared-regs
--
arch/x86/Makefile=201=endif
--
arch/x86/Makefile-203-# Workaround for a gcc prelease that unfortunately was shipped in a suse release
arch/x86/Makefile:204:KBUILD_CFLAGS += -Wno-sign-compare
arch/x86/Makefile-205-#
--
drivers/gpu/drm/Makefile=27=ifeq ($(findstring 3, $(KBUILD_EXTRA_WARN)),)
drivers/gpu/drm/Makefile:28:subdir-ccflags-y += -Wno-sign-compare
drivers/gpu/drm/Makefile-29-endif
--
drivers/hwtracing/coresight/Makefile=12=subdir-ccflags-y += -Wmissing-include-dirs
drivers/hwtracing/coresight/Makefile:13:subdir-ccflags-y += -Wno-sign-compare
drivers/hwtracing/coresight/Makefile-14-condflags := \
--
fs/btrfs/Makefile=18=subdir-ccflags-y += -Wno-missing-field-initializers
fs/btrfs/Makefile:19:subdir-ccflags-y += -Wno-sign-compare
fs/btrfs/Makefile-20-subdir-ccflags-y += -Wno-shift-negative-value
--
fs/ntfs3/Makefile=21=subdir-ccflags-y += -Wno-missing-field-initializers
fs/ntfs3/Makefile:22:subdir-ccflags-y += -Wno-sign-compare
fs/ntfs3/Makefile-23-subdir-ccflags-y += -Wno-type-limits
--
scripts/Makefile.warn=186=KBUILD_CFLAGS += -Wredundant-decls
scripts/Makefile.warn:187:KBUILD_CFLAGS += -Wsign-compare
scripts/Makefile.warn-188-KBUILD_CFLAGS += -Wswitch-default
--
scripts/Makefile.warn=192=else
--
scripts/Makefile.warn-194-# The following turn off the warnings enabled by -Wextra
scripts/Makefile.warn:195:KBUILD_CFLAGS += -Wno-sign-compare
scripts/Makefile.warn-196-KBUILD_CFLAGS += -Wno-unused-parameter
--
scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py=13=class TestSavedCmdParser(unittest.TestCase):
--
scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py-119- cmd = (
scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py:120: "gcc -Wp,-MMD,arch/x86/pci/.i386.o.d -nostdinc -I../arch/x86/include -I./arch/x86/include/generated -I../include -I./include -I../a...
scripts/sbom/tests/cmd_graph/test_savedcmd_parser.py-121- "arch/x86/pci/i386"
--
tools/objtool/Makefile=50=WARNINGS := -Werror -Wall -Wextra -Wmissing-prototypes \
tools/objtool/Makefile-51- -Wmissing-declarations -Wwrite-strings \
tools/objtool/Makefile:52: -Wno-implicit-fallthrough -Wno-sign-compare \
tools/objtool/Makefile-53- -Wno-unused-parameter
--
tools/perf/util/Build=318=ifeq ($(FLEX_GE_260),1)
--
tools/perf/util/Build-328- ifeq ($(FLEX_LT_262),1)
tools/perf/util/Build:329: flex_flags += -Wno-sign-compare
tools/perf/util/Build-330- endif
--
tools/power/cpupower/Makefile=122=OPTIMIZATION := $(call cc-supports,-Os,-O2)
tools/power/cpupower/Makefile-123-
tools/power/cpupower/Makefile:124:WARNINGS := -Wall -Wchar-subscripts -Wpointer-arith -Wsign-compare
tools/power/cpupower/Makefile-125-WARNINGS += $(call cc-supports,-Wno-pointer-sign)
--
tools/testing/selftests/bpf/Makefile=464=BPF_CFLAGS = -g -Wall -Werror -D__TARGET_ARCH_$(SRCARCH) $(MENDIAN) \
--
tools/testing/selftests/bpf/Makefile-474- #
tools/testing/selftests/bpf/Makefile:475:# TODO: enable me -Wsign-compare
tools/testing/selftests/bpf/Makefile-476-
--
tools/testing/selftests/bpf/bpf_experimental.h=149=l_true: \
--
tools/testing/selftests/bpf/bpf_experimental.h-153-/* C type conversions coupled with comparison operator are tricky.
tools/testing/selftests/bpf/bpf_experimental.h:154: * Make sure BPF program is compiled with -Wsign-compare then
tools/testing/selftests/bpf/bpf_experimental.h-155- * __lhs OP __rhs below will catch the mistake.
]
|
| 657/5 |
2026/09/09 19:09 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 70603
output: 35
thoughts: 974
Thoughts: **Analyzing Potential Integer Overflow in `scatter_elem_sz_set`**
Okay, let's break this down. I'm looking at `scripts/Makefile.warn` and specifically the `-Wno-sign-compare` flag. This got me thinking about a comparison in `drivers/scsi/sg.c` at line 1670: `scatter_elem_sz < PAGE_SIZE`. I recall that this comparison was already present, and `scatter_elem_sz` is an `int`, so why the concern?
The issue then expanded as I began looking at `scatter_elem_sz_set`. I noticed that the code doesn't explicitly check for negative numbers during the parsing from the string. My first thought was, what happens if someone provides a negative number, like `-1`? Will the comparison, `(size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))`, flag this? If so, will this `-Wsign-compare` be tripped if I compile with `W=1`?
I then compared it to how `def_reserved_size_set` handles negative numbers. It explicitly checks for negative sizes. In contrast, `scatter_elem_sz_set` relies on the implicit overflow detection when comparing.
I went and verified that negative number handling is correct. Let's trace it through: If `size = -1`, the `int` `-1` gets promoted to an `unsigned long`, which becomes `0xffffffffffffffffUL`. The first comparison, `0xffffffffffffffffUL < PAGE_SIZE`, is false. The second comparison, `0xffffffffffffffffUL > (PAGE_SIZE << MAX_PAGE_ORDER)`, is true. Therefore, the function will correctly return `-ERANGE` (indicating an out-of-range error), preventing an issue from an improperly assigned negative number.
So it _does_ reject negative inputs. Zero is rejected as well. The logic in place correctly rejects any size less than `PAGE_SIZE`. Sizes from `PAGE_SIZE` to `PAGE_SIZE << MAX_PAGE_ORDER` are accepted. Any size greater than that range is rejected.
But I still felt uneasy. Although the check functions, I still asked, why rely on that implicit promotion when a simple `size < 0` check would have made it so much clearer?
Then, the possibility of `size > INT_MAX` came to mind. However, checking `kstrtoint`'s documentation, I can confirm that it returns `-ERANGE` if the input string is too large to fit within an `int`. This prevents an integer overflow scenario that could lead to unexpected behavior.
So, in summary, even though the logic isn't as explicitly clear as I'd like, the current code in `scatter_elem_sz_set` correctly handles both negative numbers and very large values due to the error conditions triggered by the promotions to an unsigned long and the limits of `kstrtoint`.
|
| 658/5 |
2026/09/09 19:09 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:lib/kstrtox.c Name:kstrtoint]
Results: map[SourceCode: 246: /**
247: * kstrtoint - convert a string to an int
248: * @s: The start of the string. The string must be null-terminated, and may also
249: * include a single newline before its terminating null. The first character
250: * may also be a plus sign or a minus sign.
251: * @base: The number base to use. The maximum supported base is 16. If base is
252: * given as 0, then the base of the string is automatically detected with the
253: * conventional semantics - If it begins with 0x the number will be parsed as a
254: * hexadecimal (case insensitive), if it otherwise begins with 0, it will be
255: * parsed as an octal number. Otherwise it will be parsed as a decimal.
256: * @res: Where to write the result of the conversion on success.
257: *
258: * Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
259: * Preferred over simple_strtol(). Return code must be checked.
260: */
261: noinline
262: int kstrtoint(const char *s, unsigned int base, int *res)
263: {
264: long long tmp;
265: int rv;
266:
267: rv = kstrtoll(s, base, &tmp);
268: if (rv < 0)
269: return rv;
270: if (tmp != (int)tmp)
271: return -ERANGE;
272: *res = tmp;
273: return 0;
274: }
SourceFile:lib/kstrtox.c]
|
| 659/5 |
2026/09/09 19:09 |
llm |
patch-reviewer-compressor |
0m
Model:
Reply: ### Execution Summary
#### 1. Approaches Tried and Results
* **Analysis of Crash Report & Stack Trace:**
- Bug: `UBSAN: shift-out-of-bounds in drivers/scsi/sg.c:1887:13` (`shift exponent 64 is too large for 32-bit type 'int'`).
- Stack: `sg_open` -> `sg_add_sfp` -> `sg_build_reserve` -> `sg_build_indirect`.
- Trigger: Writing `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`.
* **Examination of `sg_build_indirect` (`drivers/scsi/sg.c:1853`):**
- Found that `num = scatter_elem_sz;` read `0`.
- The check `if (num < PAGE_SIZE)` updated globals `scatter_elem_sz` and `scatter_elem_sz_prev`, but left local variable `num == 0`.
- `order = get_order(0)` caused underflow (`size--` wrapped to `0xffffffffffffffff`), yielding `order = 52`.
- `ret_sz = 1 << (PAGE_SHIFT + order)` yielded `1 << (12 + 52) = 1 << 64`, triggering UBSAN shift-out-of-bounds.
* **Evaluation of Root Cause "Proposed Fix" vs Proposed Patch Diff:**
- The root cause note suggested a localized band-aid: updating `num = PAGE_SIZE;` inside the `if (num < PAGE_SIZE)` check and doing `order = min_t(int, order, MAX_PAGE_ORDER);`.
- The proposed patch diff instead implements an architectural invariant shift by converting `scatter_elem_sz` from a raw unchecked `module_param_named` to a validated `module_param_cb` using `scatter_elem_sz_set()`, mirroring the existing idiomatic pattern used for `def_reserved_size`.
* **Git History and Precedent Investigation:**
- Examined commit `d06a310b45e1` ("scsi: sg: Resolve soft lockup issue when opening /dev/sgX"): identical pattern used for `def_reserved_size` via `def_reserved_size_set()` and `module_param_cb()`.
- Examined commits `6460e75a104d` (2006) and `10db10d144c0` (2008): tracked why `scatter_elem_sz_prev` existed (originally tracked dynamic power-of-two page allocation roundups prior to uniform block layer conversions; became obsolete/vestigial after 2008).
* **Bounds and Limit Verification:**
- Checked `MAX_PAGE_ORDER` across architectures (`CONFIG_ARCH_FORCE_MAX_ORDER` ranges from 8 to 16, typically 10).
- Verified `PAGE_SIZE << MAX_PAGE_ORDER` fits comfortably in signed 32-bit `int` across all architectures (e.g. 4MB on x86, max ~64MB-256MB on PowerPC/ARM, far below 2GB).
- Verified `alloc_order_allowed()` in `mm/page_alloc.c` allows `order <= MAX_PAGE_ORDER`.
- Verified `scatter_elem_sz_set()` properly checks `size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER)`, rejecting 0, negative values, and excessive sizes with `-ERANGE`.
---
#### 2. Current Hypotheses and Theories
* **Patch Quality & Maintainer Taste:**
- The proposed patch eliminates the invalid state at the boundary (`sysfs` parameter write / boot argument parsing) via `module_param_cb` rather than letting corrupt state into the allocation pipeline.
- Removes the legacy, un-synchronized, vestigial `scatter_elem_sz_prev` global variable and the clumsy in-band runtime checks/re-assignments in `sg_build_indirect`.
- Simplifies `num` calculation inside the loop to `num = min(rem_sz, ret_sz);` (used solely for tracing).
- Fully aligns with subsystem idiom (`def_reserved_size_ops` in the same file) and complies with Section 1 (Core Philosophy: Band-Aid vs Architectural Design) of the Maintainer Taste guidelines.
---
#### 3. Key File Paths, Structs, and Code Snippets
* **File:** `drivers/scsi/sg.c`
* **Module Parameter Setter & Ops Added by Patch:**
```c
static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
return -ERANGE;
scatter_elem_sz = size;
return 0;
}
static const struct kernel_param_ops scatter_elem_sz_ops = {
.set = scatter_elem_sz_set,
.get = param_get_int,
};
module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
S_IRUGO | S_IWUSR);
```
* **Cleaned `sg_build_indirect()` Allocation Calculation:**
```c
order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
}
```
* **Init check in `init_sg()`:**
```c
if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
```
---
#### 4. Watchouts for Reasoning Loops / Repetitive Tool Calls
* Verified that all code references (`get_order`, `MAX_PAGE_ORDER`, `init_sg`, `sg_build_indirect`, `def_reserved_size`) have been fully resolved.
* No further code inspection needed; ready to invoke `set-results` and provide the final architectural evaluation.
Tokens:
input: 55755
output: 1605
thoughts: 0
|
| 660/5 |
2026/09/09 19:10 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 32028
output: 37
thoughts: 521
Thoughts: **Analyzing `sg_build_indirect` for Potential Integer Overflow**
Okay, so I'm looking at this code and immediately my brain goes to potential integer overflow issues. I know that `kstrtoint` returns `-ERANGE` when it overflows, so anything larger than `INT_MAX` or smaller than `INT_MIN` will trigger that error.
I'm focused on the changes in `sg_build_indirect`, specifically how it handles `scatter_elem_sz` and related variables. I see the original code has several lines dealing with `scatter_elem_sz` and its previous value (`scatter_elem_sz_prev`). There's this check:
```c
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
```
And then the updated code uses `get_order(scatter_elem_sz)` instead:
```c
+ order = get_order(scatter_elem_sz);
```
I also see this part of the original code:
```c
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
```
And then there is an entire block of code that is now removed:
```c
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
```
My concern now is if we are setting `ret_sz` (which is a power of 2) or `scatter_elem_sz` to a value that is too large. Is it possible for a large value to be read and assigned here, potentially leading to overflow? I need to understand this whole function, line by line, to see how these variables are used and how they're calculated. I'm going to read the entire `sg_build_indirect` function to make sure that I understand every nuance of what's happening.
|
| 661/5 |
2026/09/09 19:10 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c Name:sg_build_indirect]
Results: map[SourceCode:1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
SourceFile:drivers/scsi/sg.c]
|
| 662/5 |
2026/09/09 19:10 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 34480
output: 37
thoughts: 3322
Thoughts: **Analyzing the `sg_build_indirect` Patch: A Deep Dive**
Okay, let's break this down. My initial focus was on tracing `sg_build_indirect`, pinpointing the core logic within this function. The original code's approach to determining and allocating scatter-gather elements seemed, well, convoluted. It involved calculating allocation sizes, managing `scatter_elem_sz_prev`, and handling potential failures with a retry mechanism. I was initially focused on the arithmetic around `ret_sz`, `rem_sz`, and `num`. The interplay of these variables and how the allocation order was managed felt like the place to start.
Then I saw the diff. The removal of the `scatter_elem_sz_prev` variable and the associated checks immediately stood out. It introduced a cleaner approach where the minimum size logic had been simplified using the `min()` function. The old code was calculating `num` in a confusing way, potentially leading to incorrect values after an order decrement, which would be problematic. This prompted a detailed look at where `num` was used, and I realized that it was only used for a print statement.
That's when I dug deeper into the history. It's clear that the original code included some kind of optimization, a kludge, around how the user could set `scatter_elem_sz` with a module parameter, and it was fixing it up. It seems the module parameter was being "fixed" in place, so the code was trying to detect if the user changed the parameter via sysfs. This shadow variable and the conditional adjustments within the core allocation path were remnants of an older system of module parameter validation. It was an in-band parameter validation, and now we're moving it out of the band.
The patch itself represents a shift in philosophy. Rather than patching *around* the problem – using `if` statements and checks to handle invalid states – the maintainer is making those invalid states unrepresentable. Instead of defensive checks within `sg_build_indirect`, they're moving the validation to the module parameter's boundary, using `module_param_cb` to define a valid range for `scatter_elem_sz`. That means that the `scatter_elem_sz` parameter is guaranteed to always be in a valid range.
So, the new approach uses `module_param_cb` to validate and enforce that `scatter_elem_sz` is within a valid range (between `PAGE_SIZE` and `PAGE_SIZE << MAX_PAGE_ORDER`) *before* the function even runs. The `scatter_elem_sz_set` function now validates the input, and invalid values are rejected, preventing the underflow and UBSAN issue. Now `scatter_elem_sz_prev` is not needed.
The key is in understanding the subtle difference between "fixing it" and "preventing it." The proposed "fix" from the bug report was a band-aid: adding a check within the function. The actual patch uses a *systematic* approach. It's a complete shift: validate the input *before* the function even executes. This is precisely the kind of architectural improvement I appreciate.
I've examined the patch closely, and I'm certain there are no regressions. The core logic is simplified, and the parameter validation is handled properly. There are no compiler warnings, no syntax errors, and no logic bugs. This is a very clean and thoughtful solution. The patch aligns perfectly with best practices and enhances the robustness of the system.
|
| 663/5 |
2026/09/09 19:10 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1625 LineCount:40]
Results: map[Contents:1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
1655: MODULE_DESCRIPTION("SCSI generic (sg) driver");
1656: MODULE_LICENSE("GPL");
1657: MODULE_VERSION(SG_VERSION_STR);
1658: MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
1659:
1660: MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
1662: MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1663: MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
1664:
]
|
| 664/5 |
2026/09/09 19:10 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 39220
output: 34
thoughts: 1583
Thoughts: **Analysis of SG Driver Patch**
Alright, let's break this down. From a quick glance, it looks like this patch is simplifying the scatter/gather element size handling within the SCSI generic (sg) driver. The original code defines two kernel parameters, `def_reserved_size` and `scatter_elem_sz`, both using the `module_param_cb` mechanism. The first, `def_reserved_size`, seems straightforward, just setting a reserved memory size with a 1MB upper bound. The second, `scatter_elem_sz`, is the one I'm interested in; it defines the size of a scatter/gather element, with bounds of `PAGE_SIZE` to `PAGE_SIZE << MAX_PAGE_ORDER`.
The key change is in the `init_sg()` function. Originally, it clamped `scatter_elem_sz` to `PAGE_SIZE` if the configured size was smaller. The patch removes an unnecessary variable (`scatter_elem_sz_prev`) and simplifies the logic, removing the conditional assignment that seems redundant and could lead to subtle issues. This is good; less code, fewer potential bugs.
The biggest impact is in `sg_build_indirect()`. This function seems to be responsible for building the indirect scatterlist. The original code was needlessly complex. It recalculates the order based on a variable that might mutate within the loop. The patch directly uses the configured `scatter_elem_sz` to derive the order. The loop condition is simplified. Most importantly, it removes all references to the now removed `scatter_elem_sz_prev` variable. The logic `num = min(rem_sz, ret_sz)` to compute element size in the loop is exactly what I would expect. This looks much cleaner. The conditional code within the loop that was responsible for updating `scatter_elem_sz_prev` has been removed. This significantly improves clarity, reduces redundancy, and removes potential for unexpected behavior due to dynamic adjustment of the element size during list construction.
Finally, I checked for unused variables. There aren't any.
Overall, this is a positive change. It makes the code easier to follow, likely improves performance a bit by avoiding unnecessary recalculations, and reduces the risk of errors associated with the complex state management of the old implementation. It looks like a solid refactoring.
|
| 665/5 |
2026/09/09 19:10 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1 LineCount:70]
Results: map[Contents: 1: // SPDX-License-Identifier: GPL-2.0-or-later
2: /*
3: * History:
4: * Started: Aug 9 by Lawrence Foard (entropy@world.std.com),
5: * to allow user process control of SCSI devices.
6: * Development Sponsored by Killy Corp. NY NY
7: *
8: * Original driver (sg.c):
9: * Copyright (C) 1992 Lawrence Foard
10: * Version 2 and 3 extensions to driver:
11: * Copyright (C) 1998 - 2014 Douglas Gilbert
12: */
13:
14: static int sg_version_num = 30536; /* 2 digits for each component */
15: #define SG_VERSION_STR "3.5.36"
16:
17: /*
18: * D. P. Gilbert (dgilbert@interlog.com), notes:
19: * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
20: * the kernel/module needs to be built with CONFIG_SCSI_LOGGING
21: * (otherwise the macros compile to empty statements).
22: *
23: */
24: #include <linux/module.h>
25:
26: #include <linux/fs.h>
27: #include <linux/kernel.h>
28: #include <linux/sched.h>
29: #include <linux/string.h>
30: #include <linux/mm.h>
31: #include <linux/errno.h>
32: #include <linux/mtio.h>
33: #include <linux/ioctl.h>
34: #include <linux/major.h>
35: #include <linux/slab.h>
36: #include <linux/fcntl.h>
37: #include <linux/init.h>
38: #include <linux/poll.h>
39: #include <linux/moduleparam.h>
40: #include <linux/cdev.h>
41: #include <linux/idr.h>
42: #include <linux/seq_file.h>
43: #include <linux/blkdev.h>
44: #include <linux/delay.h>
45: #include <linux/blktrace_api.h>
46: #include <linux/mutex.h>
47: #include <linux/atomic.h>
48: #include <linux/ratelimit.h>
49: #include <linux/uio.h>
50: #include <linux/cred.h> /* for sg_check_file_access() */
51:
52: #include <scsi/scsi.h>
53: #include <scsi/scsi_cmnd.h>
54: #include <scsi/scsi_dbg.h>
55: #include <scsi/scsi_device.h>
56: #include <scsi/scsi_driver.h>
57: #include <scsi/scsi_eh.h>
58: #include <scsi/scsi_host.h>
59: #include <scsi/scsi_ioctl.h>
60: #include <scsi/scsi_tcq.h>
61: #include <scsi/sg.h>
62:
63: #include "scsi_logging.h"
64:
65: #ifdef CONFIG_SCSI_PROC_FS
66: #include <linux/proc_fs.h>
67: static char *sg_version_date = "20140603";
68:
69: static int sg_proc_init(void);
70: #endif
]
|
| 666/5 |
2026/09/09 19:10 |
llm |
patch-reviewer |
0m
Model:
Tokens:
input: 42426
output: 19
thoughts: 461
Thoughts: **Patch Review: sg_build_indirect Fix**
Okay, so `<linux/mm.h>` has included `<linux/mmzone.h>`, which means `MAX_PAGE_ORDER` is available, and the patch compiled and passed tests. Good start. Now, let's go through the evaluation criteria systematically.
First, the core philosophy. This patch clearly moves away from the band-aid approach inside `sg_build_indirect`, where it was trying to defensively handle invalid input. Instead, it's pushing the validation to the configuration entry point using `module_param_cb` and `scatter_elem_sz_set`. This is the right approach – preventing the issue from even entering the system in the first place. This is a much better architectural design.
Next, maintainer taste and structural simplicity. The patch completely eliminates that vestigial and racy `scatter_elem_sz_prev` variable. Excellent! It also removes the runtime detection and mutation logic from the I/O path, which is critical for performance and cleanliness. Furthermore, it simplifies how `num` is calculated for logging, which helps in debugging, or in a worst case scenario, profiling.
Then, there's the idiom alignment. The patch aligns perfectly with the pattern already used within the same driver for `def_reserved_size` – using `def_reserved_size_set`, `def_reserved_size_ops`, and `module_param_cb`. This is good for consistency and maintainability.
Regarding bug resolution: Writing `"0"` to `/sys/module/sg/parameters/scatter_elem_sz` is now rejected with `-ERANGE`, preventing the issue. With the new bounds check with `module_param_cb` (`scatter_elem_sz` remaining within `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`), the underflow in `get_order()` and subsequent shift-out-of-bounds cannot happen. It's a clean, complete fix.
Finally, no regressions, no leaks. This is a solid, clean, upstream-quality fix.
Therefore, this patch is approved. I'll call `set-results` with `ReviewApproved: true` and an empty `ReviewComments` list.
|
| 667/5 |
2026/09/09 19:10 |
tool |
set-results |
0m
Args: map[ReviewApproved:true ReviewComments:[]]
Results: map[ReviewApproved:true ReviewComments:[]]
|
| 668/4 |
2026/09/09 19:10 |
action |
evaluate-patch-review |
0m
Results: map[NeedsIteration:false ReviewFeedback:]
|
| 669/1 |
2026/09/09 19:10 |
action |
apply-patch |
0m
Results:
|
| 670/1 |
2026/09/09 19:10 |
action |
init-style-items |
0m
Results:
|
| 671/1 |
2026/09/09 19:10 |
action |
run-checkpatch |
0m
Results: map[CheckpatchOutput:WARNING: Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'.
#44: FILE: drivers/scsi/sg.c:1649:
+ S_IRUGO | S_IWUSR);
total: 0 errors, 1 warnings, 91 lines checked
NOTE: For some of the reported defects, checkpatch may be able to
mechanically convert to the typical style using --fix or --fix-inplace.
Your patch has style problems, please review.
NOTE: If any of the errors are false positives, please report
them to the maintainer, see CHECKPATCH in MAINTAINERS.
]
|
| 672/1 |
2026/09/09 19:10 |
loop |
|
14m
|
| 673/2 |
2026/09/09 19:10 |
iteration |
0 |
14m
|
| 674/3 |
2026/09/09 19:10 |
agent |
checkpatch-arbiter |
0m
Model:
Results: map[ActionableIssues:[Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'.]]
Instruction:
You are an expert Linux kernel maintainer acting as a code style arbiter.
Your task is to review scripts/checkpatch.pl output and reviewer style requests for a proposed patch.
Determine which reported issues are genuine, actionable formatting/style defects (e.g. indentation, whitespace,
naming, syntax style) and should be fixed. List them in ActionableIssues.
Ignore issues that are false positives, intentional constructs (e.g. BUG_ON/XA_BUG_ON in test files, macros,
subsystem conventions), or unfixable without breaking code logic or tests. If no issues should be changed,
leave ActionableIssues empty.
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 patch diff is:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..71e1adea0 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,34 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1691,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1895,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
The checkpatch.pl output is:
WARNING: Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'.
#44: FILE: drivers/scsi/sg.c:1649:
+ S_IRUGO | S_IWUSR);
total: 0 errors, 1 warnings, 91 lines checked
NOTE: For some of the reported defects, checkpatch may be able to
mechanically convert to the typical style using --fix or --fix-inplace.
Your patch has style problems, please review.
NOTE: If any of the errors are false positives, please report
them to the maintainer, see CHECKPATCH in MAINTAINERS.
Carefully evaluate each issue and populate ActionableIssues.
|
| 675/4 |
2026/09/09 19:10 |
llm |
checkpatch-arbiter |
0m
Model:
Tokens:
input: 1716
output: 47
thoughts: 4541
Thoughts: **Analysis of checkpatch.pl Output for drivers/scsi/sg.c Patch**
Okay, I'm diving into this checkpatch output for the `sg.c` patch. It's flagging a style issue, and my initial reaction is, "Is this a real problem, or a false positive?" The warning states, *"Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'."* I need to determine if this is a genuine and *actionable* issue.
First, I always refer back to the kernel coding style. The Documentation confirms that octal permissions (like `0644`) are *preferred* over symbolic ones (like `S_IRUGO | S_IWUSR`), especially in new or converted code. Historically, the symbolic permissions were used, but readability and the risk of error are reduced with octal numbers.
The patch itself is changing `module_param_named` to `module_param_cb` for `scatter_elem_sz`, and this is where the warning originates. The existing code uses `S_IRUGO | S_IWUSR`, so there is a question of consistency. The patch is adding a `scatter_elem_sz_set` function with `module_param_cb`. However, `def_reserved_size_set` already exists and uses `0644` with `module_param_cb`, confirming that the warning is indeed applicable.
Now, I have to make sure this is *actionable*. Is this a style defect that needs fixing, or is there a reason why the author might have intentionally used symbolic permissions in the context of `sg.c`? No! The SCSI subsystem and `sg.c` doesn't mandate symbolic, and the surrounding lines in the code do not use them, either. It could be an oversight. The kernel coding style is clear, and checkpatch is specifically designed to catch this. It's definitely actionable because using `0644` in place of `S_IRUGO | S_IWUSR` is semantically equivalent. Changing it follows the kernel's coding standards. There are no test failures or logic changes.
So, in summary, this is a legitimate issue. I'm going to add the following to `ActionableIssues`: `"Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'."` and will be added as is.
|
| 676/4 |
2026/09/09 19:10 |
tool |
set-results |
0m
Args: map[ActionableIssues:[Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'.]]
Results: map[ActionableIssues:[Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'.]]
|
| 677/3 |
2026/09/09 19:10 |
action |
evaluate-checkpatch-arbiter |
0m
Results:
|
| 678/3 |
2026/09/09 19:11 |
action |
If |
13m
Args:
|
| 679/4 |
2026/09/09 19:11 |
agent |
patch-formatter |
1m
Model:
Instruction:
You are an expert Linux kernel developer tasked with formatting a kernel patch.
Your objective is purely formatting: you must ensure the patch complies with the kernel's coding style,
conforms to the surrounding code rules, and addresses the requested style changes, while preserving the code
logic exactly as it is.
You should stop once the requested formatting changes are done.
Do not question the requested changes unless they are obviously wrong.
WARNING: The clang-format tool may break the formatting of the surrounding code (like manual alignment).
Use it with caution. We want to make the change fit into the existing formatting as much as possible.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The current patch diff is:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..71e1adea0 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,34 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1691,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1895,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
The following style and formatting issues must be fixed:
- Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'.
Use the provided tools to format the patch.
Reply: I have fixed the issue by replacing the symbolic permissions `S_IRUGO | S_IWUSR` with the octal permission `0644` in `module_param_cb()` for `scatter_elem_sz`. The patch now complies with kernel coding style guidelines and passes `checkpatch.pl` without warnings or errors.
|
| 680/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 5675
output: 19
thoughts: 80
Thoughts: Okay, here's my take on those thoughts, framed as my own internal process:
**Reviewing the Patch and Style Guidelines**
Alright, let's get down to brass tacks. I've got a patch diff in front of me, and it seems like the system is flagging some formatting and style inconsistencies. Specifically, the system is pointing out an issue with symbolic permissions, preferring octal notation for file permissions instead. Using symbolic notation can be less explicit and, honestly, a bit prone to subtle errors if you're not careful. Octal permissions, while possibly a bit less immediately readable for someone unfamiliar, are generally a clearer and more robust standard.
My immediate response? Let's verify these concerns. I'll run `patch-diff` again to double-check that the patch still looks as expected after a cursory inspection. Then, I'll definitely bring in `checkpatch`. I trust `checkpatch` to give me a more in-depth look at this code and identify any other style problems the system might have missed. This should give me a solid picture of whether the symbolic permissions are the only issue or if there are other formatting or style issues I need to address before moving forward. I'd like to get the overall quality of this patch right.
|
| 681/5 |
2026/09/09 19:11 |
tool |
patch-diff |
0m
Error:
|
| 682/5 |
2026/09/09 19:11 |
tool |
checkpatch |
0m
Results: map[Output:WARNING: Symbolic permissions 'S_IRUGO | S_IWUSR' are not preferred. Consider using octal permissions '0644'.
#44: FILE: drivers/scsi/sg.c:1649:
+ S_IRUGO | S_IWUSR);
total: 0 errors, 1 warnings, 91 lines checked
NOTE: For some of the reported defects, checkpatch may be able to
mechanically convert to the typical style using --fix or --fix-inplace.
Your patch has style problems, please review.
NOTE: If any of the errors are false positives, please report
them to the maintainer, see CHECKPATCH in MAINTAINERS.
]
|
| 683/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 6224
output: 23
thoughts: 17
Thoughts: Here's my take on the process, considering I'm an expert:
**Diving into sg.c Patch Diff**
Okay, so we're looking at a patch for `drivers/scsi/sg.c`, which means we're dealing with the SCSI generic interface. This is where userspace applications like `sg_raw` and others interact with SCSI devices at a lower level. My immediate thought is, what are they changing? Is it related to error handling, command queuing, device discovery, or maybe even a new feature or optimization? Given my experience, I'm expecting to see specific calls to `scsi_execute_req`, `sg_ioctl`, or potentially modifications to how the scatter-gather lists are handled. I'm hoping it's well-commented because good `sg.c` code is crucial for correct performance. Let's get to it and see what the diff reveals. I hope it's not a performance regression!
|
| 684/5 |
2026/09/09 19:11 |
tool |
patch-diff |
0m
Args: map[File:drivers/scsi/sg.c]
Results: map[Output:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..71e1adea0 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -85,21 +85,20 @@ static int sg_proc_init(void);
* /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
* of this size (or less if there is not enough memory) will be reserved
* for use by this file descriptor.
*/
/* picks up init parameter */
static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
static int sg_add_device(struct device *);
static void sg_remove_device(struct device *);
static DEFINE_IDR(sg_index_idr);
static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
file descriptor list for device */
@@ -1614,23 +1613,48 @@ sg_remove_device(struct device *cl_dev)
read_unlock_irqrestore(&sdp->sfd_lock, iflags);
sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
device_destroy(&sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));
cdev_del(sdp->cdev);
sdp->cdev = NULL;
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
@@ -1660,35 +1684,33 @@ MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
"size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
static int __init
init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
if (rc)
return rc;
rc = class_register(&sg_sysfs_class);
if (rc)
goto err_out;
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
return 0;
}
class_unregister(&sg_sysfs_class);
err_out:
unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
return rc;
}
@@ -1854,76 +1876,59 @@ static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
int blk_size = buff_size, order;
gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
if (blk_size < 0)
return -EFAULT;
if (0 == blk_size)
++blk_size; /* don't know why */
/* round request up to next highest SG_SECTOR_SZ byte boundary */
blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: buff_size=%d, blk_size=%d\n",
buff_size, blk_size));
/* N.B. ret_sz carried into this block ... */
mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
k, rem_sz));
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
return 0;
out:
for (i = 0; i < k; i++)
__free_pages(schp->pages[i], order);
if (--order >= 0)
goto retry;
return -ENOMEM;
}
]
|
| 685/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 8835
output: 37
thoughts: 29
Thoughts: Here's a summary of my thought process, as requested:
**Diving into the SCSI Driver**
Okay, time to get my hands dirty. I need to take a look at the `sg.c` driver, specifically lines 1640 through 1655. I'm going to use the `read-file` command, naturally. Let's see what's going on there. I'm hoping I can quickly assess the code in that area for [insert your field's relevant concerns, e.g., potential race conditions, buffer handling issues, error conditions, DMA setup]. I have a hunch it might relate to [mention your hypothesis based on the context]. Let's just pull up the code and see what surprises are in store.
|
| 686/5 |
2026/09/09 19:11 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1635 LineCount:30]
Results: map[Contents:1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
1650:
1651: module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
1652: S_IRUGO | S_IWUSR);
1653:
1654: MODULE_AUTHOR("Douglas Gilbert");
1655: MODULE_DESCRIPTION("SCSI generic (sg) driver");
1656: MODULE_LICENSE("GPL");
1657: MODULE_VERSION(SG_VERSION_STR);
1658: MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
1659:
1660: MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
1661: "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
1662: MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1663: MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
1664:
]
|
| 687/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 9557
output: 37
thoughts: 21
Thoughts: Okay, here's my attempt at summarizing the thought process, as requested, in the first person and targeted towards an expert:
**Delving into the Historical Context**
Alright, before I jump to any conclusions or start synthesizing, I need to zoom in a bit. My gut tells me there's something critical nestled between lines 1610 and 1640. That's the period I need to thoroughly re-examine. I know the material, but a quick re-read of the surrounding context is always a good practice before I form any new thoughts. Just have to make sure I don't miss anything subtle and I am not forming the wrong opinion. That particular range often contains the seed of understanding, that's what I'll begin with.
|
| 688/5 |
2026/09/09 19:11 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c FirstLine:1615 LineCount:35]
Results: map[Contents:1615:
1616: sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
1617: device_destroy(&sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));
1618: cdev_del(sdp->cdev);
1619: sdp->cdev = NULL;
1620:
1621: kref_put(&sdp->d_ref, sg_device_destroy);
1622: }
1623:
1624: module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
1625: module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1626:
1627: static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
1628: {
1629: int size, ret;
1630:
1631: if (!val)
1632: return -EINVAL;
1633:
1634: ret = kstrtoint(val, 0, &size);
1635: if (ret)
1636: return ret;
1637:
1638: /* limit to 1 MB */
1639: if (size < 0 || size > 1048576)
1640: return -ERANGE;
1641:
1642: def_reserved_size = size;
1643: return 0;
1644: }
1645:
1646: static const struct kernel_param_ops def_reserved_size_ops = {
1647: .set = def_reserved_size_set,
1648: .get = param_get_int,
1649: };
]
|
| 689/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 10326
output: 29
thoughts: 989
Thoughts: **Analyzing and Addressing a Kernel Style Warning**
Okay, here's the situation. I need to address a `checkpatch` warning regarding symbolic permissions in `drivers/scsi/sg.c`. Specifically, it flagged `S_IRUGO | S_IWUSR` and suggests replacing it with the octal equivalent `0644`.
First, I confirmed that the original code used `module_param_named` for `scatter_elem_sz` and `sg_allow_dio`. The change involves replacing `module_param_named` with `module_param_cb` for `scatter_elem_sz`, along with defining a set function (`scatter_elem_sz_set`) and `kernel_param_ops`.
The core of the issue is whether to use the symbolic constants or the octal representation for the permission flags within the `module_param_cb` call. The warning clearly directs me to use the octal form.
Now, a quick length check: the one-line version is 79 characters. Given the existing formatting in `sg.c`, specifically around line 1651 where `def_reserved_size` is handled using a two-line `module_param_cb`, I need to determine if it is more readable to keep it on one line.
I'll consult the kernel coding style and look for examples using `module_param_cb` within the `drivers/scsi/` directory to see how this kind of thing is usually handled. This will inform my decision on whether to put it on one line or two. I need to maintain consistency with existing code style. And after that, I can apply the fix to `sg.c`.
|
| 690/5 |
2026/09/09 19:11 |
tool |
grepper |
0m
Args: map[Expression:module_param_cb PathPrefix:drivers/scsi]
Results: map[Output:drivers/scsi/sg.c=1646=static const struct kernel_param_ops def_reserved_size_ops = {
--
drivers/scsi/sg.c-1650-
drivers/scsi/sg.c:1651:module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
drivers/scsi/sg.c-1652- S_IRUGO | S_IWUSR);
]
|
| 691/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 11840
output: 111
thoughts: 488
Thoughts: **Analyzing a Module Parameter Change**
Okay, so I'm looking at this `module_param_cb` call and thinking about how to clean it up a bit. Specifically, I'm considering changing the permission flags from `S_IRUGO | S_IWUSR` to the more direct octal representation, `0644`. I'm going to test the original code and the two options to keep line length.
First, I need to make sure I understand the original code block and what was changed. I'll quickly check the exact original code to confirm. Ah, here it is, pulled from the patch.
Now, I'm considering the one-line versus two-line format. The one-liner `module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);` comes in at 79 characters, which should be fine according to most style guides. But I want to verify what `checkpatch` thinks about the formatting of that line.
So, I'm going to use `codeeditor` with the current code to make sure I am working with the correct version of the code and then run `checkpatch`. I also will verify if the patch is applied.
|
| 692/5 |
2026/09/09 19:11 |
tool |
codeeditor |
0m
Args: map[CurrentCode:module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
S_IRUGO | S_IWUSR); NewCode:module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
0644); SourceFile:drivers/scsi/sg.c]
Results:
|
| 693/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 12720
output: 9
thoughts: 5
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert user and presented in the first person:
**Checkpatch Incoming**
Alright, time to get this show on the road. The code looks *mostly* clean to my eye, but we all know that's not enough. Experience has taught me the devil is in the details, and I *know* what subtle issues a seemingly innocent chunk of code can hide. Thus, it's time to unleash the beast. Run `checkpatch`! Let's see what it has to say. Even if I *think* I've caught everything, `checkpatch` has a knack for ferreting out the nitpicks I've missed – the trailing whitespace, the inconsistent indentation, the line length violations that only a dedicated tool can spot. This isn't about proving anything; it's about rigorous quality control. It's about ensuring this code adheres to the project's style guide and best practices, no matter how tedious that may seem. Better to catch these things now, during the static analysis phase, than have them bite me (or worse, someone else) later during integration or, heaven forbid, in a production environment. So, let's run it.
|
| 694/5 |
2026/09/09 19:11 |
tool |
checkpatch |
0m
Results: map[Output:total: 0 errors, 0 warnings, 91 lines checked
Your patch has no obvious style problems and is ready for submission.
]
|
| 695/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 13037
output: 104
thoughts: 62
Thoughts: Okay, let's break this down.
**Refactoring the `module_param_cb` Call**
I'm thinking about tidying up this `module_param_cb` call. It's currently on multiple lines, and I'm wondering if cramming it onto a single line would be more readable. Specifically, I'm considering combining `module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);` into one line. I suspect this might make it more compact.
But, I know I need to be thorough. I'll need to test this change thoroughly. I need to make sure I run it through `checkpatch` as well. That tool is pretty good at sniffing out style violations, so I need to make sure the single-line approach doesn't trigger any warnings or errors there. It’s also crucial to see if this affects its behavior in any way, even though I'm fairly certain it won't. I'll need to make sure I test it, though.
|
| 696/5 |
2026/09/09 19:11 |
tool |
codeeditor |
0m
Args: map[CurrentCode:module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
0644); NewCode:module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644); SourceFile:drivers/scsi/sg.c]
Results:
|
| 697/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 13445
output: 9
thoughts: 9
Thoughts: Okay, here's the summary, rendered as a first-person thought process, assuming the user is an expert.
**Checking the Code Integrity**
Right, before I dive too deep into this code, let's make sure it's clean and conforms to style guidelines. I know my own standards are high, but let's not introduce any easily-spotted regressions or inconsistencies. I need to make sure I run `checkpatch` on this before making any assumptions about its readability or correctness. That utility is my first port of call for ensuring I'm starting from a solid, compliant base. Let's see what that uncovers.
|
| 698/5 |
2026/09/09 19:11 |
tool |
checkpatch |
0m
Results: map[Output:total: 0 errors, 0 warnings, 90 lines checked
Your patch has no obvious style problems and is ready for submission.
]
|
| 699/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 13640
output: 33
thoughts: 54
Thoughts: Okay, let's break this down.
**Kernel Code Style Inquiry**
Hmm, before I commit to a particular style, I need to make sure I'm following established conventions within the kernel itself. I can't just wing it; it has to be idiomatic. So, my immediate thought is to determine the "best" or preferred way to handle this particular scenario – specifically, how `module_param_cb` is usually formatted in the kernel.
I need to quickly assess how seasoned kernel developers write this. Is there a clear preference, perhaps influenced by the 80-column line length rule? I should examine existing code, paying close attention to examples where the definition comfortably fits within the 80-column limit versus instances where it's necessary to split the definition across multiple lines. This will dictate if I need to do the same and follow their convention or not.
|
| 700/5 |
2026/09/09 19:11 |
tool |
grepper |
0m
Args: map[Expression:module_param_cb\(.*0644\); PathPrefix:]
Results: map[Output:arch/powerpc/kvm/book3s_hv.c=117=static const struct kernel_param_ops module_param_ops = {
--
arch/powerpc/kvm/book3s_hv.c-121-
arch/powerpc/kvm/book3s_hv.c:122:module_param_cb(kvm_irq_bypass, &module_param_ops, &kvm_irq_bypass, 0644);
arch/powerpc/kvm/book3s_hv.c-123-MODULE_PARM_DESC(kvm_irq_bypass, "Bypass passthrough interrupt optimization");
arch/powerpc/kvm/book3s_hv.c-124-
arch/powerpc/kvm/book3s_hv.c:125:module_param_cb(h_ipi_redirect, &module_param_ops, &h_ipi_redirect, 0644);
arch/powerpc/kvm/book3s_hv.c-126-MODULE_PARM_DESC(h_ipi_redirect, "Redirect H_IPI wakeup to a free host core");
--
arch/x86/kvm/mmu/mmu.c=84=static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
--
arch/x86/kvm/mmu/mmu.c-88-
arch/x86/kvm/mmu/mmu.c:89:module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
arch/x86/kvm/mmu/mmu.c-90-__MODULE_PARM_TYPE(nx_huge_pages, "bool");
--
arch/x86/kvm/vmx/vmx.c=479=static const struct kernel_param_ops vmentry_l1d_flush_ops = {
--
arch/x86/kvm/vmx/vmx.c-482-};
arch/x86/kvm/vmx/vmx.c:483:module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
arch/x86/kvm/vmx/vmx.c-484-
--
drivers/acpi/sysfs.c=146=static const struct kernel_param_ops param_ops_debug_level = {
--
drivers/acpi/sysfs.c-150-
drivers/acpi/sysfs.c:151:module_param_cb(debug_layer, ¶m_ops_debug_layer, &acpi_dbg_layer, 0644);
drivers/acpi/sysfs.c:152:module_param_cb(debug_level, ¶m_ops_debug_level, &acpi_dbg_level, 0644);
drivers/acpi/sysfs.c-153-
--
drivers/acpi/sysfs.c=209=static const struct kernel_param_ops param_ops_trace_attrib = {
--
drivers/acpi/sysfs.c-213-
drivers/acpi/sysfs.c:214:module_param_cb(trace_method_name, ¶m_ops_trace_method, &trace_method_name, 0644);
drivers/acpi/sysfs.c:215:module_param_cb(trace_debug_layer, ¶m_ops_trace_attrib, &acpi_gbl_trace_dbg_layer, 0644);
drivers/acpi/sysfs.c:216:module_param_cb(trace_debug_level, ¶m_ops_trace_attrib, &acpi_gbl_trace_dbg_level, 0644);
drivers/acpi/sysfs.c-217-
--
drivers/char/ipmi/ipmi_watchdog.c=286=MODULE_PARM_DESC(panic_wdt_timeout, "Timeout value on kernel panic in seconds.");
drivers/char/ipmi/ipmi_watchdog.c-287-
drivers/char/ipmi/ipmi_watchdog.c:288:module_param_cb(action, ¶m_ops_str, action_op, 0644);
drivers/char/ipmi/ipmi_watchdog.c-289-MODULE_PARM_DESC(action, "Timeout action. One of: "
--
drivers/char/ipmi/ipmi_watchdog.c-291-
drivers/char/ipmi/ipmi_watchdog.c:292:module_param_cb(preaction, ¶m_ops_str, preaction_op, 0644);
drivers/char/ipmi/ipmi_watchdog.c-293-MODULE_PARM_DESC(preaction, "Pretimeout action. One of: "
--
drivers/char/ipmi/ipmi_watchdog.c-295-
drivers/char/ipmi/ipmi_watchdog.c:296:module_param_cb(preop, ¶m_ops_str, preop_op, 0644);
drivers/char/ipmi/ipmi_watchdog.c-297-MODULE_PARM_DESC(preop, "Pretimeout driver operation. One of: "
--
drivers/dma/dmatest.c=163=static bool dmatest_run;
drivers/dma/dmatest.c:164:module_param_cb(run, &run_ops, &dmatest_run, 0644);
drivers/dma/dmatest.c-165-MODULE_PARM_DESC(run, "Run the test (default: false)");
--
drivers/dma/dmatest.c=175=static struct kparam_string newchan_kps = {
--
drivers/dma/dmatest.c-178-};
drivers/dma/dmatest.c:179:module_param_cb(channel, &multi_chan_ops, &newchan_kps, 0644);
drivers/dma/dmatest.c-180-MODULE_PARM_DESC(channel, "Bus ID of the channel to test (default: any)");
--
drivers/edac/i10nm_base.c=1084=static const struct kernel_param_ops decoding_via_mca_param_ops = {
--
drivers/edac/i10nm_base.c-1088-
drivers/edac/i10nm_base.c:1089:module_param_cb(decoding_via_mca, &decoding_via_mca_param_ops, &decoding_via_mca, 0644);
drivers/edac/i10nm_base.c-1090-MODULE_PARM_DESC(decoding_via_mca, "decoding_via_mca: 0=off(default), 1=enable");
--
drivers/firmware/efi/efi-pstore.c=46=static const struct kernel_param_ops pstore_disable_ops = {
--
drivers/firmware/efi/efi-pstore.c-50-
drivers/firmware/efi/efi-pstore.c:51:module_param_cb(pstore_disable, &pstore_disable_ops, &pstore_disable, 0644);
drivers/firmware/efi/efi-pstore.c-52-__MODULE_PARM_TYPE(pstore_disable, "bool");
--
drivers/firmware/qcom/qcom_scm.c=2744=static const struct kernel_param_ops download_mode_param_ops = {
--
drivers/firmware/qcom/qcom_scm.c-2748-
drivers/firmware/qcom/qcom_scm.c:2749:module_param_cb(download_mode, &download_mode_param_ops, NULL, 0644);
drivers/firmware/qcom/qcom_scm.c-2750-MODULE_PARM_DESC(download_mode, "download mode: off/0/N for no dump mode, full/on/1/Y for full dump mode, mini for minidump mode and full,mini for both full and m...
--
drivers/firmware/qcom/qcom_scm.c=2785=static const struct kernel_param_ops minidump_dest_param_ops = {
--
drivers/firmware/qcom/qcom_scm.c-2789-
drivers/firmware/qcom/qcom_scm.c:2790:module_param_cb(minidump_dest, &minidump_dest_param_ops, NULL, 0644);
drivers/firmware/qcom/qcom_scm.c-2791-MODULE_PARM_DESC(minidump_dest, "Minidump SRAM destination: usb (default) or storage");
--
drivers/gpu/drm/drm_panic.c=852=static const struct kernel_param_ops drm_panic_ops = {
--
drivers/gpu/drm/drm_panic.c-856-
drivers/gpu/drm/drm_panic.c:857:module_param_cb(panic_screen, &drm_panic_ops, NULL, 0644);
drivers/gpu/drm/drm_panic.c-858-MODULE_PARM_DESC(panic_screen,
--
drivers/hid/hid-cougar.c=317=static const struct kernel_param_ops cougar_g6_is_space_ops = {
--
drivers/hid/hid-cougar.c-320-};
drivers/hid/hid-cougar.c:321:module_param_cb(g6_is_space, &cougar_g6_is_space_ops, &g6_is_space, 0644);
drivers/hid/hid-cougar.c-322-
--
drivers/hid/hid-steam.c=2727=static const struct kernel_param_ops steam_lizard_mode_ops = {
--
drivers/hid/hid-steam.c-2731-
drivers/hid/hid-steam.c:2732:module_param_cb(lizard_mode, &steam_lizard_mode_ops, &lizard_mode, 0644);
drivers/hid/hid-steam.c-2733-MODULE_PARM_DESC(lizard_mode,
--
drivers/infiniband/ulp/isert/ib_isert.c=38=static int isert_sg_tablesize = ISCSI_ISER_MIN_SG_TABLESIZE;
drivers/infiniband/ulp/isert/ib_isert.c:39:module_param_cb(sg_tablesize, &sg_tablesize_ops, &isert_sg_tablesize, 0644);
drivers/infiniband/ulp/isert/ib_isert.c-40-MODULE_PARM_DESC(sg_tablesize,
--
drivers/media/usb/uvc/uvc_driver.c=2497=param_check_uint(nodrop, &uvc_no_drop_param);
drivers/media/usb/uvc/uvc_driver.c:2498:module_param_cb(nodrop, ¶m_ops_nodrop, &uvc_no_drop_param, 0644);
drivers/media/usb/uvc/uvc_driver.c-2499-__MODULE_PARM_TYPE(nodrop, "uint");
--
drivers/nvme/host/pci.c=108=static unsigned int io_queue_depth = 1024;
drivers/nvme/host/pci.c:109:module_param_cb(io_queue_depth, &io_queue_depth_ops, &io_queue_depth, 0644);
drivers/nvme/host/pci.c-110-MODULE_PARM_DESC(io_queue_depth, "set io queue depth, should >= 2 and < 4096");
--
drivers/nvme/host/pci.c=266=static unsigned int write_queues;
drivers/nvme/host/pci.c:267:module_param_cb(write_queues, &io_queue_count_ops, &write_queues, 0644);
drivers/nvme/host/pci.c-268-MODULE_PARM_DESC(write_queues,
--
drivers/nvme/host/pci.c=272=static unsigned int poll_queues;
drivers/nvme/host/pci.c:273:module_param_cb(poll_queues, &io_queue_count_ops, &poll_queues, 0644);
drivers/nvme/host/pci.c-274-MODULE_PARM_DESC(poll_queues, "Number of queues to use for polled IO.");
--
drivers/nvme/target/rdma.c=155=static unsigned int nvmet_rdma_srq_size = 1024;
drivers/nvme/target/rdma.c:156:module_param_cb(srq_size, &srq_size_ops, &nvmet_rdma_srq_size, 0644);
drivers/nvme/target/rdma.c-157-MODULE_PARM_DESC(srq_size, "set Shared Receive Queue (SRQ) size, should >= 256 (default: 1024)");
--
drivers/power/supply/bq27xxx_battery.c=1141=static unsigned int poll_interval = 360;
drivers/power/supply/bq27xxx_battery.c:1142:module_param_cb(poll_interval, ¶m_ops_poll_interval, &poll_interval, 0644);
drivers/power/supply/bq27xxx_battery.c-1143-MODULE_PARM_DESC(poll_interval,
--
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c=86=static const struct kernel_param_ops slider_def_balance_ops = {
--
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c-90-
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c:91:module_param_cb(slider_balance, &slider_def_balance_ops, NULL, 0644);
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c-92-MODULE_PARM_DESC(slider_balance, "Set slider default value for balance");
--
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c=120=static const struct kernel_param_ops slider_offset_ops = {
--
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c-131- */
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c:132:module_param_cb(slider_offset, &slider_offset_ops, NULL, 0644);
drivers/thermal/intel/int340x_thermal/processor_thermal_soc_slider.c-133-MODULE_PARM_DESC(slider_offset, "Set slider offset");
--
drivers/thermal/intel/intel_powerclamp.c=115=static const struct kernel_param_ops duration_ops = {
--
drivers/thermal/intel/intel_powerclamp.c-119-
drivers/thermal/intel/intel_powerclamp.c:120:module_param_cb(duration, &duration_ops, NULL, 0644);
drivers/thermal/intel/intel_powerclamp.c-121-MODULE_PARM_DESC(duration, "forced idle time for each attempt in msec.");
--
drivers/thermal/intel/intel_powerclamp.c=206=static const struct kernel_param_ops cpumask_ops = {
--
drivers/thermal/intel/intel_powerclamp.c-210-
drivers/thermal/intel/intel_powerclamp.c:211:module_param_cb(cpumask, &cpumask_ops, NULL, 0644);
drivers/thermal/intel/intel_powerclamp.c-212-MODULE_PARM_DESC(cpumask, "Mask of CPUs to use for idle injection.");
--
drivers/thermal/intel/intel_powerclamp.c=255=static const struct kernel_param_ops max_idle_ops = {
--
drivers/thermal/intel/intel_powerclamp.c-259-
drivers/thermal/intel/intel_powerclamp.c:260:module_param_cb(max_idle, &max_idle_ops, &max_idle, 0644);
drivers/thermal/intel/intel_powerclamp.c-261-MODULE_PARM_DESC(max_idle, "maximum injected idle time to the total CPU time ratio in percent range:1-100");
--
drivers/thermal/intel/intel_powerclamp.c=302=static const struct kernel_param_ops window_size_ops = {
--
drivers/thermal/intel/intel_powerclamp.c-306-
drivers/thermal/intel/intel_powerclamp.c:307:module_param_cb(window_size, &window_size_ops, &window_size, 0644);
drivers/thermal/intel/intel_powerclamp.c-308-MODULE_PARM_DESC(window_size, "sliding window in number of clamping cycles\n"
--
drivers/ufs/core/ufs-fault-injection.c=25=static char g_trigger_eh_str[FAULT_INJ_STR_SIZE];
drivers/ufs/core/ufs-fault-injection.c:26:module_param_cb(trigger_eh, &ufs_fault_ops, g_trigger_eh_str, 0644);
drivers/ufs/core/ufs-fault-injection.c-27-MODULE_PARM_DESC(trigger_eh,
--
drivers/ufs/core/ufs-fault-injection.c=31=static char g_timeout_str[FAULT_INJ_STR_SIZE];
drivers/ufs/core/ufs-fault-injection.c:32:module_param_cb(timeout, &ufs_fault_ops, g_timeout_str, 0644);
drivers/ufs/core/ufs-fault-injection.c-33-MODULE_PARM_DESC(timeout,
--
drivers/ufs/core/ufs-mcq.c=51=static unsigned int rw_queues;
drivers/ufs/core/ufs-mcq.c:52:module_param_cb(rw_queues, &rw_queue_count_ops, &rw_queues, 0644);
drivers/ufs/core/ufs-mcq.c-53-MODULE_PARM_DESC(rw_queues,
--
drivers/ufs/core/ufs-mcq.c=67=static unsigned int read_queues;
drivers/ufs/core/ufs-mcq.c:68:module_param_cb(read_queues, &read_queue_count_ops, &read_queues, 0644);
drivers/ufs/core/ufs-mcq.c-69-MODULE_PARM_DESC(read_queues,
--
drivers/ufs/core/ufs-mcq.c=83=static unsigned int poll_queues = 1;
drivers/ufs/core/ufs-mcq.c:84:module_param_cb(poll_queues, &poll_queue_count_ops, &poll_queues, 0644);
drivers/ufs/core/ufs-mcq.c-85-MODULE_PARM_DESC(poll_queues,
--
drivers/ufs/core/ufs-txeq.c=35=static unsigned int adaptive_txeq_gear = UFS_HS_G6;
drivers/ufs/core/ufs-txeq.c:36:module_param_cb(adaptive_txeq_gear, &txeq_gear_ops, &adaptive_txeq_gear, 0644);
drivers/ufs/core/ufs-txeq.c-37-MODULE_PARM_DESC(adaptive_txeq_gear, "For HS-Gear[n] and above, adaptive txeq shall be used");
--
drivers/ufs/core/ufs-txeq.c=57=static unsigned int txeq_setting_sel;
drivers/ufs/core/ufs-txeq.c:58:module_param_cb(txeq_setting_sel, &txeq_setting_sel_ops, &txeq_setting_sel, 0644);
drivers/ufs/core/ufs-txeq.c-59-MODULE_PARM_DESC(txeq_setting_sel, "The qTxEQGnSettings and wTxEQGnSettingsExt Attributes selector used to retrieve and store TX Equalization settings");
--
drivers/ufs/core/ufshcd.c=131=static const struct kernel_param_ops uic_cmd_timeout_ops = {
--
drivers/ufs/core/ufshcd.c-135-
drivers/ufs/core/ufshcd.c:136:module_param_cb(uic_cmd_timeout, &uic_cmd_timeout_ops, &uic_cmd_timeout, 0644);
drivers/ufs/core/ufshcd.c-137-MODULE_PARM_DESC(uic_cmd_timeout,
--
drivers/ufs/core/ufshcd.c=148=static const struct kernel_param_ops dev_cmd_timeout_ops = {
--
drivers/ufs/core/ufshcd.c-152-
drivers/ufs/core/ufshcd.c:153:module_param_cb(dev_cmd_timeout, &dev_cmd_timeout_ops, &dev_cmd_timeout, 0644);
drivers/ufs/core/ufshcd.c-154-MODULE_PARM_DESC(dev_cmd_timeout,
--
drivers/usb/gadget/legacy/serial.c=124=static const struct kernel_param_ops enable_ops = {
--
drivers/usb/gadget/legacy/serial.c-128-
drivers/usb/gadget/legacy/serial.c:129:module_param_cb(enable, &enable_ops, &enable, 0644);
drivers/usb/gadget/legacy/serial.c-130-
--
drivers/usb/storage/usb.c=161=static const struct kernel_param_ops delay_use_ops = {
--
drivers/usb/storage/usb.c-164-};
drivers/usb/storage/usb.c:165:module_param_cb(delay_use, &delay_use_ops, &delay_use, 0644);
drivers/usb/storage/usb.c-166-MODULE_PARM_DESC(delay_use, "time to delay before using a new device");
--
drivers/vhost/scsi.c=90=static const struct kernel_param_ops vhost_scsi_inline_sg_cnt_op = {
--
drivers/vhost/scsi.c-94-
drivers/vhost/scsi.c:95:module_param_cb(inline_sg_cnt, &vhost_scsi_inline_sg_cnt_op, NULL, 0644);
drivers/vhost/scsi.c-96-MODULE_PARM_DESC(inline_sg_cnt, "Set the number of scatterlist entries to pre-allocate. The default is 2048.");
--
drivers/virt/nitro_enclaves/ne_misc_dev.c=95=static struct kparam_string ne_cpus_arg = {
--
drivers/virt/nitro_enclaves/ne_misc_dev.c-99-
drivers/virt/nitro_enclaves/ne_misc_dev.c:100:module_param_cb(ne_cpus, &ne_cpu_pool_ops, &ne_cpus_arg, 0644);
drivers/virt/nitro_enclaves/ne_misc_dev.c-101-/* https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html#cpu-lists */
--
fs/ceph/super.c=1707=bool disable_send_metrics = false;
fs/ceph/super.c:1708:module_param_cb(disable_send_metrics, ¶m_ops_metrics, &disable_send_metrics, 0644);
fs/ceph/super.c-1709-MODULE_PARM_DESC(disable_send_metrics, "Enable sending perf metrics to ceph cluster (default: on)");
--
fs/fuse/dir.c=73=static const struct kernel_param_ops inval_wq_ops = {
--
fs/fuse/dir.c-76-};
fs/fuse/dir.c:77:module_param_cb(inval_wq, &inval_wq_ops, &inval_wq, 0644);
fs/fuse/dir.c-78-__MODULE_PARM_TYPE(inval_wq, "uint");
--
fs/nfs/inode.c=2805=MODULE_LICENSE("GPL");
fs/nfs/inode.c:2806:module_param_cb(enable_ino64, ¶m_ops_enable_ino64, &enable_ino64, 0644);
fs/nfs/inode.c-2807-
--
kernel/rcu/tree.c=507=static const struct kernel_param_ops next_fqs_jiffies_ops = {
--
kernel/rcu/tree.c-511-
kernel/rcu/tree.c:512:module_param_cb(jiffies_till_first_fqs, &first_fqs_jiffies_ops, &jiffies_till_first_fqs, 0644);
kernel/rcu/tree.c:513:module_param_cb(jiffies_till_next_fqs, &next_fqs_jiffies_ops, &jiffies_till_next_fqs, 0644);
kernel/rcu/tree.c-514-module_param(rcu_kick_kthreads, bool, 0644);
--
kernel/rcu/tree.c=4062=static atomic_t do_rcu_barrier;
kernel/rcu/tree.c:4063:module_param_cb(do_rcu_barrier, &do_rcu_barrier_ops, &do_rcu_barrier, 0644);
kernel/rcu/tree.c-4064-
--
kernel/workqueue.c=7316=static const struct kernel_param_ops wq_affn_dfl_ops = {
--
kernel/workqueue.c-7320-
kernel/workqueue.c:7321:module_param_cb(default_affinity_scope, &wq_affn_dfl_ops, NULL, 0644);
kernel/workqueue.c-7322-
--
mm/memory_hotplug.c=168=static const struct kernel_param_ops online_policy_ops = {
--
mm/memory_hotplug.c-171-};
mm/memory_hotplug.c:172:module_param_cb(online_policy, &online_policy_ops, &online_policy, 0644);
mm/memory_hotplug.c-173-MODULE_PARM_DESC(online_policy,
--
mm/zswap.c=93=static const struct kernel_param_ops zswap_enabled_param_ops = {
--
mm/zswap.c-96-};
mm/zswap.c:97:module_param_cb(enabled, &zswap_enabled_param_ops, &zswap_enabled, 0644);
mm/zswap.c-98-
--
net/ipv4/tcp_dctcp.c=67=static const struct kernel_param_ops dctcp_shift_g_ops = {
--
net/ipv4/tcp_dctcp.c-71-
net/ipv4/tcp_dctcp.c:72:module_param_cb(dctcp_shift_g, &dctcp_shift_g_ops, &dctcp_shift_g, 0644);
net/ipv4/tcp_dctcp.c-73-MODULE_PARM_DESC(dctcp_shift_g, "parameter g for updating dctcp_alpha");
]
|
| 701/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 21099
output: 23
thoughts: 847
Thoughts: **Analyzing Code Style for `module_param_cb`**
Okay, so I'm looking at this `module_param_cb` line: `module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);`. It's 79 characters, which neatly fits within the 80-character limit, and checkpatch gave me no errors or warnings which is great. I was a bit concerned about it being so close to the limit, but 79 is *strictly less than* 80. The kernel coding style emphasizes 80 chars, but with a soft limit up to 100 which is fine, 79 chars is completely fine.
Now, let's compare. Originally, it was split across two lines because it used the symbolic permissions `S_IRUGO | S_IWUSR`, which made the line exceed 80 characters:
```c
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz,
+ S_IRUGO | S_IWUSR);
```
That was 90 characters on one line, so splitting was the right move there. But now, with the octal permissions `0644`, it fits on a single line. The original patch did the right thing in splitting the line for symbolic permissions.
Hmm, but is there *any* reason to split it now? It seems natural to keep it on one line since it fits. I wonder what a reviewer or maintainer might think.
Also, I just remembered, the same file has an example with the same style on line 1651:
```c
module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
S_IRUGO | S_IWUSR);
```
Even without permissions, `def_reserved_size` was 78 characters which required it to be split.
Let's quickly check what checkpatch says about both cases:
`module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);` and the split version gives no errors, and no warnings, so that's good!
However, I remember Linux kernel coding style generally discourages putting only the single argument `0644);` on the second line. That looks unusual.
Looks like keeping it on one line is preferable:
`module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);` is the right choice.
|
| 702/5 |
2026/09/09 19:11 |
tool |
patch-diff |
0m
Args: map[File:drivers/scsi/sg.c]
Results: map[Output:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..4c82fc00d 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -85,21 +85,20 @@ static int sg_proc_init(void);
* /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
* of this size (or less if there is not enough memory) will be reserved
* for use by this file descriptor.
*/
/* picks up init parameter */
static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
static int sg_add_device(struct device *);
static void sg_remove_device(struct device *);
static DEFINE_IDR(sg_index_idr);
static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock
file descriptor list for device */
@@ -1614,23 +1613,47 @@ sg_remove_device(struct device *cl_dev)
read_unlock_irqrestore(&sdp->sfd_lock, iflags);
sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
device_destroy(&sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index));
cdev_del(sdp->cdev);
sdp->cdev = NULL;
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
if (!val)
return -EINVAL;
ret = kstrtoint(val, 0, &size);
if (ret)
return ret;
@@ -1660,35 +1683,33 @@ MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
"size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
static int __init
init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
if (rc)
return rc;
rc = class_register(&sg_sysfs_class);
if (rc)
goto err_out;
sg_sysfs_valid = 1;
rc = scsi_register_interface(&sg_interface);
if (0 == rc) {
#ifdef CONFIG_SCSI_PROC_FS
sg_proc_init();
#endif /* CONFIG_SCSI_PROC_FS */
return 0;
}
class_unregister(&sg_sysfs_class);
err_out:
unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
return rc;
}
@@ -1854,76 +1875,59 @@ static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
int blk_size = buff_size, order;
gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
if (blk_size < 0)
return -EFAULT;
if (0 == blk_size)
++blk_size; /* don't know why */
/* round request up to next highest SG_SECTOR_SZ byte boundary */
blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: buff_size=%d, blk_size=%d\n",
buff_size, blk_size));
/* N.B. ret_sz carried into this block ... */
mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
} /* end of for loop */
schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
k, rem_sz));
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
return 0;
out:
for (i = 0; i < k; i++)
__free_pages(schp->pages[i], order);
if (--order >= 0)
goto retry;
return -ENOMEM;
}
]
|
| 703/5 |
2026/09/09 19:11 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 24932
output: 9
thoughts: 15
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Kernel Code Hygiene Check**
Okay, before I even *think* about submitting this patch, I'm going to run `checkpatch.pl` again. No, I *know* I've run it multiple times already, but I've been making a few tweaks, and I *really* don't want to get anything kicked back for a stupid whitespace error or a coding style violation that I missed. It's just good practice to verify the current state of the codebase. I need a clean run before I consider this ready for review. This is second nature after so much experience. I'll make sure there are no warnings or errors reported, even if they seem minor. I'm aiming for pristine, not just "good enough."
|
| 704/5 |
2026/09/09 19:12 |
tool |
checkpatch |
0m
Error:
|
| 705/5 |
2026/09/09 19:12 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 25269
output: 71
thoughts: 133
Thoughts: **Ready for Submission**
Okay, the `checkpatch` tool gave us a clean bill of health. No errors, no warnings, and ninety lines checked – all good. The patch is looking stylistically clean and ready to go. The requested change regarding symbolic permissions was straightforward. Replacing `S_IRUGO | S_IWUSR` with the octal equivalent, `0644`, in the `module_param_cb` function fixed that issue cleanly. With this style check complete and the requested change implemented, we are in a strong position to provide the user with the final response.
|
| 706/4 |
2026/09/09 19:12 |
action |
test-patch-inplace |
12m
Results: map[PatchDiff:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..4c82fc00d 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,33 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1690,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1894,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
TestError:]
|
| 707/4 |
2026/09/09 19:24 |
action |
run-checkpatch |
0m
Results: map[CheckpatchOutput:total: 0 errors, 0 warnings, 90 lines checked
Your patch has no obvious style problems and is ready for submission.
]
|
| 708/2 |
2026/09/09 19:24 |
iteration |
1 |
0m
|
| 709/3 |
2026/09/09 19:24 |
agent |
checkpatch-arbiter |
0m
Model:
Results:
Instruction:
You are an expert Linux kernel maintainer acting as a code style arbiter.
Your task is to review scripts/checkpatch.pl output and reviewer style requests for a proposed patch.
Determine which reported issues are genuine, actionable formatting/style defects (e.g. indentation, whitespace,
naming, syntax style) and should be fixed. List them in ActionableIssues.
Ignore issues that are false positives, intentional constructs (e.g. BUG_ON/XA_BUG_ON in test files, macros,
subsystem conventions), or unfixable without breaking code logic or tests. If no issues should be changed,
leave ActionableIssues empty.
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 patch diff is:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..4c82fc00d 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,33 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1690,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1894,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
The checkpatch.pl output is:
total: 0 errors, 0 warnings, 90 lines checked
Your patch has no obvious style problems and is ready for submission.
Carefully evaluate each issue and populate ActionableIssues.
|
| 710/4 |
2026/09/09 19:24 |
llm |
checkpatch-arbiter |
0m
Model:
Tokens:
input: 1582
output: 15
thoughts: 1581
Thoughts: **Reviewing the SG Driver Patch**
Okay, so I've been given a git patch diff for `drivers/scsi/sg.c` along with the output from `checkpatch.pl`. My task is to go through this, look for any actionable formatting or style issues and indicate any items. I'm an expert in this, so let's get down to it.
The first thing I did was look at the provided checkpatch output. It claims "total: 0 errors, 0 warnings". Right away, that's a good sign. The instructions specifically mention checking for *actionable* style defects, so it's not simply about *finding* problems, but about determining if any are legitimate style concerns that need to be addressed before submission.
The absence of any reviewer comments also means that I'm relying solely on the automated checkpatch output and my own expert review of the patch to make the determination.
I went and closely re-reviewed the patch diff itself, making sure there were no subtle formatting anomalies that `checkpatch` might have missed. After this review, I'm confident that the checkpatch output is correct. The changes look clean, and I see no obvious indentation, whitespace, naming, or syntax style issues. I'm not picking up any concerns that I would see as "actionable."
Since checkpatch is saying it's ready for submission and I don't see anything, I'm going to leave the `ActionableIssues` list empty. This patch appears to be free of stylistic defects.
|
| 711/4 |
2026/09/09 19:25 |
tool |
set-results |
0m
Args:
Results:
|
| 712/3 |
2026/09/09 19:25 |
action |
evaluate-checkpatch-arbiter |
0m
Results: map[NeedRefinement:false]
|
| 713/3 |
2026/09/09 19:25 |
action |
If |
0m
Args: map[NeedRefinement:false]
|
| 714/1 |
2026/09/09 19:25 |
agent |
fixes-finder |
14m
Model:
Results: map[FixesHash:10db10d144c0248f285242f79daf6b9de6b00a62]
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 ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
The explanation of the root cause is:
An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
The patch that fixes the bug is:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..4c82fc00d 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,33 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1690,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1894,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
Search for the commit(s) that introduced this bug.
|
| 715/2 |
2026/09/09 19:25 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 7696
output: 76
thoughts: 490
Thoughts: **Tracing the Bug Introduction**
Okay, so I've got a crash report, a breakdown of what's gone wrong, and a patch that should fix it. Now my job is to pinpoint the exact commit that *introduced* this bug. That's the key to understanding why this regression happened and preventing it in the future.
Looking at the patch itself, it's pretty clear that it involves `scatter_elem_sz_prev`. The old code seems to be tracking `scatter_elem_sz` and `scatter_elem_sz_prev` to ensure they stay in sync, but there's a problem somewhere. Specifically, the diff modifies the relationship between the two. The old code ensured that the values tracked each other and had logic to reset them, now it's gone.
My next step is to use some Git magic. I'm going to lean on `git blame` or `git log`. I can trace the history of `scatter_elem_sz_prev` or even `sg_build_indirect` in `drivers/scsi/sg.c` to see when those lines of code were added or last modified. That should give me the commit that caused this issue. Let's get to work!
|
| 716/2 |
2026/09/09 19:25 |
tool |
git-blame |
0m
Args: map[End:1915 File:drivers/scsi/sg.c Start:1870]
Results: map[Output:d6b10348f9397 1870)
d6b10348f9397 1871) /* N.B. ret_sz carried into this block ... */
d6b10348f9397 1872) mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
d6b10348f9397 1873) if (mx_sc_elems < 0)
d6b10348f9397 1874) return mx_sc_elems; /* most likely -ENOMEM */
d6b10348f9397 1875)
6460e75a104d1 1876) num = scatter_elem_sz;
6460e75a104d1 1877) if (unlikely(num != scatter_elem_sz_prev)) {
6460e75a104d1 1878) if (num < PAGE_SIZE) {
6460e75a104d1 1879) scatter_elem_sz = PAGE_SIZE;
6460e75a104d1 1880) scatter_elem_sz_prev = PAGE_SIZE;
6460e75a104d1 1881) } else
6460e75a104d1 1882) scatter_elem_sz_prev = num;
6460e75a104d1 1883) }
10db10d144c02 1884)
10db10d144c02 1885) order = get_order(num);
10db10d144c02 1886) retry:
10db10d144c02 1887) ret_sz = 1 << (PAGE_SHIFT + order);
10db10d144c02 1888)
10db10d144c02 1889) for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
10db10d144c02 1890) k++, rem_sz -= ret_sz) {
10db10d144c02 1891)
6460e75a104d1 1892) num = (rem_sz > scatter_elem_sz_prev) ?
10db10d144c02 1893) scatter_elem_sz_prev : rem_sz;
10db10d144c02 1894)
5b9d397447f8c 1895) schp->pages[k] = alloc_pages(gfp_mask, order);
10db10d144c02 1896) if (!schp->pages[k])
10db10d144c02 1897) goto out;
d6b10348f9397 1898)
6460e75a104d1 1899) if (num == scatter_elem_sz_prev) {
6460e75a104d1 1900) if (unlikely(ret_sz > scatter_elem_sz_prev)) {
6460e75a104d1 1901) scatter_elem_sz = ret_sz;
6460e75a104d1 1902) scatter_elem_sz_prev = ret_sz;
6460e75a104d1 1903) }
6460e75a104d1 1904) }
d6b10348f9397 1905)
95e159d6dd808 1906) SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
95e159d6dd808 1907) "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
95e159d6dd808 1908) k, num, ret_sz));
d6b10348f9397 1909) } /* end of for loop */
d6b10348f9397 1910)
10db10d144c02 1911) schp->page_order = order;
d6b10348f9397 1912) schp->k_use_sg = k;
95e159d6dd808 1913) SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
95e159d6dd808 1914) "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
95e159d6dd808 1915) k, rem_sz));
]
|
| 717/2 |
2026/09/09 19:25 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz_prev PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 718/2 |
2026/09/09 19:25 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 10028
output: 55
thoughts: 46
Thoughts: Okay, here's my interpretation of those instructions, presented as a first-person expert summary:
**Analyzing Commits: 6460e75a104d1 and 10db10d144c02**
Alright, let's dive right in. The immediate instruction is clear: I need to take a look at two specific commits, `6460e75a104d1` and `10db10d144c02`. Given my understanding of version control and the implied context (this being a technical task), my first thought is to use `git show` on both of these. I mean, that's the go-to for a detailed view, right?
I'll be looking for diffs, author information, commit messages – the whole shebang. Knowing the specifics of the commits is key to forming a relevant analysis. My expectation is to compare these two commits directly. The purpose isn't explicit but likely hinges on comparing the work between these commits. Perhaps there's a bug fix, a feature addition, or a refactor being scrutinized. I will need to understand what changed, and why, and what impact that had on the system. I will look for any clues.
This is all about efficient exploration and information gathering. This is the first step in understanding the evolution of the code or data or whatever is being tracked. I am ready to dig in and understand.
|
| 719/2 |
2026/09/09 19:25 |
tool |
git-show |
0m
Args: map[Commit:6460e75a104d1]
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 720/2 |
2026/09/09 19:25 |
tool |
git-show |
0m
Args: map[Commit:10db10d144c02]
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 721/2 |
2026/09/09 19:25 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 24492
output: 35
thoughts: 3547
Thoughts: **Root Cause Analysis of the SG Driver Crash**
Alright, let's break this down systematically. The provided crash report points to an "undefined behavior" issue within the SCSI Generic (sg) driver, specifically related to an out-of-bounds shift operation. The core problem, as I see it, stems from how a local variable `num` is handled within the `sg_build_indirect()` function.
My initial thought was to verify the information in the provided analysis by checking the commit history. I looked at the critical code block within `sg_build_indirect` that's implicated in the crash:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
My initial thought was that the explanation was incorrect, because 6460e75a104d seemed to introduce the problematic code, but I quickly realized that the code *was* correct in that commit, because `num` was overwritten inside the loop so the value of `num` was not important after the `if` statement.
The crucial event was in commit **10db10d144c02**. This commit introduced the lines:
```c
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
This is where the bug manifests. `num` is used to calculate `order`. In this version, `num` is initialized to `scatter_elem_sz`, and if the value of `scatter_elem_sz` is set to 0, and because it passes the condition `num < PAGE_SIZE`, in the `if` block, we only update `scatter_elem_sz` and `scatter_elem_sz_prev`, but not `num`. Thus, when `get_order(num)` is called, `num` is 0.
Based on `include/asm-generic/getorder.h`, `get_order(0)` is undefined. The macro expands to something that results in `order` becoming 52.
This leads directly to the out-of-bounds shift. Since `order` is 52 and `PAGE_SHIFT` is typically 12, the exponent for the bit shift becomes 64. Shifting a 32-bit integer by 64 bits is undefined behavior and, boom, UBSAN panics.
So, in summary, commit 10db10d144c02 is where the issue was introduced. It's a combination of setting the module parameter to a specific value, the use of `get_order(num)`, and the subsequent bit-shift operation that triggers the undefined behavior if a certain condition is met. The missing update to the local variable `num`, while the global variable is updated, is the crucial oversight that leads to the crash.
|
| 722/2 |
2026/09/09 19:25 |
tool |
git-log |
0m
Error:
Args: map[PathPrefix:drivers/scsi/sg.c SymbolName:sg_build_indirect]
Results:
|
| 723/2 |
2026/09/09 19:25 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 28771
output: 35
thoughts: 14
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Thinking Through Git Log Integration**
Okay, so I'm thinking about how to integrate `git log` with our system. The core issue, as always, is granularity and efficient data retrieval. My immediate thought is to use `git log` with two key pieces of information: the `SymbolName` and the `SourcePath`. This pairing is crucial. We can use the symbol name as the primary filter, allowing us to hone in on commits that potentially touch the code related to that specific function or class. The source path then becomes an additional layer of refinement – it allows us to narrow the scope within the repository, ensuring we're only looking at changes within the relevant directory structure. This avoids false positives and limits the amount of data we need to process, especially with larger codebases. The next step is to consider how we'll parse the output effectively and build the relevant data structures to represent the commit history within our system, but first, let's get a good picture of the data from git.
|
| 724/2 |
2026/09/09 19:25 |
tool |
git-log |
0m
Args: map[SourcePath:drivers/scsi/sg.c SymbolName:sg_build_indirect]
Results: map[Output:1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 725/2 |
2026/09/09 19:26 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 29080
output: 36
thoughts: 136
Thoughts: **Investigating the `sg_build_indirect` Function in the SCSI Driver**
Okay, let's dive into this. I need to understand the history or changes around the `sg_build_indirect` function within the SCSI driver. My first instinct is to use `git log -L :sg_build_indirect:drivers/scsi/sg.c` – that should pinpoint exactly the lines of code and their history. Alternatively, I could just use `git log` with `PathPrefix="drivers/scsi/sg.c"` to view all changes within that file. I'm wondering why my initial attempt to use `SymbolName` only showed a specific commit hash, likely `1da177e4c3f4`. I have to remember that `-L` in `git log` focuses on changes in the *current* state of the code, or perhaps even just the commit I indicated, `1da177e4c3f4`, so that would explain the limitation. Now, I need to remind myself, does `drivers/scsi/sg.c` actually *have* the function `sg_build_indirect` defined? It should, given the path, but I need to make sure. Let me confirm, as well, with a search for a pattern. Okay, let's switch gears and check using `git log` and the `CodeRegexp="order = get_order"`. That should help trace changes related to memory ordering, or the `get_order` function, if it is relevant.
|
| 726/2 |
2026/09/09 19:26 |
tool |
git-log |
0m
Args: map[CodeRegexp:order = get_order PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
]
|
| 727/2 |
2026/09/09 19:26 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 29616
output: 22
thoughts: 58
Thoughts: **Checking for Pre-Existing Fixes**
Okay, before I dive too deep into this, I need to be absolutely sure I'm not duplicating effort. The first thing I'm going to do is a thorough check to see if this issue – or a patch addressing it – has already surfaced in the commit history. I don't want to reinvent the wheel, especially in a codebase like this. Let's see if anyone has addressed the 'scatter_elem_sz,' 'sg_build_indirect,' or the 'shift exponent 64' concepts in their commits. I'll need to use some targeted keywords in my search. My goal here is to quickly ascertain whether this has been handled elsewhere, or whether I can save myself some time.
|
| 728/2 |
2026/09/09 19:26 |
tool |
git-log |
0m
Args: map[MessageRegexps:[scatter_elem_sz]]
Results: map[Output:4d2de3a50ce1 [SCSI] fix BUG when sum(scatterlist) > bufflen
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 729/2 |
2026/09/09 19:26 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 29917
output: 24
thoughts: 66
Thoughts: **Checking the Git History**
Okay, before I go down a rabbit hole, let's see if the fix itself has a readily available history. I'll search the git log, specifically looking for the relevant patch. I'll focus on the function name within the patch; specifically, I need to see if `static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)` is present within the commit history. That function name should be a good starting point to confirm it’s the fix I'm looking for.
|
| 730/2 |
2026/09/09 19:26 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:scatter_elem_sz_set]
Results:
|
| 731/2 |
2026/09/09 19:36 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 30161
output: 38
thoughts: 19
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Adding a Specific Path Prefix for SG Driver Code**
Right, let's get down to brass tacks. I'm thinking about how we're organizing this codebase and it strikes me that we really need to be precise with how we're referencing files. I'm imagining how we're going to search for things, and especially how an IDE or build system might traverse things, and it makes sense to nail down the precise file location for the `sg.c` SCSI generic driver. So, I'm thinking, "Let's explicitly add the `PathPrefix: "drivers/scsi/sg.c"` specification." Doing this makes it explicitly clear that we're talking about that *specific* implementation within the SCSI subsystem's driver directory. This will help with clarity, reduce ambiguity, and potentially streamline build processes or tooling down the line. I want to make sure the build knows exactly where this thing lives, and this `PathPrefix` directive gives us that absolute certainty. It also helps with code readability because it shows that it comes from the `scsi` subsystem.
|
| 732/2 |
2026/09/09 19:36 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz_set PathPrefix:drivers/scsi/sg.c]
Results:
|
| 733/2 |
2026/09/09 19:36 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 30484
output: 14
thoughts: 42
Thoughts: Okay, here's my take on those thoughts, framed as my own mental process, given my expertise:
**Checking Patch Inclusion in Git**
Alright, the query I ran just came back empty. Hmm, that likely means the fix patch I'm looking for isn't baked into the main git tree yet. Totally expected. We're often working on the bleeding edge here, with syzkaller updates and recent patches pushing ahead of what's in `HEAD`. So, time to verify. Let's start by digging into that `HEAD` commit and confirm if the patch is present or not. That will dictate my next steps, and confirm our next steps.
|
| 734/2 |
2026/09/09 19:36 |
tool |
git-log |
0m
Error:
Args:
Results:
|
| 735/2 |
2026/09/09 19:36 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 30714
output: 28
thoughts: 18
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing Recent SG Driver Commits**
Okay, let's dive in. My immediate thought is to check out the recent commits specifically within the `drivers/scsi/sg.c` file. I need to get a handle on what's been happening in the SCSI Generic driver lately, probably because I'm looking at a specific issue, or maybe I'm preparing for some architecture changes. "sg.c" is a core component, so changes there are often indicative of significant shifts in how we interact with the SCSI layer. I'll need to use my preferred tooling - likely `git log` with some filtering to pinpoint the most relevant updates. I'm going to look for anything related to error handling, performance optimization, device compatibility, or any updates in the core ioctl's. My mental checklist includes things like verifying the impact of any changes on existing functionality and whether any new features or bugfixes have emerged. I'm going to need to think in terms of the bigger picture of the driver stack. And, I'm expecting to look at diffs. It'll be essential to ensure that any adjustments play nicely with the other parts of the driver and, of course, with the userland.
|
| 736/2 |
2026/09/09 19:37 |
tool |
git-log |
0m
Args: map[Count:5 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:1d3a742afeb7 scsi: sg: Report request-table problems when any status is set
7b03c93d2beb scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
50209dec14f8 scsi: sg: Remove deprecated sg-big-buff
d06a310b45e1 scsi: sg: Resolve soft lockup issue when opening /dev/sgX
3033c471aaf6 scsi: sg: Fix sysctl sg-big-buff register during sg_init()
]
|
| 737/2 |
2026/09/09 19:37 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 31184
output: 422
thoughts: 4735
Thoughts: **Analyzing the SG Driver Bug: A Deep Dive**
Okay, let's break this down. We have two commits to consider: 6460e75a104d and 10db10d144c02. The core of the issue seems to stem from how the `scatter_elem_sz` parameter is handled, particularly its interaction with the `sg_build_indirect` function. The first commit, 6460e75a104d, introduced the `scatter_elem_sz` module parameter, making it writable via sysfs. This is where the initial vulnerability is introduced, the ability to change the `scatter_elem_sz` module parameter at run time. This commit includes a check in the `init_sg` function and `sg_build_indirect` to ensure `scatter_elem_sz` isn't smaller than `PAGE_SIZE`. However, in this original commit, the code sets `scatter_elem_sz_prev` to `PAGE_SIZE` to cap `scatter_elem_sz`, and the vulnerable local variable `num` is immediately overwritten. So, the question remains: was this commit truly the source of the bug?
The crash report and its explanation are now crucial. The bug's trigger is writing "0" to `/sys/module/sg/parameters/scatter_elem_sz`. This sets the global `scatter_elem_sz` to 0. In `sg_build_indirect`, the local variable `num` is *initialized* to `scatter_elem_sz` (which is now 0). The `if` statement correctly detects `num < PAGE_SIZE`, updating `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`, but *crucially* forgets to update that local variable, `num`. Because `num` has now become a stale value, it is now used to calculate the order `order = get_order(num)`, which ultimately leads to an out-of-bounds shift.
Now, let's examine the second commit, 10db10d144c02, which seems to have "opened the door" for the bug to manifest. This commit introduced code that *directly* uses the local variable `num` outside of the check. It calls `order = get_order(num);`. This commit changed the way the indirect IO path was handled. It made assumptions about how the `scatter_elem_sz` was being updated. This commit, therefore, *assumed* that `num` was always sanitized by the `if` statement, but it was not. It didn't validate the `num` variable after the `if` statement.
So, 6460e75a104d created the *possibility* of the bug, by making `scatter_elem_sz` writable and using the old `num`. However, 10db10d144c02 actually introduced the faulty logic, by reusing the local variable `num`. FUJITA Tomonori could have used `scatter_elem_sz` directly, or the author of 10db10d144c02 should have updated `num` in the `if` block, or by validating `scatter_elem_sz` and not assuming `scatter_elem_sz` was always sanitized, which it was not. The fix patch now validates the range of acceptable module parameters directly when written to sysfs, so the issue cannot be triggered. Therefore, although 6460e75a104d introduced a vulnerability, 10db10d144c02 introduced the bug. The bug was introduced by reusing a local variable without updating it.
|
| 738/2 |
2026/09/09 19:37 |
tool |
codeexpert |
1m
Args: map[Question:In drivers/scsi/sg.c, a bug occurs when writing 0 to /sys/module/sg/parameters/scatter_elem_sz, leading to order = get_order(num) being called with num = 0 in sg_build_indirect(), causing order = 52 and shift-out-of-bounds at ret_sz = 1 << (PAGE_SHIFT + order).
Which commit introduced this bug?
Candidate 1: 6460e75a104d10458817d2f5b2fbff775bf0b43a ("[SCSI] sg: fixes for large page_size") which added scatter_elem_sz module parameter and the check:
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
where num was not updated to PAGE_SIZE (but at that time num was immediately overwritten inside the loop: num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz).
Candidate 2: 10db10d144c0248f285242f79daf6b9de6b00a62 ("sg: convert the indirect IO path to use the block layer") which introduced order = get_order(num); and ret_sz = 1 << (PAGE_SHIFT + order); reading the un-updated num.
Which of these two commits is the one that introduced the bug and should be credited in the Fixes tag?]
Results: map[Answer:Candidate 2: 10db10d144c0248f285242f79daf6b9de6b00a62 ("sg: convert the indirect IO path to use the block layer") is the commit that introduced the bug and should be credited in the Fixes tag.
In commit 6460e75a104d ("[SCSI] sg: fixes for large page_size"), although `num` was not updated to `PAGE_SIZE` when `num < PAGE_SIZE`, `num` was never read after that check; it was immediately overwritten inside the loop on each iteration:
`num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`
Because `scatter_elem_sz_prev` was correctly set to `PAGE_SIZE`, the code behaved correctly and no out-of-bounds shift or bug occurred.
It was commit 10db10d144c0 ("sg: convert the indirect IO path to use the block layer") that introduced the code reading `num` before the loop:
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
When `scatter_elem_sz` is set to 0, `num` remains 0 at this point, leading to `get_order(0)` returning 52 and the resulting shift-out-of-bounds. Therefore, the bug was introduced by commit 10db10d144c0248f285242f79daf6b9de6b00a62.]
|
| 739/3 |
2026/09/09 19:37 |
agent |
codeexpert |
1m
Model:
Results: map[Answer:Candidate 2: 10db10d144c0248f285242f79daf6b9de6b00a62 ("sg: convert the indirect IO path to use the block layer") is the commit that introduced the bug and should be credited in the Fixes tag.
In commit 6460e75a104d ("[SCSI] sg: fixes for large page_size"), although `num` was not updated to `PAGE_SIZE` when `num < PAGE_SIZE`, `num` was never read after that check; it was immediately overwritten inside the loop on each iteration:
`num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`
Because `scatter_elem_sz_prev` was correctly set to `PAGE_SIZE`, the code behaved correctly and no out-of-bounds shift or bug occurred.
It was commit 10db10d144c0 ("sg: convert the indirect IO path to use the block layer") that introduced the code reading `num` before the loop:
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
When `scatter_elem_sz` is set to 0, `num` remains 0 at this point, leading to `get_order(0)` returning 52 and the resulting shift-out-of-bounds. Therefore, the bug was introduced by commit 10db10d144c0248f285242f79daf6b9de6b00a62.]
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.
Research the question using targeted, efficient tool calls. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code. Keep your tool calls focused and limited to the
scope of the question. Do not explore tangential code paths or perform unbounded searches.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
4. Be concise and targeted. Answer the question as directly and concisely as possible
once you have located the relevant code or definitions. If a symbol or function cannot
be found after targeted searches, conclude with the best available information rather
than continuing repetitive searches.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
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: In drivers/scsi/sg.c, a bug occurs when writing 0 to /sys/module/sg/parameters/scatter_elem_sz, leading to order = get_order(num) being called with num = 0 in sg_build_indirect(), causing order = 52 and shift-out-of-bounds at ret_sz = 1 << (PAGE_SHIFT + order).
Which commit introduced this bug?
Candidate 1: 6460e75a104d10458817d2f5b2fbff775bf0b43a ("[SCSI] sg: fixes for large page_size") which added scatter_elem_sz module parameter and the check:
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
where num was not updated to PAGE_SIZE (but at that time num was immediately overwritten inside the loop: num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz).
Candidate 2: 10db10d144c0248f285242f79daf6b9de6b00a62 ("sg: convert the indirect IO path to use the block layer") which introduced order = get_order(num); and ret_sz = 1 << (PAGE_SHIFT + order); reading the un-updated num.
Which of these two commits is the one that introduced the bug and should be credited in the Fixes tag?
|
| 740/4 |
2026/09/09 19:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4450
output: 103
thoughts: 276
Thoughts: **Debugging a SCSI Driver Bug**
Okay, so I've got a problem. Someone's reported a nasty bug in `drivers/scsi/sg.c`, and it looks like it's triggered when a user writes 0 to `/sys/module/sg/parameters/scatter_elem_sz`. Apparently, this causes a cascade of errors within `sg_build_indirect()`, starting with a call to `get_order(num)` where `num` is 0. This results in `order` becoming 52, which then leads to a shift-out-of-bounds error when calculating `ret_sz = 1 << (PAGE_SHIFT + order)`. Classic.
Now, I need to figure out which commit introduced this gem. There are two likely candidates: `6460e75a104d10458817d2f5b2fbff775bf0b43a` ("[SCSI] sg: fixes for large page_size") and `10db10d144c0248f285242f79daf6b9de6b00a62` ("sg: convert the indirect IO path to use the block layer"). Both seem like they could have potentially tinkered with the relevant code.
Time to dive in. I'll fire up `git show` for each of these commits and carefully dissect `drivers/scsi/sg.c` to pinpoint the culprit. I need to understand the code changes in relation to how it handles the size of scatter/gather elements and see if the bug is apparent in one or both of these commits. Then, I can properly identify the "Fixes" tag for the bug report.
|
| 741/4 |
2026/09/09 19:37 |
tool |
git-show |
0m
Args: map[Commit:6460e75a104d10458817d2f5b2fbff775bf0b43a]
Results: map[Output:commit 6460e75a104d10458817d2f5b2fbff775bf0b43a
Author: Douglas Gilbert <dougg@torque.net>
Date: Wed Sep 20 18:20:49 2006 -0400
[SCSI] sg: fixes for large page_size
This sg driver patch addresses the problem with larger
page sizes reported by Brian King in this post:
http://marc.theaimsgroup.com/?l=linux-scsi&m=115867718623631&w=2
Some other related matters are also addressed. Some of these
prevent oopses when the SG_SCATTER_SZ or scatter_elem_sz are
set to inappropriate values.
The scatter_elem_sz has been tested up to 4 MB which should
make the largest data transfer with one SCSI command, 32 MB
less one block, achievable with a relatively small number
of elements in the scatter gather list.
ChangeLog:
- add scatter_elem_sz boot time parameter and sysfs module
parameter that is initialized to SG_SCATTER_SZ
- the driver will then adjust scatter_elem_sz to be the
max(given(scatter_elem_sz), PAGE_SIZE)
It will also round it up, if necessary, to be a power
of two
- clean up sg.h header, correct bad urls and some statements
that are no longer valid
- make the def_reserved_size sysfs module attribute writable
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Signed-off-by: James Bottomley <James.Bottomley@SteelEye.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 34f9343ed0af..3f8b93188567 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -60,7 +60,7 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
-static char *sg_version_date = "20060818";
+static char *sg_version_date = "20060920";
static int sg_proc_init(void);
static void sg_proc_cleanup(void);
@@ -94,6 +94,9 @@ int sg_big_buff = SG_DEF_RESERVED_SIZE;
static int def_reserved_size = -1; /* picks up init parameter */
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
+static int scatter_elem_sz = SG_SCATTER_SZ;
+static int scatter_elem_sz_prev = SG_SCATTER_SZ;
+
#define SG_SECTOR_SZ 512
#define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
@@ -1537,11 +1540,9 @@ sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
msleep(10); /* dirty detach so delay device destruction */
}
-/* Set 'perm' (4th argument) to 0 to disable module_param's definition
- * of sysfs parameters (which module_param doesn't yet support).
- * Sysfs parameters defined explicitly below.
- */
-module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
+module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
+module_param_named(def_reserved_size, def_reserved_size, int,
+ S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
MODULE_AUTHOR("Douglas Gilbert");
@@ -1550,6 +1551,8 @@ MODULE_LICENSE("GPL");
MODULE_VERSION(SG_VERSION_STR);
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
+MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
+ "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
@@ -1558,8 +1561,14 @@ init_sg(void)
{
int rc;
+ if (scatter_elem_sz < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = scatter_elem_sz;
+ }
if (def_reserved_size >= 0)
sg_big_buff = def_reserved_size;
+ else
+ def_reserved_size = sg_big_buff;
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1842,15 +1851,30 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
+ num = scatter_elem_sz;
+ if (unlikely(num != scatter_elem_sz_prev)) {
+ if (num < PAGE_SIZE) {
+ scatter_elem_sz = PAGE_SIZE;
+ scatter_elem_sz_prev = PAGE_SIZE;
+ } else
+ scatter_elem_sz_prev = num;
+ }
for (k = 0, sg = schp->buffer, rem_sz = blk_size;
(rem_sz > 0) && (k < mx_sc_elems);
++k, rem_sz -= ret_sz, ++sg) {
- num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
+ num = (rem_sz > scatter_elem_sz_prev) ?
+ scatter_elem_sz_prev : rem_sz;
p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
if (!p)
return -ENOMEM;
+ if (num == scatter_elem_sz_prev) {
+ if (unlikely(ret_sz > scatter_elem_sz_prev)) {
+ scatter_elem_sz = ret_sz;
+ scatter_elem_sz_prev = ret_sz;
+ }
+ }
sg->page = p;
sg->length = ret_sz;
@@ -2341,6 +2365,9 @@ sg_add_sfp(Sg_device * sdp, int dev)
}
write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
+ if (unlikely(sg_big_buff != def_reserved_size))
+ sg_big_buff = def_reserved_size;
+
sg_build_reserve(sfp, sg_big_buff);
SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen, sfp->reserve.k_use_sg));
@@ -2437,16 +2464,16 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* If retSzp==NULL want exact size or fail */
+/* The size fetched (value output via retSzp) set when non-NULL return */
static struct page *
sg_page_malloc(int rqSz, int lowDma, int *retSzp)
{
struct page *resp = NULL;
gfp_t page_mask;
int order, a_size;
- int resSz = rqSz;
+ int resSz;
- if (rqSz <= 0)
+ if ((rqSz <= 0) || (NULL == retSzp))
return resp;
if (lowDma)
@@ -2456,8 +2483,9 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
order++, a_size <<= 1) ;
+ resSz = a_size; /* rounded up if necessary */
resp = alloc_pages(page_mask, order);
- while ((!resp) && order && retSzp) {
+ while ((!resp) && order) {
--order;
a_size >>= 1; /* divide by 2, until PAGE_SIZE */
resp = alloc_pages(page_mask, order); /* try half */
@@ -2466,8 +2494,7 @@ sg_page_malloc(int rqSz, int lowDma, int *retSzp)
if (resp) {
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
memset(page_address(resp), 0, resSz);
- if (retSzp)
- *retSzp = resSz;
+ *retSzp = resSz;
}
return resp;
}
diff --git a/include/scsi/sg.h b/include/scsi/sg.h
index 0a487fe26d4f..519c49a0fc11 100644
--- a/include/scsi/sg.h
+++ b/include/scsi/sg.h
@@ -11,26 +11,10 @@
Original driver (sg.h):
* Copyright (C) 1992 Lawrence Foard
Version 2 and 3 extensions to driver:
-* Copyright (C) 1998 - 2003 Douglas Gilbert
-
- Version: 3.5.29 (20030529)
- This version is for 2.5 series kernels.
-
- Changes since 3.5.28 (20030308)
- - fix bug introduced in version 3.1.24 (last segment of sgat list)
- Changes since 3.5.27 (20020812)
- - remove procfs entries: hosts, host_hdr + host_strs (now in sysfs)
- - add sysfs sg driver params: def_reserved_size, allow_dio, version
- - new boot option: "sg_allow_dio" and module parameter: "allow_dio"
- - multiple internal changes due to scsi subsystem rework
- Changes since 3.5.26 (20020708)
- - re-add direct IO using Kai Makisara's work
- - re-tab to 8, start using C99-isms
- - simplify memory management
- Changes since 3.5.25 (20020504)
- - driverfs additions
- - copy_to/from_user() fixes [William Stinson]
- - disable kiobufs support
+* Copyright (C) 1998 - 2006 Douglas Gilbert
+
+ Version: 3.5.34 (20060920)
+ This version is for 2.6 series kernels.
For a full changelog see http://www.torque.net/sg
@@ -40,7 +24,7 @@ Map of SG verions to the Linux kernels in which they appear:
2.1.40 2.2.20
3.0.x optional version 3 sg driver for 2.2 series
3.1.17++ 2.4.0++
- 3.5.23++ 2.5.0++
+ 3.5.30++ 2.6.0++
Major new features in SG 3.x driver (cf SG 2.x drivers)
- SG_IO ioctl() combines function if write() and read()
@@ -51,14 +35,15 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
data into kernel buffers and then use the CPU to copy the data into the
user space (vice versa for writes). That is called "indirect" IO due to
the double handling of data. There are two methods offered to remove the
- redundant copy: 1) direct IO which uses the kernel kiobuf mechanism and
- 2) using the mmap() system call to map the reserve buffer (this driver has
- one reserve buffer per fd) into the user space. Both have their advantages.
+ redundant copy: 1) direct IO and 2) using the mmap() system call to map
+ the reserve buffer (this driver has one reserve buffer per fd) into the
+ user space. Both have their advantages.
In terms of absolute speed mmap() is faster. If speed is not a concern,
indirect IO should be fine. Read the documentation for more information.
- ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' may be
- needed. That pseudo file's content is defaulted to 0. **
+ ** N.B. To use direct IO 'echo 1 > /proc/scsi/sg/allow_dio' or
+ 'echo 1 > /sys/module/sg/parameters/allow_dio' is needed.
+ That attribute is 0 by default. **
Historical note: this SCSI pass-through driver has been known as "sg" for
a decade. In broader kernel discussions "sg" is used to refer to scatter
@@ -72,20 +57,17 @@ Major new features in SG 3.x driver (cf SG 2.x drivers)
http://www.torque.net/sg/p/sg_v3_ho.html
This is a rendering from DocBook source [change the extension to "sgml"
or "xml"]. There are renderings in "ps", "pdf", "rtf" and "txt" (soon).
+ The SG_IO ioctl is now found in other parts kernel (e.g. the block layer).
+ For more information see http://www.torque.net/sg/sg_io.html
The older, version 2 documents discuss the original sg interface in detail:
http://www.torque.net/sg/p/scsi-generic.txt
http://www.torque.net/sg/p/scsi-generic_long.txt
- A version of this document (potentially out of date) may also be found in
- the kernel source tree, probably at:
- Documentation/scsi/scsi-generic.txt .
+ Also available: <kernel_source>/Documentation/scsi/scsi-generic.txt
Utility and test programs are available at the sg web site. They are
- bundled as sg_utils (for the lk 2.2 series) and sg3_utils (for the
- lk 2.4 series).
-
- There is a HOWTO on the Linux SCSI subsystem in the lk 2.4 series at:
- http://www.linuxdoc.org/HOWTO/SCSI-2.4-HOWTO
+ packaged as sg3_utils (for the lk 2.4 and 2.6 series) and sg_utils
+ (for the lk 2.2 series).
*/
@@ -238,13 +220,12 @@ typedef struct sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
#define SG_GET_ACCESS_COUNT 0x2289
-#define SG_SCATTER_SZ (8 * 4096) /* PAGE_SIZE not available to user */
+#define SG_SCATTER_SZ (8 * 4096)
/* Largest size (in bytes) a single scatter-gather list element can have.
- The value must be a power of 2 and <= (PAGE_SIZE * 32) [131072 bytes on
- i386]. The minimum value is PAGE_SIZE. If scatter-gather not supported
- by adapter then this value is the largest data block that can be
- read/written by a single scsi command. The user can find the value of
- PAGE_SIZE by calling getpagesize() defined in unistd.h . */
+ The value used by the driver is 'max(SG_SCATTER_SZ, PAGE_SIZE)'.
+ This value should be a power of 2 (and may be rounded up internally).
+ If scatter-gather is not supported by adapter then this value is the
+ largest data block that can be read/written by a single scsi command. */
#define SG_DEFAULT_RETRIES 0
]
|
| 742/4 |
2026/09/09 19:37 |
tool |
git-show |
0m
Args: map[Commit:10db10d144c0248f285242f79daf6b9de6b00a62]
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 743/4 |
2026/09/09 19:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 19259
output: 26
thoughts: 1430
Thoughts: **Analyzing the sg_build_indirect Logic and Identifying the Root Cause of a Potential Shift-Out-of-Bounds Error**
Alright, let's break this down. I'm looking at a specific commit, 10db10d144c0248f285242f79daf6b9de6b00a62, and its impact on the `sg_build_indirect` function. My initial thought process is to trace the flow with a focus on how `scatter_elem_sz` is handled.
Before the commit, if `scatter_elem_sz` was, say, initialized to 0, things seemed...odd, but *mostly* fine. `num` would be assigned 0: `num = scatter_elem_sz;`. The subsequent check `if (num < PAGE_SIZE)` would trigger the assignment of `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. Crucially, `num` *remained* 0. However, the loop then immediately overrides `num` with `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`. This meant that `num` was then *effectively* the page size (or whatever remaining size). The crucial point here is that the initial assignment of `num = 0` was never *used* because it was immediately overwritten. It looked harmless from the perspective of integer overflow or allocation of zero-sized pages.
Now, I'm focusing on what Commit 10db10d144c0248f285242f79daf6b9de6b00a62 introduced. Fujita Tomonori added these lines:
```c
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
*Immediately* before the loop. This is the key.
Let me walk through the execution, if `scatter_elem_sz` is indeed zero. I set the parameter, `scatter_elem_sz = 0`. Then, within `sg_build_indirect()`, `num` becomes 0. The conditional `if (num < PAGE_SIZE)` triggers, setting both `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. *However*, `num` is still 0!
Then, the critical lines: `order = get_order(num);` This means `order = get_order(0);`. That's where I need to look closer. *Why* would `get_order(0)` return a value that, when used as an exponent in a left bit shift, leads to a shift-out-of-bounds error? That's what I am trying to figure out. The prompt says this returns 52, which seems incredibly suspicious and would lead to a HUGE value for `ret_sz`. I need to review the code. The problem is definitely here, in how `get_order()` handles an input of 0. I need to confirm if I am understanding this correct.
Essentially, I think the issue is the subtle, but crucial, introduction of an *unused* value of `num = 0` being passed to `get_order()`, which is now causing `ret_sz` to be calculated using a nonsensical order. This did not happen *before* the commit because, although `num` was set to zero initially, it was *immediately* overwritten inside the loop with a valid value. Now the code sets up this issue before any actual calculations are done in the loop.
|
| 744/4 |
2026/09/09 19:37 |
tool |
grepper |
0m
Error:
Args: map[Expression:define get_order PathPrefix:include/]
Results:
|
| 745/4 |
2026/09/09 19:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21530
output: 33
thoughts: 22
Thoughts: Here's my take on the thought process, as if it were my own:
**Investigating `get_order.h`**
Okay, time to dive into this. The `get_order` function… right, let's go straight to the source. I'm thinking, `include/asm-generic/getorder.h` should be the place to start. This is the generic assembly-level include, so it's a good bet for understanding how this is implemented across architectures, at least at a fundamental level. I'm expecting to see a macro definition, probably involving some bitwise operations. It's likely related to calculating page sizes or allocating memory with certain constraints, depending on the context. Let's see what they've done in that generic implementation and see how it relates to the current issue.
|
| 746/4 |
2026/09/09 19:37 |
tool |
grepper |
0m
Args: map[Expression:get_order PathPrefix:include/asm-generic/getorder.h]
Results: map[Output:include/asm-generic/getorder.h-10-/**
include/asm-generic/getorder.h:11: * get_order - Determine the allocation order of a memory size
include/asm-generic/getorder.h-12- * @size: The size for which to get the order
--
include/asm-generic/getorder.h-28- */
include/asm-generic/getorder.h:29:static __always_inline __attribute_const__ int get_order(unsigned long size)
include/asm-generic/getorder.h-30-{
]
|
| 747/4 |
2026/09/09 19:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21910
output: 37
thoughts: 16
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into the Kernel's Page Allocation Machinery**
Okay, time to get my hands dirty and delve into the low-level memory management of the kernel. Let's start by examining `include/asm-generic/getorder.h`. I'm specifically interested in understanding how the kernel translates a request for a certain number of pages into a power-of-two order for allocation. This header likely contains the core logic for that translation, which is crucial for efficient buddy system allocation. I'll be looking for any clever bit manipulation tricks or precomputed tables used to optimize this fundamental operation. I'll need to pay close attention to the definition of the `get_order()` macro, how it handles the nuances of different page sizes (if any), and any potential limitations or trade-offs in its design. This is where the rubber meets the road in terms of memory allocation performance, so understanding this macro's inner workings is paramount. Any architecture-specific optimizations (though this is the generic header, I'll be looking for the intention to provide architecture-specific versions) or edge-case handling will also be of interest.
|
| 748/4 |
2026/09/09 19:37 |
tool |
read-file |
0m
Args: map[File:include/asm-generic/getorder.h FirstLine:15 LineCount:40]
Results: map[Contents: 15: * is on a logarithmic scale, where:
16: *
17: * 0 -> 2^0 * PAGE_SIZE and below
18: * 1 -> 2^1 * PAGE_SIZE to 2^0 * PAGE_SIZE + 1
19: * 2 -> 2^2 * PAGE_SIZE to 2^1 * PAGE_SIZE + 1
20: * 3 -> 2^3 * PAGE_SIZE to 2^2 * PAGE_SIZE + 1
21: * 4 -> 2^4 * PAGE_SIZE to 2^3 * PAGE_SIZE + 1
22: * ...
23: *
24: * The order returned is used to find the smallest allocation granule required
25: * to hold an object of the specified size.
26: *
27: * The result is undefined if the size is 0.
28: */
29: static __always_inline __attribute_const__ int get_order(unsigned long size)
30: {
31: if (__builtin_constant_p(size)) {
32: if (!size)
33: return BITS_PER_LONG - PAGE_SHIFT;
34:
35: if (size < (1UL << PAGE_SHIFT))
36: return 0;
37:
38: return ilog2((size) - 1) - PAGE_SHIFT + 1;
39: }
40:
41: size--;
42: size >>= PAGE_SHIFT;
43: #if BITS_PER_LONG == 32
44: return fls(size);
45: #else
46: return fls64(size);
47: #endif
48: }
49:
50: #endif /* __ASSEMBLER__ */
51:
52: #endif /* __ASM_GENERIC_GETORDER_H */
]
|
| 749/4 |
2026/09/09 19:37 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 22766
output: 41
thoughts: 611
Thoughts: **Analyzing the `sg.c` Bug: A Deep Dive**
Okay, so I'm looking at this bug in `drivers/scsi/sg.c` that's triggered when you write 0 to `/sys/module/sg/parameters/scatter_elem_sz`. My initial thought process is: if `size` starts at 0 and then is decremented (`size--`), it becomes the maximum unsigned 64-bit value, which is `0xffffffffffffffffUL`. Then, right shift it by `PAGE_SHIFT` which is 12 (for 4K pages) gives `0x000fffffffffffff`.
The `fls64()` function then tells me there are 52 bits set, which is what `fls64` returns. Following that, a shift is being done, and it will be `1 << (12 + 52) = 1 << 64`. Now, here's where it gets interesting: that's a shift out of bounds! In C, this is undefined behavior (UB), because 1 is a signed 32-bit integer, and you are shifting it 64 bits.
Now, let's break down the core problem: setting `scatter_elem_sz` to 0. It leads to `order = get_order(num)` being called with `num = 0` in `sg_build_indirect()`, and this results in `order = 52`, and hence the shift-out-of-bounds issue when calculating `ret_sz = 1 << (PAGE_SHIFT + order)`.
We've got two candidate commits that might be the culprit:
* **Candidate 1:** `6460e75a104d10458817d2f5b2fbff775bf0b43a` ("[SCSI] sg: fixes for large page\_size"). This one introduced `scatter_elem_sz` and has a check that seems relevant:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The important bit here is that `num` wasn't immediately updated. However, the code *did* overwrite `num` immediately inside the loop: `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz`.
* **Candidate 2:** `10db10d144c0248f285242f79daf6b9de6b00a62` ("sg: convert the indirect IO path to use the block layer"). This commit introduced `order = get_order(num);` and `ret_sz = 1 << (PAGE_SHIFT + order);` – crucially, reading the *un-updated* `num`.
My gut tells me Candidate 2 is the more likely culprit because it directly introduces the problematic lines of code. The check in Candidate 1 might be a contributing factor, but Candidate 2 is the one that sets up the conditions for the UB.
Now, before I decide with complete certainty, I need to check for any upstream fixes or recent relevant commits, or any discussion on the mailing lists. I'm going to run `git log` on `drivers/scsi/sg.c` to see if there's been any activity around this area. I need to make sure I'm not missing something obvious.
|
| 750/4 |
2026/09/09 19:37 |
tool |
git-log |
0m
Args: map[CodeRegexp:scatter_elem_sz Count:10 PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 751/4 |
2026/09/09 19:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24308
output: 22
thoughts: 14
Thoughts: Here's my thought process, as if I were considering those search terms:
**Analyzing Codebase Search Strategy**
Okay, so I need to find something related to "scatter_elem_sz". That likely refers to element size in a scatter operation, probably in the context of some kind of memory management or data movement system. My first instinct, given the likely technical context, is to jump straight into the source control and search through commit messages. Those often contain crucial context around why specific changes were made, what problems they addressed, or how particular optimizations were implemented. Searching commit messages for that specific term, `scatter_elem_sz`, is a good initial targeted approach. That could quickly reveal relevant code modifications, discussions, and maybe even bug reports or design rationale that will give me clues about the current state of this, or how that relates to the overall system. If that yields results, I can dig deeper into the actual code changes associated with those commits.
|
| 752/4 |
2026/09/09 19:38 |
tool |
git-log |
0m
Args: map[MessageRegexps:[scatter_elem_sz]]
Results: map[Output:4d2de3a50ce1 [SCSI] fix BUG when sum(scatterlist) > bufflen
6460e75a104d [SCSI] sg: fixes for large page_size
]
|
| 753/4 |
2026/09/09 19:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24605
output: 37
thoughts: 26
Thoughts: Here's a summary of my thinking, expressed as first-person thoughts, assuming I'm an expert:
**Investigating sg_build_indirect in drivers/scsi/sg.c**
Okay, let's dive into the guts of `sg_build_indirect` within the `drivers/scsi/sg.c` module. I need to refresh my memory on the current implementation – any recent patches I need to consider? I'm thinking about its role in handling scatter-gather lists, particularly indirect lists. I want to understand how it's interacting with the hardware, the SCSI command structures, and memory management. Is it efficiently constructing these indirect lists, minimizing DMA overhead? What are the edge cases it's designed to handle? Are there any potential bottlenecks I should keep an eye out for, especially concerning potential performance issues with larger I/O requests? Specifically, I'm thinking about: the complexity of the list building, the handling of partial transfers, potential alignment issues, and interaction with the DMA engines. Ultimately, I need to understand its behaviour when I make large block I/O requests.
|
| 754/4 |
2026/09/09 19:38 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c Name:sg_build_indirect]
Results: map[SourceCode:1853: static int
1854: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1855: {
1856: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1857: int sg_tablesize = sfp->parentdp->sg_tablesize;
1858: int blk_size = buff_size, order;
1859: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1860:
1861: if (blk_size < 0)
1862: return -EFAULT;
1863: if (0 == blk_size)
1864: ++blk_size; /* don't know why */
1865: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1866: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1867: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1868: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1869: buff_size, blk_size));
1870:
1871: /* N.B. ret_sz carried into this block ... */
1872: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1873: if (mx_sc_elems < 0)
1874: return mx_sc_elems; /* most likely -ENOMEM */
1875:
1876: num = scatter_elem_sz;
1877: if (unlikely(num != scatter_elem_sz_prev)) {
1878: if (num < PAGE_SIZE) {
1879: scatter_elem_sz = PAGE_SIZE;
1880: scatter_elem_sz_prev = PAGE_SIZE;
1881: } else
1882: scatter_elem_sz_prev = num;
1883: }
1884:
1885: order = get_order(num);
1886: retry:
1887: ret_sz = 1 << (PAGE_SHIFT + order);
1888:
1889: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1890: k++, rem_sz -= ret_sz) {
1891:
1892: num = (rem_sz > scatter_elem_sz_prev) ?
1893: scatter_elem_sz_prev : rem_sz;
1894:
1895: schp->pages[k] = alloc_pages(gfp_mask, order);
1896: if (!schp->pages[k])
1897: goto out;
1898:
1899: if (num == scatter_elem_sz_prev) {
1900: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1901: scatter_elem_sz = ret_sz;
1902: scatter_elem_sz_prev = ret_sz;
1903: }
1904: }
1905:
1906: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1907: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1908: k, num, ret_sz));
1909: } /* end of for loop */
1910:
1911: schp->page_order = order;
1912: schp->k_use_sg = k;
1913: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1914: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1915: k, rem_sz));
1916:
1917: schp->bufflen = blk_size;
1918: if (rem_sz > 0) /* must have failed */
1919: return -ENOMEM;
1920: return 0;
1921: out:
1922: for (i = 0; i < k; i++)
1923: __free_pages(schp->pages[i], order);
1924:
1925: if (--order >= 0)
1926: goto retry;
1927:
1928: return -ENOMEM;
1929: }
SourceFile:drivers/scsi/sg.c]
|
| 755/4 |
2026/09/09 19:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 26240
output: 38
thoughts: 2051
Thoughts: **Bug Analysis: sg.c - scatter_elem_sz Parameter**
Okay, let's break this down. We're looking at a bug in `drivers/scsi/sg.c` triggered by setting `scatter_elem_sz` to 0. The goal is to identify the introducing commit for the `Fixes:` tag.
First, let's dissect the problem: setting `scatter_elem_sz` to 0 results in `order = get_order(num)` being called with `num = 0` in `sg_build_indirect()`. This leads to `order = 52` and a subsequent shift-out-of-bounds error when calculating `ret_sz = 1 << (PAGE_SHIFT + order)`. The question is, which commit introduced the vulnerable code?
Candidate 1, commit `6460e75a104d` ("\[SCSI] sg: fixes for large page_size"), introduces the `scatter_elem_sz` module parameter. I remember this one. We're interested in the code where `num` is assigned and potentially mishandled. My initial thought is it seems likely that it's here:
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
If we set `scatter_elem_sz` to zero, then `num` is zero. The `if` condition triggers, setting `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. Critically, *after* this conditional, `num` is *overwritten* in the loop: `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`. Because `scatter_elem_sz_prev` is `PAGE_SIZE`, `num` is immediately assigned to `PAGE_SIZE` (or `rem_sz` if that's smaller). Therefore, any previous value of `num` is effectively dead. Then, in the allocation, a value of `PAGE_SIZE` is used (since this is allocated with `a_size = PAGE_SIZE`). No out-of-bounds shift. The code is safe. I'm certain that the code in Candidate 1 does *not* introduce the bug.
Now, let's examine Candidate 2, commit `10db10d144c0` ("sg: convert the indirect IO path to use the block layer"). This one looks more promising. It introduces the line:
```c
order = get_order(num);
ret_sz = 1 << (PAGE_SHIFT + order);
```
Crucially, this commit *reads* the value of `num` *before* the loop. The assumption appears to be that the preceding code will update `num` if necessary, however, it's clear the check is based on `scatter_elem_sz` but then reuses `num` which is never updated in the case of a value less than `PAGE_SIZE`.
If `scatter_elem_sz` is 0, the code in Candidate 1 correctly adjusts `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, in Candidate 2, the `order = get_order(num)` line now reads the *unmodified* value of `num`, which is 0, *before* the assignment inside the loop. `get_order(0)` returns 52, leading directly to the out-of-bounds shift! This confirms that Candidate 2 *does* introduce the bug. I can visualize the control flow and value propagation and it looks good.
Therefore, Candidate 2 is the culprit. Based on established kernel development practice, a `git bisect` would pinpoint this commit as the first to exhibit the described bug and the documentation on contributing patches states that the `Fixes:` tag should point to the introducing commit.
So, the answer is commit `10db10d144c0` should be in the `Fixes:` tag. I'm confident in this analysis. I'm going to double-check `git log` or `git blame` around this code, but I believe the initial analysis is accurate.
|
| 756/4 |
2026/09/09 19:38 |
tool |
git-blame |
0m
Args: map[End:1890 File:drivers/scsi/sg.c Start:1875]
Results: map[Output:d6b10348f9397 1875)
6460e75a104d1 1876) num = scatter_elem_sz;
6460e75a104d1 1877) if (unlikely(num != scatter_elem_sz_prev)) {
6460e75a104d1 1878) if (num < PAGE_SIZE) {
6460e75a104d1 1879) scatter_elem_sz = PAGE_SIZE;
6460e75a104d1 1880) scatter_elem_sz_prev = PAGE_SIZE;
6460e75a104d1 1881) } else
6460e75a104d1 1882) scatter_elem_sz_prev = num;
6460e75a104d1 1883) }
10db10d144c02 1884)
10db10d144c02 1885) order = get_order(num);
10db10d144c02 1886) retry:
10db10d144c02 1887) ret_sz = 1 << (PAGE_SHIFT + order);
10db10d144c02 1888)
10db10d144c02 1889) for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
10db10d144c02 1890) k++, rem_sz -= ret_sz) {
]
|
| 757/4 |
2026/09/09 19:38 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 29809
output: 392
thoughts: 1055
Thoughts: **Analyzing the Bug in the Indirect IO Path**
Okay, let's break this down systematically. My initial thought is to trace the evolution of this code, focusing on how `num` is handled. It looks like lines 1884-1890 are critical, and they were first introduced by commit `10db10d144c02` ("sg: convert the indirect IO path to use the block layer"). Before that, in `6460e75a104d1`, lines 1876-1883 were added. However, at that point, `num` was only ever used *within* the loop, immediately overwritten by: `num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;` Crucially, the value of `num` after that initial conditional was *never* read or used before it was overwritten in the following line. Since `scatter_elem_sz_prev` was correctly set to `PAGE_SIZE`, the original code behaved as intended, always allocating pages that were a size of `PAGE_SIZE`.
Now, the problem lies with `10db10d144c0248f285242f79daf6b9de6b00a62`. This commit introduced lines that read `num` before the loop and were dependent on the value of `num` *before* it was updated. The issue becomes clear: the code now includes `order = get_order(num);` and `ret_sz = 1 << (PAGE_SHIFT + order);`, and it's reading `num` when it *hasn't* been validated or clamped. This is where the subtle error creeps in. Specifically, when `scatter_elem_sz` is less than `PAGE_SIZE`, `num` is *not* being updated correctly. The value of `num` remains as 0. This is fatal, as passing `0` to `get_order(num)` produces an invalid order (likely an extreme value like 52 on 64-bit systems with 4KB pages). This leads to `ret_sz = 1 << (PAGE_SHIFT + order)` performing an out-of-bounds bitshift (e.g., 1 << 64).
Therefore, I'm confident that the bug was introduced by `10db10d144c0248f285242f79daf6b9de6b00a62`. A git bisect would pinpoint this specific commit. This commit is the culprit and should be credited in the `Fixes:` tag for any subsequent patches.
|
| 758/4 |
2026/09/09 19:38 |
tool |
set-results |
0m
Args: map[Answer:Candidate 2: 10db10d144c0248f285242f79daf6b9de6b00a62 ("sg: convert the indirect IO path to use the block layer") is the commit that introduced the bug and should be credited in the Fixes tag.
In commit 6460e75a104d ("[SCSI] sg: fixes for large page_size"), although `num` was not updated to `PAGE_SIZE` when `num < PAGE_SIZE`, `num` was never read after that check; it was immediately overwritten inside the loop on each iteration:
`num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`
Because `scatter_elem_sz_prev` was correctly set to `PAGE_SIZE`, the code behaved correctly and no out-of-bounds shift or bug occurred.
It was commit 10db10d144c0 ("sg: convert the indirect IO path to use the block layer") that introduced the code reading `num` before the loop:
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
When `scatter_elem_sz` is set to 0, `num` remains 0 at this point, leading to `get_order(0)` returning 52 and the resulting shift-out-of-bounds. Therefore, the bug was introduced by commit 10db10d144c0248f285242f79daf6b9de6b00a62.]
Results: map[Answer:Candidate 2: 10db10d144c0248f285242f79daf6b9de6b00a62 ("sg: convert the indirect IO path to use the block layer") is the commit that introduced the bug and should be credited in the Fixes tag.
In commit 6460e75a104d ("[SCSI] sg: fixes for large page_size"), although `num` was not updated to `PAGE_SIZE` when `num < PAGE_SIZE`, `num` was never read after that check; it was immediately overwritten inside the loop on each iteration:
`num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz;`
Because `scatter_elem_sz_prev` was correctly set to `PAGE_SIZE`, the code behaved correctly and no out-of-bounds shift or bug occurred.
It was commit 10db10d144c0 ("sg: convert the indirect IO path to use the block layer") that introduced the code reading `num` before the loop:
order = get_order(num);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
When `scatter_elem_sz` is set to 0, `num` remains 0 at this point, leading to `get_order(0)` returning 52 and the resulting shift-out-of-bounds. Therefore, the bug was introduced by commit 10db10d144c0248f285242f79daf6b9de6b00a62.]
|
| 759/2 |
2026/09/09 19:38 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 37540
output: 51
thoughts: 325
Thoughts: **Analyzing the Root Cause**
Okay, let's break this down. My initial assessment points to a very specific issue stemming from how the variable `num` is handled across different commits. It seems clear to me now.
In commit 6460e75a104d10458817d2f5b2fbff775bf0b43a, `num` was utilized as a temporary storage variable, and then immediately reassigned within the loop. It wasn't involved in any size calculations or further use after its re-assignment from `rem_sz` and `scatter_elem_sz_prev`. There was no potential for issues because it was immediately overwritten. No calculations were performed based on that specific value.
However, in commit 10db10d144c0248f285242f79daf6b9de6b00a62, FUJITA Tomonori introduced a key change. This commit appears to reintroduce `num`, but this time it's used with `get_order(num)` and `ret_sz = 1 << (PAGE_SHIFT + order)`. My concern is that they are re-using the *stale* value of `num`, *without* updating it when `scatter_elem_sz < PAGE_SIZE`. This is where the issue likely originated. The `1 << (PAGE_SHIFT + order)` shift is the smoking gun, and directly triggers the undefined behavior. I need to confirm the hash and examine the diff again.
|
| 760/2 |
2026/09/09 19:38 |
tool |
git-show |
0m
Args: map[Commit:10db10d144c0248f285242f79daf6b9de6b00a62]
Results: map[Output:commit 10db10d144c0248f285242f79daf6b9de6b00a62
Author: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Date: Fri Aug 29 12:32:18 2008 +0200
sg: convert the indirect IO path to use the block layer
This patch converts the indirect IO path (including mmap IO and old
struct sg_header) to use the block layer functions (blk_get_request,
blk_execute_rq_nowait, blk_rq_map_user, etc) instead of
scsi_execute_async().
[Jens: fixed compile error with SCSI logging enabled]
Signed-off-by: FUJITA Tomonori <fujita.tomonori@lab.ntt.co.jp>
Signed-off-by: Douglas Gilbert <dougg@torque.net>
Cc: Mike Christie <michaelc@cs.wisc.edu>
Cc: James Bottomley <James.Bottomley@HansenPartnership.com>
Signed-off-by: Jens Axboe <jens.axboe@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index cb6de0752ee1..d6391666502c 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -47,7 +47,6 @@ static int sg_version_num = 30534; /* 2 digits for each component */
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
-#include <linux/scatterlist.h>
#include <linux/blktrace_api.h>
#include <linux/smp_lock.h>
@@ -119,7 +118,8 @@ typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
unsigned b_malloc_len; /* actual len malloc'ed in buffer */
- struct scatterlist *buffer;/* scatter list */
+ struct page **pages;
+ int page_order;
char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */
unsigned char cmd_opcode; /* first byte of command */
} Sg_scatter_hold;
@@ -190,8 +190,6 @@ static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
int read_only, Sg_request **o_srp);
static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking);
-static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up);
static int sg_write_xfer(Sg_request * srp);
static int sg_read_xfer(Sg_request * srp);
static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
@@ -199,8 +197,6 @@ static void sg_remove_scat(Sg_scatter_hold * schp);
static void sg_build_reserve(Sg_fd * sfp, int req_size);
static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
-static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
-static void sg_page_free(struct page *page, int size);
static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
@@ -771,26 +767,11 @@ sg_common_write(Sg_fd * sfp, Sg_request * srp,
break;
}
hp->duration = jiffies_to_msecs(jiffies);
-/* Now send everything of to mid-level. The next time we hear about this
- packet is when sg_cmd_done() is called (i.e. a callback). */
- if (srp->rq) {
- srp->rq->timeout = timeout;
- blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
- srp->rq, 1, sg_rq_end_io);
- return 0;
- }
- if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
- hp->dxfer_len, srp->data.k_use_sg, timeout,
- SG_DEFAULT_RETRIES, srp, sg_cmd_done,
- GFP_ATOMIC)) {
- SCSI_LOG_TIMEOUT(1, printk("sg_common_write: scsi_execute_async failed\n"));
- /*
- * most likely out of mem, but could also be a bad map
- */
- sg_finish_rem_req(srp);
- return -ENOMEM;
- } else
- return 0;
+
+ srp->rq->timeout = timeout;
+ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk,
+ srp->rq, 1, sg_rq_end_io);
+ return 0;
}
static int
@@ -1206,8 +1187,7 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
- struct scatterlist *sg;
- int k;
+ int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
@@ -1217,15 +1197,14 @@ sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
- sg = rsv_schp->buffer;
sa = vma->vm_start;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
if (offset < len) {
- struct page *page;
- page = virt_to_page(page_address(sg_page(sg)) + offset);
+ struct page *page = nth_page(rsv_schp->pages[k],
+ offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
@@ -1247,8 +1226,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
Sg_fd *sfp;
unsigned long req_sz, len, sa;
Sg_scatter_hold *rsv_schp;
- int k;
- struct scatterlist *sg;
+ int k, length;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
@@ -1262,11 +1240,10 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
return -ENOMEM; /* cannot map more than reserved buffer */
sa = vma->vm_start;
- sg = rsv_schp->buffer;
- for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
- ++k, sg = sg_next(sg)) {
+ length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
len = vma->vm_end - sa;
- len = (len < sg->length) ? len : sg->length;
+ len = (len < length) ? len : length;
sa += len;
}
@@ -1310,7 +1287,6 @@ sg_cmd_done(void *data, char *sense, int result, int resid)
if (0 != result) {
struct scsi_sense_hdr sshdr;
- memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
srp->header.status = 0xff & result;
srp->header.masked_status = status_byte(result);
srp->header.msg_status = msg_byte(result);
@@ -1685,34 +1661,51 @@ static int sg_start_req(Sg_request *srp, unsigned char *cmd)
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
unsigned long alignment = queue_dma_alignment(q) | q->dma_pad_mask;
+ struct rq_map_data map_data;
SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
+ res = __sg_start_req(srp, hp, cmd);
+ if (res)
+ return res;
+
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
- return __sg_start_req(srp, hp, cmd);
+ return 0;
#ifdef SG_ALLOW_DIO_CODE
if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
(dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
(!sfp->parentdp->device->host->unchecked_isa_dma) &&
- !(uaddr & alignment) && !(dxfer_len & alignment)) {
- res = __sg_start_req(srp, hp, cmd);
- if (!res)
- res = sg_build_direct(srp, sfp, dxfer_len);
-
- return res;
- }
+ !(uaddr & alignment) && !(dxfer_len & alignment))
+ return sg_build_direct(srp, sfp, dxfer_len);
#endif
if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
sg_link_reserve(sfp, srp, dxfer_len);
- else {
+ else
res = sg_build_indirect(req_schp, sfp, dxfer_len);
- if (res) {
- sg_remove_scat(req_schp);
- return res;
- }
+
+ if (!res) {
+ struct request *rq = srp->rq;
+ Sg_scatter_hold *schp = &srp->data;
+ int iovec_count = (int) hp->iovec_count;
+
+ map_data.pages = schp->pages;
+ map_data.page_order = schp->page_order;
+ map_data.nr_entries = schp->k_use_sg;
+
+ if (iovec_count)
+ res = blk_rq_map_user_iov(q, rq, &map_data, hp->dxferp,
+ iovec_count,
+ hp->dxfer_len, GFP_ATOMIC);
+ else
+ res = blk_rq_map_user(q, rq, &map_data, hp->dxferp,
+ hp->dxfer_len, GFP_ATOMIC);
+
+ if (!res)
+ srp->bio = rq->bio;
}
- return 0;
+
+ return res;
}
static void
@@ -1730,6 +1723,7 @@ sg_finish_rem_req(Sg_request * srp)
if (srp->rq) {
if (srp->bio)
blk_rq_unmap_user(srp->bio);
+
blk_put_request(srp->rq);
}
@@ -1739,21 +1733,12 @@ sg_finish_rem_req(Sg_request * srp)
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
- int sg_bufflen = tablesize * sizeof(struct scatterlist);
+ int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
- /*
- * TODO: test without low_dma, we should not need it since
- * the block layer will bounce the buffer for us
- *
- * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
- */
- if (sfp->low_dma)
- gfp_flags |= GFP_DMA;
- schp->buffer = kzalloc(sg_bufflen, gfp_flags);
- if (!schp->buffer)
+ schp->pages = kzalloc(sg_bufflen, gfp_flags);
+ if (!schp->pages)
return -ENOMEM;
- sg_init_table(schp->buffer, tablesize);
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
@@ -1780,11 +1765,10 @@ sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
static int
sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
{
- struct scatterlist *sg;
- int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
+ int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
int sg_tablesize = sfp->parentdp->sg_tablesize;
- int blk_size = buff_size;
- struct page *p = NULL;
+ int blk_size = buff_size, order;
+ gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
if (blk_size < 0)
return -EFAULT;
@@ -1808,15 +1792,26 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
} else
scatter_elem_sz_prev = num;
}
- for (k = 0, sg = schp->buffer, rem_sz = blk_size;
- (rem_sz > 0) && (k < mx_sc_elems);
- ++k, rem_sz -= ret_sz, sg = sg_next(sg)) {
-
+
+ if (sfp->low_dma)
+ gfp_mask |= GFP_DMA;
+
+ if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
+ gfp_mask |= __GFP_ZERO;
+
+ order = get_order(num);
+retry:
+ ret_sz = 1 << (PAGE_SHIFT + order);
+
+ for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
+ k++, rem_sz -= ret_sz) {
+
num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
- p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
- if (!p)
- return -ENOMEM;
+ scatter_elem_sz_prev : rem_sz;
+
+ schp->pages[k] = alloc_pages(gfp_mask, order);
+ if (!schp->pages[k])
+ goto out;
if (num == scatter_elem_sz_prev) {
if (unlikely(ret_sz > scatter_elem_sz_prev)) {
@@ -1824,12 +1819,12 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
scatter_elem_sz_prev = ret_sz;
}
}
- sg_set_page(sg, p, (ret_sz > num) ? num : ret_sz, 0);
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, "
"ret_sz=%d\n", k, num, ret_sz));
} /* end of for loop */
+ schp->page_order = order;
schp->k_use_sg = k;
SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, "
"rem_sz=%d\n", k, rem_sz));
@@ -1837,8 +1832,15 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
schp->bufflen = blk_size;
if (rem_sz > 0) /* must have failed */
return -ENOMEM;
-
return 0;
+out:
+ for (i = 0; i < k; i++)
+ __free_pages(schp->pages[k], order);
+
+ if (--order >= 0)
+ goto retry;
+
+ return -ENOMEM;
}
static int
@@ -1846,13 +1848,8 @@ sg_write_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
@@ -1866,83 +1863,9 @@ sg_write_xfer(Sg_request * srp)
&& ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
return 0;
- SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- ksglen = sg->length;
- p = page_address(sg_page(sg));
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_from_user(p, up, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_from_user(p, up, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
- return 0;
-}
+ SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, k_use_sg=%d\n",
+ num_xfer, schp->k_use_sg));
-static int
-sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
- int wr_xf, int *countp, unsigned char __user **up)
-{
- int num_xfer = (int) hp->dxfer_len;
- unsigned char __user *p = hp->dxferp;
- int count;
-
- if (0 == sg_num) {
- if (wr_xf && ('\0' == hp->interface_id))
- count = (int) hp->flags; /* holds "old" input_size */
- else
- count = num_xfer;
- } else {
- sg_iovec_t iovec;
- if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
- return -EFAULT;
- p = iovec.iov_base;
- count = (int) iovec.iov_len;
- }
- if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
- return -EFAULT;
- if (up)
- *up = p;
- if (countp)
- *countp = count;
return 0;
}
@@ -1950,21 +1873,18 @@ static void
sg_remove_scat(Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
- if (schp->buffer && (schp->sglist_len > 0)) {
- struct scatterlist *sg = schp->buffer;
-
+ if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg);
- ++k, sg = sg_next(sg)) {
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5, printk(
- "sg_remove_scat: k=%d, pg=0x%p, len=%d\n",
- k, sg_page(sg), sg->length));
- sg_page_free(sg_page(sg), sg->length);
+ "sg_remove_scat: k=%d, pg=0x%p\n",
+ k, schp->pages[k]));
+ __free_pages(schp->pages[k], schp->page_order);
}
- kfree(schp->buffer);
+ kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
@@ -1975,13 +1895,8 @@ sg_read_xfer(Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int num_xfer = 0;
- int j, k, onum, usglen, ksglen, res;
- int iovec_count = (int) hp->iovec_count;
int dxfer_dir = hp->dxfer_direction;
- unsigned char *p;
- unsigned char __user *up;
int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
@@ -1996,53 +1911,7 @@ sg_read_xfer(Sg_request * srp)
return 0;
SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
- num_xfer, iovec_count, schp->k_use_sg));
- if (iovec_count) {
- onum = iovec_count;
- if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
- return -EFAULT;
- } else
- onum = 1;
-
- p = page_address(sg_page(sg));
- ksglen = sg->length;
- for (j = 0, k = 0; j < onum; ++j) {
- res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
- if (res)
- return res;
-
- for (; p; sg = sg_next(sg), ksglen = sg->length,
- p = page_address(sg_page(sg))) {
- if (usglen <= 0)
- break;
- if (ksglen > usglen) {
- if (usglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, usglen))
- return -EFAULT;
- p += usglen;
- ksglen -= usglen;
- break;
- } else {
- if (ksglen >= num_xfer) {
- if (__copy_to_user(up, p, num_xfer))
- return -EFAULT;
- return 0;
- }
- if (__copy_to_user(up, p, ksglen))
- return -EFAULT;
- up += ksglen;
- usglen -= ksglen;
- }
- ++k;
- if (k >= schp->k_use_sg)
- return 0;
- }
- }
-
+ num_xfer, (int)hp->iovec_count, schp->k_use_sg));
return 0;
}
@@ -2050,7 +1919,6 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
- struct scatterlist *sg = schp->buffer;
int k, num;
SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
@@ -2058,15 +1926,18 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- for (k = 0; (k < schp->k_use_sg) && sg_page(sg); ++k, sg = sg_next(sg)) {
- num = sg->length;
+ blk_rq_unmap_user(srp->bio);
+ srp->bio = NULL;
+
+ num = 1 << (PAGE_SHIFT + schp->page_order);
+ for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
if (num > num_read_xfer) {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
- if (__copy_to_user(outp, page_address(sg_page(sg)),
+ if (__copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
@@ -2101,24 +1972,22 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
{
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
- struct scatterlist *sg = rsv_schp->buffer;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
rem = size;
- for (k = 0; k < rsv_schp->k_use_sg; ++k, sg = sg_next(sg)) {
- num = sg->length;
+ num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
- sfp->save_scat_len = num;
- sg->length = rem;
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
- req_schp->buffer = rsv_schp->buffer;
+ req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->b_malloc_len = rsv_schp->b_malloc_len;
+ req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
@@ -2132,22 +2001,13 @@ static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
- Sg_scatter_hold *rsv_schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
- if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
- struct scatterlist *sg = rsv_schp->buffer;
-
- if (sfp->save_scat_len > 0)
- (sg + (req_schp->k_use_sg - 1))->length =
- (unsigned) sfp->save_scat_len;
- else
- SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
- }
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
- req_schp->buffer = NULL;
+ req_schp->pages = NULL;
+ req_schp->page_order = 0;
req_schp->sglist_len = 0;
sfp->save_scat_len = 0;
srp->res_used = 0;
@@ -2405,53 +2265,6 @@ sg_res_in_use(Sg_fd * sfp)
return srp ? 1 : 0;
}
-/* The size fetched (value output via retSzp) set when non-NULL return */
-static struct page *
-sg_page_malloc(int rqSz, int lowDma, int *retSzp)
-{
- struct page *resp = NULL;
- gfp_t page_mask;
- int order, a_size;
- int resSz;
-
- if ((rqSz <= 0) || (NULL == retSzp))
- return resp;
-
- if (lowDma)
- page_mask = GFP_ATOMIC | GFP_DMA | __GFP_COMP | __GFP_NOWARN;
- else
- page_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN;
-
- for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
- order++, a_size <<= 1) ;
- resSz = a_size; /* rounded up if necessary */
- resp = alloc_pages(page_mask, order);
- while ((!resp) && order) {
- --order;
- a_size >>= 1; /* divide by 2, until PAGE_SIZE */
- resp = alloc_pages(page_mask, order); /* try half */
- resSz = a_size;
- }
- if (resp) {
- if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
- memset(page_address(resp), 0, resSz);
- *retSzp = resSz;
- }
- return resp;
-}
-
-static void
-sg_page_free(struct page *page, int size)
-{
- int order, a_size;
-
- if (!page)
- return;
- for (order = 0, a_size = PAGE_SIZE; a_size < size;
- order++, a_size <<= 1) ;
- __free_pages(page, order);
-}
-
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
]
|
| 761/2 |
2026/09/09 19:38 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 47901
output: 53
thoughts: 96
Thoughts: Okay, here's my interpretation of that.
**Pinpointing the Culprit**
Alright, based on what I'm seeing, `10db10d144c0248f285242f79daf6b9de6b00a62`... *that's* the commit that likely introduced the regression. Time to zero in on it. I'm going to call `set-results` with that specific commit hash. That will allow me to narrow down the scope of the problem.
|
| 762/2 |
2026/09/09 19:38 |
tool |
set-results |
0m
Args: map[FixesHash:10db10d144c0248f285242f79daf6b9de6b00a62]
Results: map[FixesHash:10db10d144c0248f285242f79daf6b9de6b00a62]
|
| 763/1 |
2026/09/09 19:39 |
action |
format-fixes |
0m
Results: map[Fixes:map[AuthorEmail:fujita.tomonori@lab.ntt.co.jp AuthorName:FUJITA Tomonori Hash:10db10d144c0248f285242f79daf6b9de6b00a62 Title:sg: convert the indirect IO path to use the block layer]]
|
| 764/1 |
2026/09/09 19:39 |
action |
get-maintainers |
0m
Results: map[Recipients:[map[Email:James.Bottomley@HansenPartnership.com Name:James E.J. Bottomley To:true] map[Email:dgilbert@interlog.com Name:Doug Gilbert To:true] map[Email:linux-kernel@vger.kernel.org Name: To:false] map[Email:linux-scsi@vger.kernel.org Name: To:true] map[Email:mkp@kernel.org Name:Martin K. Petersen To:true] map[Email:fujita.tomonori@lab.ntt.co.jp Name:FUJITA Tomonori To:true]]]
|
| 765/1 |
2026/09/09 19:39 |
action |
get-recent-commits |
0m
Results: map[RecentCommits:scsi: sg: Report request-table problems when any status is set
scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
scsi: sg: Remove deprecated sg-big-buff
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
scsi: sg: Fix sysctl sg-big-buff register during sg_init()
Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
treewide: Replace kmalloc with kmalloc_obj for non-scalar types
block: pass io_comp_batch to rq_end_io_fn callback
scsi: sg: Fix occasional bogus elapsed time that exceeds timeout
scsi: sg: Do not sleep in atomic context
scsi: sg: drop nth_page() usage within SG entry
scsi: sg: Remove unnecessary NULL check before unregister_sysctl_table()
treewide: const qualify ctl_tables where applicable
scsi: sg: Fix slab-use-after-free read in sg_release()
scsi: sg: Enable runtime power management
[tree-wide] finally take no_llseek out
scsi: sg: Avoid race in error handling & drop bogus warn
scsi: sg: Avoid sg device teardown race
scsi: sg: Make sg_sysfs_class constant
scsi: Remove now superfluous sentinel element from ctl_table array
]
|
| 766/1 |
2026/09/09 19:39 |
agent |
description-generator |
0m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with writing a commit description for
a kernel bug fixing commit. The description should start with a one-line summary,
and then include description of the bug being fixed, and how it's fixed by the provided patch.
The one-line summary should describe the change being made, rather than mention the tool that
detected the bug.
The description must not contain lines starting with '#' because they will dropped by git as comments.
The description must not contain lines starting with '--' or '---' (including inline code diffs)
because they may confuse git/patch utilities.
Your final reply should contain only the text of the commit description.
The one-line summary must be not longer than 72 characters.
IMPORTANT: Do not wrap lines manually (e.g., at 80 characters); we will reformat the text
automatically, so keep paragraphs as single lines without newlines.
Generally try to phrase the description without mentioning syzkaller
(avoid phrases like "the bug was triggered by syzkaller" or "the bug was triggered by fuzzer", etc).
How the bug was triggered is generally an irrelevant detail.
Any bug triggered by a fuzzer can also be triggered by a malicious user, or a buggy program.
If the crash is reported by a sanitizer (e.g., KASAN, KMSAN, lockdep), include the relevant
parts of the sanitizer output to illustrate the problem. Exclude less relevant sections,
as the stack trace can be very long. Describe the execution path that leads to the manifestation
of the kernel bug.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/9d22f3af01dc24fa8887cb4af37a784370af643b/drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 1 UID: 0 PID: 6145 Comm: syz.0.17 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
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
do_open fs/namei.c:4837 [inline]
path_openat+0x1443/0x1d60 fs/namei.c:5000
do_file_open+0x23e/0x4a0 fs/namei.c:5029
do_sys_openat2+0x115/0x200 fs/open.c:1417
do_sys_open fs/open.c:1423 [inline]
__do_sys_openat fs/open.c:1439 [inline]
__se_sys_openat fs/open.c:1434 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1434
do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
do_syscall_64+0x155/0x510 arch/x86/entry/syscall_64.c:84
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7feb90d9e159
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:00007feb91d05028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007feb91025fa0 RCX: 00007feb90d9e159
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007feb90e3503b R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007feb91026038 R14: 00007feb91025fa0 R15: 00007ffcfd347918
</TASK>
---[ end trace ]---
The explanation of the root cause of the bug is:
An analysis of the crash reveals that the issue is caused by a missing update to a local variable after validating a module parameter, combined with an unbounded shift operation.
### Root Cause
1. **Triggering the Bug:**
The reproducer writes the string `"0"` to `/sys/module/sg/parameters/scatter_elem_sz`. Since `scatter_elem_sz` is a writable module parameter (with permissions `S_IRUGO | S_IWUSR`), this sets its value to `0`.
2. **Missing Local Variable Update:**
When the reproducer subsequently opens `/dev/sg0`, the driver eventually calls `sg_build_indirect()`. In this function, the local variable `num` is initialized to the current value of `scatter_elem_sz` (which is `0`):
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
```
The code correctly detects that `num < PAGE_SIZE` (since `0 < 4096`) and updates the global variables `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. However, **it forgets to update the local variable `num`**. Consequently, `num` remains `0`.
3. **Undefined Behavior in `get_order()`:**
The code then calls `order = get_order(num);` with `num = 0`. According to the documentation in `include/asm-generic/getorder.h`, the result of `get_order(0)` is undefined. In practice, the macro executes:
```c
size--;
size >>= PAGE_SHIFT;
return fls64(size);
```
For `size = 0`, `size--` underflows to `0xffffffffffffffff`. Shifting right by `PAGE_SHIFT` (12) yields `0x000fffffffffffff`. `fls64()` then returns the 1-based index of the highest set bit, which is `52`. Thus, `order` becomes `52`.
4. **Shift-Out-Of-Bounds:**
The code then attempts to calculate the allocation size:
```c
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT = 12` and `order = 52`, the shift exponent evaluates to `64`. Shifting a 32-bit signed integer (the literal `1`) by 64 bits is undefined behavior, which triggers the exact UBSAN panic seen in the crash report: `shift exponent 64 is too large for 32-bit type 'int'`.
5. **Secondary Bug (Large Values):**
Even if `num` is a large positive value (e.g., `INT_MAX`), `get_order(INT_MAX)` evaluates to `19`. The shift exponent becomes `12 + 19 = 31`. `1 << 31` overflows a signed 32-bit `int` into the sign bit, which is also undefined behavior. Furthermore, passing `order = 19` to `alloc_pages()` will trigger a `WARN_ON_ONCE` in the page allocator because it exceeds `MAX_PAGE_ORDER`.
### Proposed Fix
To fix this, two changes are required in `sg_build_indirect()`:
1. Update the local variable `num` to `PAGE_SIZE` when `num < PAGE_SIZE`.
2. Bound the `order` to `MAX_PAGE_ORDER` (defined in `<linux/mmzone.h>`) to prevent undefined behavior and avoid calling `alloc_pages()` with an invalid order. The code already has a fallback loop that decrements `order` and retries if allocation fails, so bounding it initially is perfectly safe and more efficient.
```c
num = scatter_elem_sz;
if (unlikely(num != scatter_elem_sz_prev)) {
if (num < PAGE_SIZE) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
scatter_elem_sz_prev = num;
}
order = get_order(num);
+ order = min_t(int, order, MAX_PAGE_ORDER);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
```
The diff of the bug fix is:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 5408f002e..4c82fc00d 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -92,7 +92,6 @@ static int def_reserved_size = SG_DEF_RESERVED_SIZE;
static int sg_allow_dio = SG_ALLOW_DIO_DEF;
static int scatter_elem_sz = SG_SCATTER_SZ;
-static int scatter_elem_sz_prev = SG_SCATTER_SZ;
#define SG_SECTOR_SZ 512
@@ -1621,9 +1620,33 @@ sg_remove_device(struct device *cl_dev)
kref_put(&sdp->d_ref, sg_device_destroy);
}
-module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int scatter_elem_sz_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ if (size < PAGE_SIZE || size > (PAGE_SIZE << MAX_PAGE_ORDER))
+ return -ERANGE;
+
+ scatter_elem_sz = size;
+ return 0;
+}
+
+static const struct kernel_param_ops scatter_elem_sz_ops = {
+ .set = scatter_elem_sz_set,
+ .get = param_get_int,
+};
+
+module_param_cb(scatter_elem_sz, &scatter_elem_sz_ops, &scatter_elem_sz, 0644);
+
static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
{
int size, ret;
@@ -1667,10 +1690,8 @@ init_sg(void)
{
int rc;
- if (scatter_elem_sz < PAGE_SIZE) {
+ if (scatter_elem_sz < PAGE_SIZE)
scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = scatter_elem_sz;
- }
rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS, "sg");
@@ -1873,36 +1894,19 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
if (mx_sc_elems < 0)
return mx_sc_elems; /* most likely -ENOMEM */
- num = scatter_elem_sz;
- if (unlikely(num != scatter_elem_sz_prev)) {
- if (num < PAGE_SIZE) {
- scatter_elem_sz = PAGE_SIZE;
- scatter_elem_sz_prev = PAGE_SIZE;
- } else
- scatter_elem_sz_prev = num;
- }
-
- order = get_order(num);
+ order = get_order(scatter_elem_sz);
retry:
ret_sz = 1 << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
- num = (rem_sz > scatter_elem_sz_prev) ?
- scatter_elem_sz_prev : rem_sz;
+ num = min(rem_sz, ret_sz);
schp->pages[k] = alloc_pages(gfp_mask, order);
if (!schp->pages[k])
goto out;
- if (num == scatter_elem_sz_prev) {
- if (unlikely(ret_sz > scatter_elem_sz_prev)) {
- scatter_elem_sz = ret_sz;
- scatter_elem_sz_prev = ret_sz;
- }
- }
-
SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
k, num, ret_sz));
Additional description of the patch:
An architectural revision has been applied to address the root cause and the senior maintainer's feedback:
### Root Cause & Deficiencies of Previous Approaches
1. **Root Cause**:
Writing `"0"` to `/sys/module/sg/parameters/scatter_elem_sz` set `scatter_elem_sz = 0`. During `sg_build_indirect()`, the driver detected that `num < PAGE_SIZE` and updated global variables, but failed to update local variable `num`. `get_order(0)` underflowed into calculating `order = 52`, which subsequently resulted in `1 << (12 + 52)` (shifting 1 by 64 bits), triggering the UBSAN `shift-out-of-bounds` panic.
2. **Architectural Deficiencies in Previous Attempts**:
- **Data-path sanitization**: Patching `sg_build_indirect()` to sanitize out-of-range module parameter values inside the I/O fast path violates invariant hygiene and caller/callee boundaries.
- **Data races and global mutation**: Mutating `scatter_elem_sz` and `scatter_elem_sz_prev` inside `sg_build_indirect()` without synchronization introduces data races between concurrent opens and requests.
- **Parameter divergence**: Clamping `order` inside `sg_build_indirect()` leaves the sysfs parameter at an invalid value while driver allocations diverge silently.
- **Anti-patterns**: Casting `(int)PAGE_SIZE` to work around signed/unsigned comparison.
### Fix Details
Following the subsystem precedent in `drivers/scsi/sg.c` (commit `d06a310b45e1` for `def_reserved_size`):
1. **Module Parameter Boundary Validation**:
- Replaced `module_param_named(scatter_elem_sz, ...)` with `module_param_cb()` using a custom `.set` callback `scatter_elem_sz_set()`.
- Validates that user input is within `[PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER]`, rejecting invalid or out-of-range inputs with `-ERANGE` (or `-EINVAL` on malformed input) at the sysfs boundary.
2. **Eliminated Unsynchronized Global State**:
- Removed `scatter_elem_sz_prev` completely from the driver.
- In `init_sg()`, ensured `scatter_elem_sz` is clamped to `PAGE_SIZE` if `PAGE_SIZE > SG_SCATTER_SZ` without referencing `scatter_elem_sz_prev`.
3. **Simplified `sg_build_indirect()`**:
- Removed the runtime mutation and tracking block from `sg_build_indirect()`.
- Initialized allocation order directly via `order = get_order(scatter_elem_sz)`.
- Simplified the per-element size logging to use `num = min(rem_sz, ret_sz)`.
Here are summaries of recent commits that touched the same files.
Format the summary line consistently with these, look how prefixes
are specified, letter capitalization, style, etc.
scsi: sg: Report request-table problems when any status is set
scsi: sg: Don't use GFP_ATOMIC in sg_start_req()
scsi: sg: Remove deprecated sg-big-buff
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
scsi: sg: Fix sysctl sg-big-buff register during sg_init()
Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
treewide: Replace kmalloc with kmalloc_obj for non-scalar types
block: pass io_comp_batch to rq_end_io_fn callback
scsi: sg: Fix occasional bogus elapsed time that exceeds timeout
scsi: sg: Do not sleep in atomic context
scsi: sg: drop nth_page() usage within SG entry
scsi: sg: Remove unnecessary NULL check before unregister_sysctl_table()
treewide: const qualify ctl_tables where applicable
scsi: sg: Fix slab-use-after-free read in sg_release()
scsi: sg: Enable runtime power management
[tree-wide] finally take no_llseek out
scsi: sg: Avoid race in error handling & drop bogus warn
scsi: sg: Avoid sg device teardown race
scsi: sg: Make sg_sysfs_class constant
scsi: Remove now superfluous sentinel element from ctl_table array
Reply: scsi: sg: Validate scatter_elem_sz module parameter
Writing an invalid value such as 0 to
/sys/module/sg/parameters/scatter_elem_sz causes a shift-out-of-bounds bug
during subsequent device operations. When opening a device via sg_open(),
the driver calls sg_build_indirect() to allocate scatter-gather buffers. In
sg_build_indirect(), the code checks if the local variable num is less than
PAGE_SIZE and updates the global scatter_elem_sz and scatter_elem_sz_prev
variables, but fails to update num. As a result, num remains 0 and is
passed to order = get_order(num). Calling get_order(0) is undefined and
underflows to 52 on 64-bit systems, causing ret_sz = 1 << (PAGE_SHIFT +
order) to compute 1 << 64. Shifting a 32-bit int by 64 bits triggers a
UBSAN shift-out-of-bounds warning:
UBSAN: shift-out-of-bounds in drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
</TASK>
Additionally, excessively large values written to scatter_elem_sz can cause
order to exceed MAX_PAGE_ORDER, which can overflow signed 32-bit arithmetic
and trigger warnings in the page allocator. Mutating global variables
scatter_elem_sz and scatter_elem_sz_prev inside the I/O path without
locking also introduces data races between concurrent device accesses.
Fix this by replacing module_param_named() with module_param_cb() for
scatter_elem_sz, similar to def_reserved_size. The setter callback
scatter_elem_sz_set() validates that the input value is within [PAGE_SIZE,
PAGE_SIZE << MAX_PAGE_ORDER], rejecting invalid values with -ERANGE or
-EINVAL at the sysfs boundary. Remove scatter_elem_sz_prev and the runtime
parameter modification from sg_build_indirect(), compute the allocation
order directly from scatter_elem_sz, and simplify the per-element size
calculation using min(rem_sz, ret_sz).
|
| 767/2 |
2026/09/09 19:39 |
llm |
description-generator |
0m
Model:
Tokens:
input: 8660
output: 27
thoughts: 1172
Thoughts: **scsi: sg: Validate scatter_elem_sz and synchronize access**
Okay, here's what I've got. I need to craft a kernel commit description for this `drivers/scsi/sg.c` bug fix. First, the one-liner: it needs to describe the *change*, not the tool that found the bug, and it can't be longer than 72 characters. The title is done.
The bug is a UBSAN shift-out-of-bounds error. It happens in `sg_build_indirect()` when `scatter_elem_sz` is set to an invalid value, particularly zero or a value less than `PAGE_SIZE`, via `/sys/module/sg/parameters/scatter_elem_sz`. This happens if `scatter_elem_sz` and `scatter_elem_sz_prev` were updated but `num` was not updated and remained zero. When `get_order(0)` is called, it underflows and leads to `1 << 64` which causes the UBSAN error. Also, an excessively large value can cause `order` to exceed `MAX_PAGE_ORDER`. There's also a race condition here with the unsynchronized access to `scatter_elem_sz`.
The fix: I'm going to use `module_param_cb` for `scatter_elem_sz`, along with a setter callback `scatter_elem_sz_set()`. This callback will validate the input, ensuring it's between `PAGE_SIZE` and `PAGE_SIZE << MAX_PAGE_ORDER`, and reject invalid values with `-ERANGE` or `-EINVAL`. I'll remove `scatter_elem_sz_prev` and get rid of the unsynchronized validation and mutation in `sg_build_indirect()`. Instead, I'll calculate `order = get_order(scatter_elem_sz)` directly and use `min(rem_sz, ret_sz)` for per-element size accounting. That should take care of this.
|
| 768/2 |
2026/09/09 19:39 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d06a310b45e153872033dd0cf19d5a2279121099
Author: Yang Erkun <yangerkun@huawei.com>
Date: Tue Jan 27 14:20:43 2026 +0800
scsi: sg: Resolve soft lockup issue when opening /dev/sgX
The parameter def_reserved_size defines the default buffer size reserved
for each Sg_fd and should be restricted to a range between 0 and 1,048,576
(see https://tldp.org/HOWTO/SCSI-Generic-HOWTO/proc.html). Although the
function sg_proc_write_dressz enforces this limit, it is possible to bypass
it by directly modifying the module parameter as shown below, which then
causes a soft lockup:
echo -1 > /sys/module/sg/parameters/def_reserved_size
exec 4<> /dev/sg0
watchdog: BUG: soft lockup - CPU#5 stuck for 26 seconds! [bash:537]
Modules loaded:
CPU: 5 UID: 0 PID: 537 Command: bash, kernel version 6.19.0-rc3+ #134,
PREEMPT disabled
Hardware: QEMU Standard PC (i440FX + PIIX, 1996), BIOS version
1.16.1-2.fc37 dated 04/01/2014
...
Call Trace:
sg_build_reserve+0x5c/0xa0
sg_add_sfp+0x168/0x270
sg_open+0x16e/0x340
chrdev_open+0xbe/0x230
do_dentry_open+0x175/0x480
vfs_open+0x34/0xf0
do_open+0x265/0x3d0
path_openat+0x110/0x290
do_filp_open+0xc3/0x170
do_sys_openat2+0x71/0xe0
__x64_sys_openat+0x6d/0xa0
do_syscall_64+0x62/0x310
entry_SYSCALL_64_after_hwframe+0x76/0x7e
The fix is to use module_param_cb to validate and reject invalid values
assigned to def_reserved_size.
Fixes: 6460e75a104d ("[SCSI] sg: fixes for large page_size")
Signed-off-by: Yang Erkun <yangerkun@huawei.com>
Reviewed-by: Bart Van Assche <bvanassche@acm.org>
Link: https://patch.msgid.link/20260127062044.3034148-3-yangerkun@huawei.com
Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 71d34186dec9..f38d36fbeef3 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1623,10 +1623,35 @@ sg_remove_device(struct device *cl_dev)
}
module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
-module_param_named(def_reserved_size, def_reserved_size, int,
- S_IRUGO | S_IWUSR);
module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
+static int def_reserved_size_set(const char *val, const struct kernel_param *kp)
+{
+ int size, ret;
+
+ if (!val)
+ return -EINVAL;
+
+ ret = kstrtoint(val, 0, &size);
+ if (ret)
+ return ret;
+
+ /* limit to 1 MB */
+ if (size < 0 || size > 1048576)
+ return -ERANGE;
+
+ def_reserved_size = size;
+ return 0;
+}
+
+static const struct kernel_param_ops def_reserved_size_ops = {
+ .set = def_reserved_size_set,
+ .get = param_get_int,
+};
+
+module_param_cb(def_reserved_size, &def_reserved_size_ops, &def_reserved_size,
+ S_IRUGO | S_IWUSR);
+
MODULE_AUTHOR("Douglas Gilbert");
MODULE_DESCRIPTION("SCSI generic (sg) driver");
MODULE_LICENSE("GPL");
]
|
| 769/2 |
2026/09/09 19:39 |
llm |
description-generator |
0m
Model:
Tokens:
input: 11608
output: 764
thoughts: 5791
Thoughts: **scsi: sg: Validate scatter_elem_sz module parameter**
Writing an invalid value such as 0 to /sys/module/sg/parameters/scatter_elem_sz causes a shift-out-of-bounds bug during subsequent device operations. When opening a device via sg_open(), the driver calls sg_build_indirect() to allocate scatter-gather buffers. In sg_build_indirect(), the code checks if the local variable num is less than PAGE_SIZE and updates the global scatter_elem_sz and scatter_elem_sz_prev variables, but fails to update num. As a result, num remains 0 and is passed to order = get_order(num). Calling get_order(0) is undefined and underflows to 52 on 64-bit systems, causing ret_sz = 1 << (PAGE_SHIFT + order) to compute 1 << 64. Shifting a 32-bit int by 64 bits triggers a UBSAN shift-out-of-bounds warning:
UBSAN: shift-out-of-bounds in drivers/scsi/sg.c:1887:13
shift exponent 64 is too large for 32-bit type 'int'
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
ubsan_epilogue+0xa/0x30 lib/ubsan.c:233
__ubsan_handle_shift_out_of_bounds+0x36d/0x400 lib/ubsan.c:494
sg_build_indirect+0x559/0x870 drivers/scsi/sg.c:1887
sg_build_reserve drivers/scsi/sg.c:1997 [inline]
sg_add_sfp drivers/scsi/sg.c:2177 [inline]
sg_open+0x1128/0x18a0 drivers/scsi/sg.c:349
chrdev_open+0x4d9/0x600 fs/char_dev.c:411
do_dentry_open+0x816/0x1380 fs/open.c:996
vfs_open+0x3b/0x340 fs/open.c:1101
</TASK>
Additionally, excessively large values written to scatter_elem_sz can cause order to exceed MAX_PAGE_ORDER, which can overflow signed 32-bit arithmetic and trigger warnings in the page allocator. Mutating global variables scatter_elem_sz and scatter_elem_sz_prev inside the I/O path without locking also introduces data races between concurrent device accesses.
Fix this by replacing module_param_named() with module_param_cb() for scatter_elem_sz, similar to def_reserved_size. The setter callback scatter_elem_sz_set() validates that the input value is within [PAGE_SIZE, PAGE_SIZE << MAX_PAGE_ORDER], rejecting invalid values with -ERANGE or -EINVAL at the sysfs boundary. Remove scatter_elem_sz_prev and the runtime parameter modification from sg_build_indirect(), compute the allocation order directly from scatter_elem_sz, and simplify the per-element size calculation using min(rem_sz, ret_sz).
|