| 0/0 |
2026/05/20 21:47 |
flow |
patching |
1h53m
Results: map[AckedBy:<nil> Fixes:map[Hash:10db10d144c0248f285242f79daf6b9de6b00a62 Title:sg: convert the indirect IO path to use the block layer] KernelBranch:master KernelCommit:5200f5f493f79f14bbdc349e402a40dfb32f23c8 KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git PatchDescription:scsi: sg: Fix shift-out-of-bounds in sg_build_indirect()
When the scatter_elem_sz module parameter is set to 0 (or a negative
value), sg_build_indirect() attempts to clamp it to PAGE_SIZE. However,
while the global variables are updated, the local variable num is not.
This results in num remaining 0. Calling get_order(0) underflows and
returns a very large order (e.g., 52). Subsequently, the expression 1 <<
(PAGE_SHIFT + order) evaluates to 1 << 64, which triggers a
shift-out-of-bounds undefined behavior.
Fix this by updating the local variable num to PAGE_SIZE during the
clamping process to ensure it is never 0 or negative when passed to
get_order(). Additionally, replace the unsafe 1 << (PAGE_SHIFT + order)
pattern with the safer and more idiomatic PAGE_SIZE << order throughout
the file. This prevents any potential undefined behavior if PAGE_SHIFT +
order equals or exceeds 31 (or 64 for 1UL), and ensures consistency
across sg_build_indirect(), sg_vma_fault(), sg_mmap(), sg_read_oxfer(),
and sg_link_reserve(). PatchDiff:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 74cd4e8a6..cb4450a89 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1232,7 +1232,7 @@ sg_vma_fault(struct vm_fault *vmf)
"sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1278,7 +1278,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
}
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1877,6 +1877,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1885,7 +1886,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = PAGE_SIZE << order;
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
@@ -1964,7 +1965,7 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- num = 1 << (PAGE_SHIFT + schp->page_order);
+ num = PAGE_SIZE << 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(schp->pages[k]),
@@ -2015,7 +2016,7 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
"sg_link_reserve: size=%d\n", size));
rem = size;
- num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ num = PAGE_SIZE << rsv_schp->page_order;
for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
req_schp->k_use_sg = k + 1;
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:martin.petersen@oracle.com Name:Martin K. Petersen To:true]] ReportedBy:<nil> ReviewedBy:<nil> TestedBy:<nil>]
|
| 1/1 |
2026/05/20 21:47 |
action |
base-commit-picker |
0m
Results: map[KernelBranch:master KernelCommit:5200f5f493f79f14bbdc349e402a40dfb32f23c8 KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git]
|
| 2/1 |
2026/05/20 21:47 |
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=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000ul, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200001000000ul, /*len=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// openat$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/05/20 21:47 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/d5a02ed91a4f019017141f71e695c75b27c3612e]
|
| 4/1 |
2026/05/20 21:47 |
action |
kernel-builder |
24m
Results: map[KernelObj:/app/workdir/cache/build/026618c4ed15adaec1a942aea2d54646727d539b]
|
| 5/1 |
2026/05/20 22:12 |
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/d5a02ed91a4f019017141f71e695c75b27c3612e/drivers/scsi/sg.c:1888:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 0 UID: 0 PID: 6185 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+0x385/0x410 lib/ubsan.c:494
sg_build_indirect+0x549/0x850 drivers/scsi/sg.c:1888
sg_build_reserve drivers/scsi/sg.c:1998 [inline]
sg_add_sfp drivers/scsi/sg.c:2178 [inline]
sg_open+0x122a/0x1a40 drivers/scsi/sg.c:349
chrdev_open+0x4cd/0x5e0 fs/char_dev.c:411
do_dentry_open+0x785/0x14e0 fs/open.c:947
vfs_open+0x3b/0x340 fs/open.c:1079
do_open fs/namei.c:4699 [inline]
path_openat+0x2e08/0x3860 fs/namei.c:4858
do_file_open+0x23e/0x4a0 fs/namei.c:4887
do_sys_openat2+0x113/0x200 fs/open.c:1364
do_sys_open fs/open.c:1370 [inline]
__do_sys_openat fs/open.c:1386 [inline]
__se_sys_openat fs/open.c:1381 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1381
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f72e679ce59
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:00007f72e75e3028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007f72e6a15fa0 RCX: 00007f72e679ce59
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007f72e6832d6f R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f72e6a16038 R14: 00007f72e6a15fa0 R15: 00007ffe5f34f718
</TASK>
---[ end trace ]---
ReproducedFaultInjection:]
|
| 6/1 |
2026/05/20 22:14 |
action |
codesearch-prepare |
15m
Results: map[Index:codesearch-index]
|
| 7/1 |
2026/05/20 22:29 |
agent |
debugger |
6m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with debugging a kernel crash root cause.
You need to provide a detailed explanation of the root cause for another developer to be
able to write a fix for the bug based on your explanation. Include all relevant details
into the response: function/struct/field/etc names, code snippets, line numbers,
macro/enum values, etc.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
------------[ cut here ]------------
UBSAN: shift-out-of-bounds in /app/workdir/cache/src/d5a02ed91a4f019017141f71e695c75b27c3612e/drivers/scsi/sg.c:1888:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 0 UID: 0 PID: 6185 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+0x385/0x410 lib/ubsan.c:494
sg_build_indirect+0x549/0x850 drivers/scsi/sg.c:1888
sg_build_reserve drivers/scsi/sg.c:1998 [inline]
sg_add_sfp drivers/scsi/sg.c:2178 [inline]
sg_open+0x122a/0x1a40 drivers/scsi/sg.c:349
chrdev_open+0x4cd/0x5e0 fs/char_dev.c:411
do_dentry_open+0x785/0x14e0 fs/open.c:947
vfs_open+0x3b/0x340 fs/open.c:1079
do_open fs/namei.c:4699 [inline]
path_openat+0x2e08/0x3860 fs/namei.c:4858
do_file_open+0x23e/0x4a0 fs/namei.c:4887
do_sys_openat2+0x113/0x200 fs/open.c:1364
do_sys_open fs/open.c:1370 [inline]
__do_sys_openat fs/open.c:1386 [inline]
__se_sys_openat fs/open.c:1381 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1381
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f72e679ce59
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:00007f72e75e3028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007f72e6a15fa0 RCX: 00007f72e679ce59
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007f72e6832d6f R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f72e6a16038 R14: 00007f72e6a15fa0 R15: 00007ffe5f34f718
</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=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200000000000ul, /*len=*/0x1000000ul, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x200001000000ul, /*len=*/0x1000ul, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// openat$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 excellent catch by syzkaller. The root cause of this crash is a missing local variable update after clamping a module parameter, combined with an unsafe bitwise shift on a signed 32-bit integer.
### Root Cause Analysis
The `sg` driver exposes the `scatter_elem_sz` module parameter, which can be modified at runtime by a privileged user via `/sys/module/sg/parameters/scatter_elem_sz`.
1. **The Sysfs Write:**
The syzkaller reproducer writes the string `"0"` to this sysfs file. The kernel parses this using `kstrtoint` and sets the global variable `scatter_elem_sz` to `0`. (Writing a negative value like `"-1"` would have the same effect).
2. **The Trigger:**
The reproducer then opens `/dev/sg0`. This invokes `sg_open()`, which calls `sg_add_sfp()`, and subsequently `sg_build_reserve()` and `sg_build_indirect()`.
3. **The Missing Variable Update:**
In `sg_build_indirect()`, the code reads `scatter_elem_sz` into a local variable `num` and attempts to clamp it to a minimum of `PAGE_SIZE`:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 scatter_elem_sz = PAGE_SIZE;
1901 scatter_elem_sz_prev = PAGE_SIZE;
1902 } else
1903 scatter_elem_sz_prev = num;
1904 }
1905
1906 order = get_order(num);
```
Notice that while the global `scatter_elem_sz` and `scatter_elem_sz_prev` are correctly clamped to `PAGE_SIZE`, **the local variable `num` is never updated**. Thus, `num` remains `0` (or negative).
4. **The `get_order()` Underflow:**
The code then calls `order = get_order(num);` where `num` is `0`.
Inside `get_order(unsigned long size)`, the size is decremented (`size--`), which underflows `0` to `0xffffffffffffffffUL`. It is then shifted right by `PAGE_SHIFT` (12), resulting in `0x000fffffffffffffUL`. The `fls64()` of this value is `52`. Thus, `get_order(0)` returns `52`.
5. **The UBSAN Shift-Out-Of-Bounds:**
Immediately after, the code calculates the return size:
```c
1907 retry:
1908 ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT` being `12` and `order` being `52`, the expression evaluates to `1 << 64`. Since the literal `1` is a signed 32-bit `int`, shifting it by 64 is undefined behavior and triggers the exact UBSAN warning seen in the crash: `shift exponent 64 is too large for 32-bit type 'int'`.
*(Note: There is also a secondary bug here. If a user intentionally writes a very large valid value like `0x7fffffff` to `scatter_elem_sz`, `order` becomes `19`. The expression `1 << (12 + 19)` evaluates to `1 << 31`, which shifts a bit into the sign bit of a signed 32-bit integerโalso undefined behavior in C).*
### Proposed Fix
To fix this, we need to update `num` to `PAGE_SIZE` when clamping, and change the literal `1` to `1UL` to prevent any undefined behavior when `order` is legitimately large.
```c
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1897,6 +1897,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1905,7 +1906,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = 1UL << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
```
|
| 8/2 |
2026/05/20 22:29 |
llm |
debugger |
0m
Model:
Tokens:
input: 6952
output: 23
thoughts: 280
Thoughts: **Analyzing a UBSAN Report in the SCSI Subsystem**
Okay, so I've got a syzkaller report on a UBSAN shift-out-of-bounds error, specifically in `sg_build_indirect` within the `scsi/sg.c` driver. The error message is clear: "shift exponent 64 is too large for 32-bit type 'int'." This instantly points towards a potential integer overflow issue during a bit-shift operation, and the call trace from `sg_build_indirect` down to `chrdev_open` gives me the context.
My immediate focus shifts to the C reproducer. Looks like it's writing to `/sys/module/sg/parameters/scatter_elem_sz`. The data being written starts with `30 00`, which initially seemed like "0\0", but now I see there is more to it than that. The buffer itself is a bit longer, 0x16b bytes, and the `count` is 0xe (14 bytes). Then the key thing is, `30` is the ASCII code for '0'. The data being written to `scatter_elem_sz` gives me a crucial clue. It tells me that the reproducer is interacting with the `sg` module's parameter `scatter_elem_sz`, which must have something to do with scatter/gather lists.
Now, I'm going to jump into `drivers/scsi/sg.c` around line 1888 to understand the context of `sg_build_indirect` and how this `scatter_elem_sz` parameter might be influencing the problematic shift operation.
|
| 9/2 |
2026/05/20 22:29 |
tool |
read-file |
0m
Args: map[File:drivers/scsi/sg.c]
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0-or-later
/*
* History:
* Started: Aug 9 by Lawrence Foard (entropy@world.std.com),
* to allow user process control of SCSI devices.
* Development Sponsored by Killy Corp. NY NY
*
* Original driver (sg.c):
* Copyright (C) 1992 Lawrence Foard
* Version 2 and 3 extensions to driver:
* Copyright (C) 1998 - 2014 Douglas Gilbert
*/
static int sg_version_num = 30536; /* 2 digits for each component */
#define SG_VERSION_STR "3.5.36"
/*
* D. P. Gilbert (dgilbert@interlog.com), notes:
* - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
* the kernel/module needs to be built with CONFIG_SCSI_LOGGING
* (otherwise the macros compile to empty statements).
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/mtio.h>
#include <linux/ioctl.h>
#include <linux/major.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/moduleparam.h>
#include <linux/cdev.h>
#include <linux/idr.h>
#include <linux/seq_file.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/blktrace_api.h>
#include <linux/mutex.h>
#include <linux/atomic.h>
#include <linux/ratelimit.h>
#include <linux/uio.h>
#include <linux/cred.h> /* for sg_check_file_access() */
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_driver.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_ioctl.h>
#include <scsi/scsi_tcq.h>
#include <scsi/sg.h>
#include "scsi_logging.h"
#ifdef CONFIG_SCSI_PROC_FS
#include <linux/proc_fs.h>
static char *sg_version_date = "20140603";
static int sg_proc_init(void);
#endif
#define SG_ALLOW_DIO_DEF 0
#define SG_MAX_DEVS (1 << MINORBITS)
/* SG_MAX_CDB_SIZE should be 260 (spc4r37 section 3.1.30) however the type
* of sg_io_hdr::cmd_len can only represent 255. All SCSI commands greater
* than 16 bytes are "variable length" whose length is a multiple of 4
*/
#define SG_MAX_CDB_SIZE 252
#define SG_DEFAULT_TIMEOUT mult_frac(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
/* 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.
*/
/* 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 */
static struct class_interface sg_interface = {
.add_dev = sg_add_device,
.remove_dev = sg_remove_device,
};
typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */
unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */
unsigned bufflen; /* Size of (aggregate) data buffer */
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;
struct sg_device; /* forward declarations */
struct sg_fd;
typedef struct sg_request { /* SG_MAX_QUEUE requests outstanding per file */
struct list_head entry; /* list entry */
struct sg_fd *parentfp; /* NULL -> not in use */
Sg_scatter_hold data; /* hold buffer, perhaps scatter list */
sg_io_hdr_t header; /* scsi command+info, see <scsi/sg.h> */
unsigned char sense_b[SCSI_SENSE_BUFFERSIZE];
char res_used; /* 1 -> using reserve buffer, 0 -> not ... */
char orphan; /* 1 -> drop on sight, 0 -> normal */
char sg_io_owned; /* 1 -> packet belongs to SG_IO */
/* done protected by rq_list_lock */
char done; /* 0->before bh, 1->before read, 2->read */
struct request *rq;
struct bio *bio;
struct execute_work ew;
} Sg_request;
typedef struct sg_fd { /* holds the state of a file descriptor */
struct list_head sfd_siblings; /* protected by device's sfd_lock */
struct sg_device *parentdp; /* owning device */
wait_queue_head_t read_wait; /* queue read until command done */
rwlock_t rq_list_lock; /* protect access to list in req_arr */
struct mutex f_mutex; /* protect against changes in this fd */
int timeout; /* defaults to SG_DEFAULT_TIMEOUT */
int timeout_user; /* defaults to SG_DEFAULT_TIMEOUT_USER */
Sg_scatter_hold reserve; /* buffer held for this file descriptor */
struct list_head rq_list; /* head of request list */
struct fasync_struct *async_qp; /* used by asynchronous notification */
Sg_request req_arr[SG_MAX_QUEUE]; /* used as singly-linked list */
char force_packid; /* 1 -> pack_id input to read(), 0 -> ignored */
char cmd_q; /* 1 -> allow command queuing, 0 -> don't */
unsigned char next_cmd_len; /* 0: automatic, >0: use on next write() */
char keep_orphan; /* 0 -> drop orphan (def), 1 -> keep for read() */
char mmap_called; /* 0 -> mmap() never called on this fd */
char res_in_use; /* 1 -> 'reserve' array in use */
struct kref f_ref;
struct execute_work ew;
} Sg_fd;
typedef struct sg_device { /* holds the state of each scsi generic device */
struct scsi_device *device;
wait_queue_head_t open_wait; /* queue open() when O_EXCL present */
struct mutex open_rel_lock; /* held when in open() or release() */
int sg_tablesize; /* adapter's max scatter-gather table size */
u32 index; /* device index number */
struct list_head sfds;
rwlock_t sfd_lock; /* protect access to sfd list */
atomic_t detaching; /* 0->device usable, 1->device detaching */
bool exclude; /* 1->open(O_EXCL) succeeded and is active */
int open_cnt; /* count of opens (perhaps < num(sfds) ) */
char sgdebug; /* 0->off, 1->sense, 9->dump dev, 10-> all devs */
char name[DISK_NAME_LEN];
struct cdev * cdev; /* char_dev [sysfs: /sys/cdev/major/sg<n>] */
struct kref d_ref;
} Sg_device;
/* tasklet or soft irq callback */
static enum rq_end_io_ret sg_rq_end_io(struct request *rq, blk_status_t status,
const struct io_comp_batch *iob);
static int sg_start_req(Sg_request *srp, unsigned char *cmd);
static int sg_finish_rem_req(Sg_request * srp);
static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size);
static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count,
Sg_request * srp);
static ssize_t sg_new_write(Sg_fd *sfp, struct file *file,
const char __user *buf, size_t count, int blocking,
int read_only, int sg_io_owned, 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_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
static void sg_remove_scat(Sg_fd * sfp, 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 Sg_fd *sg_add_sfp(Sg_device * sdp);
static void sg_remove_sfp(struct kref *);
static Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id, bool *busy);
static Sg_request *sg_add_request(Sg_fd * sfp);
static int sg_remove_request(Sg_fd * sfp, Sg_request * srp);
static Sg_device *sg_get_dev(int dev);
static void sg_device_destroy(struct kref *kref);
#define SZ_SG_HEADER sizeof(struct sg_header)
#define SZ_SG_IO_HDR sizeof(sg_io_hdr_t)
#define SZ_SG_IOVEC sizeof(sg_iovec_t)
#define SZ_SG_REQ_INFO sizeof(sg_req_info_t)
#define sg_printk(prefix, sdp, fmt, a...) \
sdev_prefix_printk(prefix, (sdp)->device, (sdp)->name, fmt, ##a)
/*
* The SCSI interfaces that use read() and write() as an asynchronous variant of
* ioctl(..., SG_IO, ...) are fundamentally unsafe, since there are lots of ways
* to trigger read() and write() calls from various contexts with elevated
* privileges. This can lead to kernel memory corruption (e.g. if these
* interfaces are called through splice()) and privilege escalation inside
* userspace (e.g. if a process with access to such a device passes a file
* descriptor to a SUID binary as stdin/stdout/stderr).
*
* This function provides protection for the legacy API by restricting the
* calling context.
*/
static int sg_check_file_access(struct file *filp, const char *caller)
{
if (filp->f_cred != current_real_cred()) {
pr_err_once("%s: process %d (%s) changed security contexts after opening file descriptor, this is not allowed.\n",
caller, task_tgid_vnr(current), current->comm);
return -EPERM;
}
return 0;
}
static int sg_allow_access(struct file *filp, unsigned char *cmd)
{
struct sg_fd *sfp = filp->private_data;
if (sfp->parentdp->device->type == TYPE_SCANNER)
return 0;
if (!scsi_cmd_allowed(cmd, filp->f_mode & FMODE_WRITE))
return -EPERM;
return 0;
}
static int
open_wait(Sg_device *sdp, int flags)
{
int retval = 0;
if (flags & O_EXCL) {
while (sdp->open_cnt > 0) {
mutex_unlock(&sdp->open_rel_lock);
retval = wait_event_interruptible(sdp->open_wait,
(atomic_read(&sdp->detaching) ||
!sdp->open_cnt));
mutex_lock(&sdp->open_rel_lock);
if (retval) /* -ERESTARTSYS */
return retval;
if (atomic_read(&sdp->detaching))
return -ENODEV;
}
} else {
while (sdp->exclude) {
mutex_unlock(&sdp->open_rel_lock);
retval = wait_event_interruptible(sdp->open_wait,
(atomic_read(&sdp->detaching) ||
!sdp->exclude));
mutex_lock(&sdp->open_rel_lock);
if (retval) /* -ERESTARTSYS */
return retval;
if (atomic_read(&sdp->detaching))
return -ENODEV;
}
}
return retval;
}
/* Returns 0 on success, else a negated errno value */
static int
sg_open(struct inode *inode, struct file *filp)
{
int dev = iminor(inode);
int flags = filp->f_flags;
struct request_queue *q;
struct scsi_device *device;
Sg_device *sdp;
Sg_fd *sfp;
int retval;
nonseekable_open(inode, filp);
if ((flags & O_EXCL) && (O_RDONLY == (flags & O_ACCMODE)))
return -EPERM; /* Can't lock it with read only access */
sdp = sg_get_dev(dev);
if (IS_ERR(sdp))
return PTR_ERR(sdp);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_open: flags=0x%x\n", flags));
/* This driver's module count bumped by fops_get in <linux/fs.h> */
/* Prevent the device driver from vanishing while we sleep */
device = sdp->device;
retval = scsi_device_get(device);
if (retval)
goto sg_put;
/* scsi_block_when_processing_errors() may block so bypass
* check if O_NONBLOCK. Permits SCSI commands to be issued
* during error recovery. Tread carefully. */
if (!((flags & O_NONBLOCK) ||
scsi_block_when_processing_errors(device))) {
retval = -ENXIO;
/* we are in error recovery for this device */
goto sdp_put;
}
mutex_lock(&sdp->open_rel_lock);
if (flags & O_NONBLOCK) {
if (flags & O_EXCL) {
if (sdp->open_cnt > 0) {
retval = -EBUSY;
goto error_mutex_locked;
}
} else {
if (sdp->exclude) {
retval = -EBUSY;
goto error_mutex_locked;
}
}
} else {
retval = open_wait(sdp, flags);
if (retval) /* -ERESTARTSYS or -ENODEV */
goto error_mutex_locked;
}
/* N.B. at this point we are holding the open_rel_lock */
if (flags & O_EXCL)
sdp->exclude = true;
if (sdp->open_cnt < 1) { /* no existing opens */
sdp->sgdebug = 0;
q = device->request_queue;
sdp->sg_tablesize = queue_max_segments(q);
}
sfp = sg_add_sfp(sdp);
if (IS_ERR(sfp)) {
retval = PTR_ERR(sfp);
goto out_undo;
}
filp->private_data = sfp;
sdp->open_cnt++;
mutex_unlock(&sdp->open_rel_lock);
retval = 0;
sg_put:
kref_put(&sdp->d_ref, sg_device_destroy);
return retval;
out_undo:
if (flags & O_EXCL) {
sdp->exclude = false; /* undo if error */
wake_up_interruptible(&sdp->open_wait);
}
error_mutex_locked:
mutex_unlock(&sdp->open_rel_lock);
sdp_put:
kref_put(&sdp->d_ref, sg_device_destroy);
scsi_device_put(device);
return retval;
}
/* Release resources associated with a successful sg_open()
* Returns 0 on success, else a negated errno value */
static int
sg_release(struct inode *inode, struct file *filp)
{
Sg_device *sdp;
Sg_fd *sfp;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_release\n"));
mutex_lock(&sdp->open_rel_lock);
sdp->open_cnt--;
/* possibly many open()s waiting on exlude clearing, start many;
* only open(O_EXCL)s wait on 0==open_cnt so only start one */
if (sdp->exclude) {
sdp->exclude = false;
wake_up_interruptible_all(&sdp->open_wait);
} else if (0 == sdp->open_cnt) {
wake_up_interruptible(&sdp->open_wait);
}
mutex_unlock(&sdp->open_rel_lock);
kref_put(&sfp->f_ref, sg_remove_sfp);
return 0;
}
static int get_sg_io_pack_id(int *pack_id, void __user *buf, size_t count)
{
struct sg_header __user *old_hdr = buf;
int reply_len;
if (count >= SZ_SG_HEADER) {
/* negative reply_len means v3 format, otherwise v1/v2 */
if (get_user(reply_len, &old_hdr->reply_len))
return -EFAULT;
if (reply_len >= 0)
return get_user(*pack_id, &old_hdr->pack_id);
if (in_compat_syscall() &&
count >= sizeof(struct compat_sg_io_hdr)) {
struct compat_sg_io_hdr __user *hp = buf;
return get_user(*pack_id, &hp->pack_id);
}
if (count >= sizeof(struct sg_io_hdr)) {
struct sg_io_hdr __user *hp = buf;
return get_user(*pack_id, &hp->pack_id);
}
}
/* no valid header was passed, so ignore the pack_id */
*pack_id = -1;
return 0;
}
static ssize_t
sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
{
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
int req_pack_id = -1;
bool busy;
sg_io_hdr_t *hp;
struct sg_header *old_hdr;
int retval;
/*
* This could cause a response to be stranded. Close the associated
* file descriptor to free up any resources being held.
*/
retval = sg_check_file_access(filp, __func__);
if (retval)
return retval;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_read: count=%d\n", (int) count));
if (sfp->force_packid)
retval = get_sg_io_pack_id(&req_pack_id, buf, count);
if (retval)
return retval;
srp = sg_get_rq_mark(sfp, req_pack_id, &busy);
if (!srp) { /* now wait on packet to arrive */
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
retval = wait_event_interruptible(sfp->read_wait,
((srp = sg_get_rq_mark(sfp, req_pack_id, &busy)) ||
(!busy && atomic_read(&sdp->detaching))));
if (!srp)
/* signal or detaching */
return retval ? retval : -ENODEV;
}
if (srp->header.interface_id != '\0')
return sg_new_read(sfp, buf, count, srp);
hp = &srp->header;
old_hdr = kzalloc(SZ_SG_HEADER, GFP_KERNEL);
if (!old_hdr)
return -ENOMEM;
old_hdr->reply_len = (int) hp->timeout;
old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */
old_hdr->pack_id = hp->pack_id;
old_hdr->twelve_byte =
((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;
old_hdr->target_status = hp->masked_status;
old_hdr->host_status = hp->host_status;
old_hdr->driver_status = hp->driver_status;
if ((CHECK_CONDITION & hp->masked_status) ||
(srp->sense_b[0] & 0x70) == 0x70) {
old_hdr->driver_status = DRIVER_SENSE;
memcpy(old_hdr->sense_buffer, srp->sense_b,
sizeof (old_hdr->sense_buffer));
}
switch (hp->host_status) {
/* This setup of 'result' is for backward compatibility and is best
ignored by the user who should use target, host + driver status */
case DID_OK:
case DID_PASSTHROUGH:
case DID_SOFT_ERROR:
old_hdr->result = 0;
break;
case DID_NO_CONNECT:
case DID_BUS_BUSY:
case DID_TIME_OUT:
old_hdr->result = EBUSY;
break;
case DID_BAD_TARGET:
case DID_ABORT:
case DID_PARITY:
case DID_RESET:
case DID_BAD_INTR:
old_hdr->result = EIO;
break;
case DID_ERROR:
old_hdr->result = (srp->sense_b[0] == 0 &&
hp->masked_status == GOOD) ? 0 : EIO;
break;
default:
old_hdr->result = EIO;
break;
}
/* Now copy the result back to the user buffer. */
if (count >= SZ_SG_HEADER) {
if (copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
buf += SZ_SG_HEADER;
if (count > old_hdr->reply_len)
count = old_hdr->reply_len;
if (count > SZ_SG_HEADER) {
if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {
retval = -EFAULT;
goto free_old_hdr;
}
}
} else
count = (old_hdr->result == 0) ? 0 : -EIO;
sg_finish_rem_req(srp);
sg_remove_request(sfp, srp);
retval = count;
free_old_hdr:
kfree(old_hdr);
return retval;
}
static ssize_t
sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp)
{
sg_io_hdr_t *hp = &srp->header;
int err = 0, err2;
int len;
if (in_compat_syscall()) {
if (count < sizeof(struct compat_sg_io_hdr)) {
err = -EINVAL;
goto err_out;
}
} else if (count < SZ_SG_IO_HDR) {
err = -EINVAL;
goto err_out;
}
hp->sb_len_wr = 0;
if ((hp->mx_sb_len > 0) && hp->sbp) {
if ((CHECK_CONDITION & hp->masked_status) ||
(srp->sense_b[0] & 0x70) == 0x70) {
int sb_len = SCSI_SENSE_BUFFERSIZE;
sb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len;
len = 8 + (int) srp->sense_b[7]; /* Additional sense length field */
len = (len > sb_len) ? sb_len : len;
if (copy_to_user(hp->sbp, srp->sense_b, len)) {
err = -EFAULT;
goto err_out;
}
hp->driver_status = DRIVER_SENSE;
hp->sb_len_wr = len;
}
}
if (hp->masked_status || hp->host_status || hp->driver_status)
hp->info |= SG_INFO_CHECK;
err = put_sg_io_hdr(hp, buf);
err_out:
err2 = sg_finish_rem_req(srp);
sg_remove_request(sfp, srp);
return err ? : err2 ? : count;
}
static ssize_t
sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
{
int mxsize, cmd_size, k;
int input_size, blocking;
unsigned char opcode;
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
struct sg_header old_hdr;
sg_io_hdr_t *hp;
unsigned char cmnd[SG_MAX_CDB_SIZE];
int retval;
retval = sg_check_file_access(filp, __func__);
if (retval)
return retval;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_write: count=%d\n", (int) count));
if (atomic_read(&sdp->detaching))
return -ENODEV;
if (!((filp->f_flags & O_NONBLOCK) ||
scsi_block_when_processing_errors(sdp->device)))
return -ENXIO;
if (count < SZ_SG_HEADER)
return -EIO;
if (copy_from_user(&old_hdr, buf, SZ_SG_HEADER))
return -EFAULT;
blocking = !(filp->f_flags & O_NONBLOCK);
if (old_hdr.reply_len < 0)
return sg_new_write(sfp, filp, buf, count,
blocking, 0, 0, NULL);
if (count < (SZ_SG_HEADER + 6))
return -EIO; /* The minimum scsi command length is 6 bytes. */
buf += SZ_SG_HEADER;
if (get_user(opcode, buf))
return -EFAULT;
if (!(srp = sg_add_request(sfp))) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,
"sg_write: queue full\n"));
return -EDOM;
}
mutex_lock(&sfp->f_mutex);
if (sfp->next_cmd_len > 0) {
cmd_size = sfp->next_cmd_len;
sfp->next_cmd_len = 0; /* reset so only this write() effected */
} else {
cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */
if ((opcode >= 0xc0) && old_hdr.twelve_byte)
cmd_size = 12;
}
mutex_unlock(&sfp->f_mutex);
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,
"sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size));
/* Determine buffer size. */
input_size = count - cmd_size;
mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;
mxsize -= SZ_SG_HEADER;
input_size -= SZ_SG_HEADER;
if (input_size < 0) {
sg_remove_request(sfp, srp);
return -EIO; /* User did not pass enough bytes for this command. */
}
hp = &srp->header;
hp->interface_id = '\0'; /* indicator of old interface tunnelled */
hp->cmd_len = (unsigned char) cmd_size;
hp->iovec_count = 0;
hp->mx_sb_len = 0;
if (input_size > 0)
hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?
SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;
else
hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;
hp->dxfer_len = mxsize;
if ((hp->dxfer_direction == SG_DXFER_TO_DEV) ||
(hp->dxfer_direction == SG_DXFER_TO_FROM_DEV))
hp->dxferp = (char __user *)buf + cmd_size;
else
hp->dxferp = NULL;
hp->sbp = NULL;
hp->timeout = old_hdr.reply_len; /* structure abuse ... */
hp->flags = input_size; /* structure abuse ... */
hp->pack_id = old_hdr.pack_id;
hp->usr_ptr = NULL;
if (copy_from_user(cmnd, buf, cmd_size)) {
sg_remove_request(sfp, srp);
return -EFAULT;
}
/*
* SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,
* but is is possible that the app intended SG_DXFER_TO_DEV, because there
* is a non-zero input_size, so emit a warning.
*/
if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {
printk_ratelimited(KERN_WARNING
"sg_write: data in/out %d/%d bytes "
"for SCSI command 0x%x-- guessing "
"data in;\n program %s not setting "
"count and/or reply_len properly\n",
old_hdr.reply_len - (int)SZ_SG_HEADER,
input_size, (unsigned int) cmnd[0],
current->comm);
}
k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);
return (k < 0) ? k : count;
}
static ssize_t
sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf,
size_t count, int blocking, int read_only, int sg_io_owned,
Sg_request **o_srp)
{
int k;
Sg_request *srp;
sg_io_hdr_t *hp;
unsigned char cmnd[SG_MAX_CDB_SIZE];
int timeout;
unsigned long ul_timeout;
if (count < SZ_SG_IO_HDR)
return -EINVAL;
sfp->cmd_q = 1; /* when sg_io_hdr seen, set command queuing on */
if (!(srp = sg_add_request(sfp))) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
"sg_new_write: queue full\n"));
return -EDOM;
}
srp->sg_io_owned = sg_io_owned;
hp = &srp->header;
if (get_sg_io_hdr(hp, buf)) {
sg_remove_request(sfp, srp);
return -EFAULT;
}
hp->duration = jiffies_to_msecs(jiffies);
if (hp->interface_id != 'S') {
sg_remove_request(sfp, srp);
return -ENOSYS;
}
if (hp->flags & SG_FLAG_MMAP_IO) {
if (hp->dxfer_len > sfp->reserve.bufflen) {
sg_remove_request(sfp, srp);
return -ENOMEM; /* MMAP_IO size must fit in reserve buffer */
}
if (hp->flags & SG_FLAG_DIRECT_IO) {
sg_remove_request(sfp, srp);
return -EINVAL; /* either MMAP_IO or DIRECT_IO (not both) */
}
if (sfp->res_in_use) {
sg_remove_request(sfp, srp);
return -EBUSY; /* reserve buffer already being used */
}
}
ul_timeout = msecs_to_jiffies(srp->header.timeout);
timeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX;
if ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) {
sg_remove_request(sfp, srp);
return -EMSGSIZE;
}
if (copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) {
sg_remove_request(sfp, srp);
return -EFAULT;
}
if (read_only && sg_allow_access(file, cmnd)) {
sg_remove_request(sfp, srp);
return -EPERM;
}
k = sg_common_write(sfp, srp, cmnd, timeout, blocking);
if (k < 0)
return k;
if (o_srp)
*o_srp = srp;
return count;
}
static int
sg_common_write(Sg_fd * sfp, Sg_request * srp,
unsigned char *cmnd, int timeout, int blocking)
{
int k, at_head;
Sg_device *sdp = sfp->parentdp;
sg_io_hdr_t *hp = &srp->header;
srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */
hp->status = 0;
hp->masked_status = 0;
hp->msg_status = 0;
hp->info = 0;
hp->host_status = 0;
hp->driver_status = 0;
hp->resid = 0;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n",
(int) cmnd[0], (int) hp->cmd_len));
if (hp->dxfer_len >= SZ_256M) {
sg_remove_request(sfp, srp);
return -EINVAL;
}
k = sg_start_req(srp, cmnd);
if (k) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
"sg_common_write: start_req err=%d\n", k));
sg_finish_rem_req(srp);
sg_remove_request(sfp, srp);
return k; /* probably out of space --> ENOMEM */
}
if (atomic_read(&sdp->detaching)) {
if (srp->bio) {
blk_mq_free_request(srp->rq);
srp->rq = NULL;
}
sg_finish_rem_req(srp);
sg_remove_request(sfp, srp);
return -ENODEV;
}
if (hp->interface_id != '\0' && /* v3 (or later) interface */
(SG_FLAG_Q_AT_TAIL & hp->flags))
at_head = 0;
else
at_head = 1;
srp->rq->timeout = timeout;
kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */
srp->rq->end_io = sg_rq_end_io;
blk_execute_rq_nowait(srp->rq, at_head);
return 0;
}
static int srp_done(Sg_fd *sfp, Sg_request *srp)
{
unsigned long flags;
int ret;
read_lock_irqsave(&sfp->rq_list_lock, flags);
ret = srp->done;
read_unlock_irqrestore(&sfp->rq_list_lock, flags);
return ret;
}
static int max_sectors_bytes(struct request_queue *q)
{
unsigned int max_sectors = queue_max_sectors(q);
max_sectors = min_t(unsigned int, max_sectors, INT_MAX >> 9);
return max_sectors << 9;
}
static void
sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo)
{
Sg_request *srp;
int val;
unsigned int ms;
val = 0;
list_for_each_entry(srp, &sfp->rq_list, entry) {
if (val >= SG_MAX_QUEUE)
break;
rinfo[val].req_state = srp->done + 1;
rinfo[val].problem =
srp->header.masked_status &
srp->header.host_status &
srp->header.driver_status;
if (srp->done)
rinfo[val].duration =
srp->header.duration;
else {
ms = jiffies_to_msecs(jiffies);
rinfo[val].duration =
(ms > srp->header.duration) ?
(ms - srp->header.duration) : 0;
}
rinfo[val].orphan = srp->orphan;
rinfo[val].sg_io_owned = srp->sg_io_owned;
rinfo[val].pack_id = srp->header.pack_id;
rinfo[val].usr_ptr = srp->header.usr_ptr;
val++;
}
}
#ifdef CONFIG_COMPAT
struct compat_sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */
char req_state;
char orphan;
char sg_io_owned;
char problem;
int pack_id;
compat_uptr_t usr_ptr;
unsigned int duration;
int unused;
};
static int put_compat_request_table(struct compat_sg_req_info __user *o,
struct sg_req_info *rinfo)
{
int i;
for (i = 0; i < SG_MAX_QUEUE; i++) {
if (copy_to_user(o + i, rinfo + i, offsetof(sg_req_info_t, usr_ptr)) ||
put_user((uintptr_t)rinfo[i].usr_ptr, &o[i].usr_ptr) ||
put_user(rinfo[i].duration, &o[i].duration) ||
put_user(rinfo[i].unused, &o[i].unused))
return -EFAULT;
}
return 0;
}
#endif
static long
sg_ioctl_common(struct file *filp, Sg_device *sdp, Sg_fd *sfp,
unsigned int cmd_in, void __user *p)
{
int __user *ip = p;
int result, val, read_only;
Sg_request *srp;
unsigned long iflags;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_ioctl: cmd=0x%x\n", (int) cmd_in));
read_only = (O_RDWR != (filp->f_flags & O_ACCMODE));
switch (cmd_in) {
case SG_IO:
if (atomic_read(&sdp->detaching))
return -ENODEV;
if (!scsi_block_when_processing_errors(sdp->device))
return -ENXIO;
result = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR,
1, read_only, 1, &srp);
if (result < 0)
return result;
result = wait_event_interruptible(sfp->read_wait,
srp_done(sfp, srp));
write_lock_irq(&sfp->rq_list_lock);
if (srp->done) {
srp->done = 2;
write_unlock_irq(&sfp->rq_list_lock);
result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp);
return (result < 0) ? result : 0;
}
srp->orphan = 1;
write_unlock_irq(&sfp->rq_list_lock);
return result; /* -ERESTARTSYS because signal hit process */
case SG_SET_TIMEOUT:
result = get_user(val, ip);
if (result)
return result;
if (val < 0)
return -EIO;
if (val >= mult_frac((s64)INT_MAX, USER_HZ, HZ))
val = min_t(s64, mult_frac((s64)INT_MAX, USER_HZ, HZ),
INT_MAX);
sfp->timeout_user = val;
sfp->timeout = mult_frac(val, HZ, USER_HZ);
return 0;
case SG_GET_TIMEOUT: /* N.B. User receives timeout as return value */
/* strange ..., for backward compatibility */
return sfp->timeout_user;
case SG_SET_FORCE_LOW_DMA:
/*
* N.B. This ioctl never worked properly, but failed to
* return an error value. So returning '0' to keep compability
* with legacy applications.
*/
return 0;
case SG_GET_LOW_DMA:
return put_user(0, ip);
case SG_GET_SCSI_ID:
{
sg_scsi_id_t v;
if (atomic_read(&sdp->detaching))
return -ENODEV;
memset(&v, 0, sizeof(v));
v.host_no = sdp->device->host->host_no;
v.channel = sdp->device->channel;
v.scsi_id = sdp->device->id;
v.lun = sdp->device->lun;
v.scsi_type = sdp->device->type;
v.h_cmd_per_lun = sdp->device->host->cmd_per_lun;
v.d_queue_depth = sdp->device->queue_depth;
if (copy_to_user(p, &v, sizeof(sg_scsi_id_t)))
return -EFAULT;
return 0;
}
case SG_SET_FORCE_PACK_ID:
result = get_user(val, ip);
if (result)
return result;
sfp->force_packid = val ? 1 : 0;
return 0;
case SG_GET_PACK_ID:
read_lock_irqsave(&sfp->rq_list_lock, iflags);
list_for_each_entry(srp, &sfp->rq_list, entry) {
if ((1 == srp->done) && (!srp->sg_io_owned)) {
read_unlock_irqrestore(&sfp->rq_list_lock,
iflags);
return put_user(srp->header.pack_id, ip);
}
}
read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
return put_user(-1, ip);
case SG_GET_NUM_WAITING:
read_lock_irqsave(&sfp->rq_list_lock, iflags);
val = 0;
list_for_each_entry(srp, &sfp->rq_list, entry) {
if ((1 == srp->done) && (!srp->sg_io_owned))
++val;
}
read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
return put_user(val, ip);
case SG_GET_SG_TABLESIZE:
return put_user(sdp->sg_tablesize, ip);
case SG_SET_RESERVED_SIZE:
result = get_user(val, ip);
if (result)
return result;
if (val < 0)
return -EINVAL;
val = min_t(int, val,
max_sectors_bytes(sdp->device->request_queue));
mutex_lock(&sfp->f_mutex);
if (val != sfp->reserve.bufflen) {
if (sfp->mmap_called ||
sfp->res_in_use) {
mutex_unlock(&sfp->f_mutex);
return -EBUSY;
}
sg_remove_scat(sfp, &sfp->reserve);
sg_build_reserve(sfp, val);
}
mutex_unlock(&sfp->f_mutex);
return 0;
case SG_GET_RESERVED_SIZE:
val = min_t(int, sfp->reserve.bufflen,
max_sectors_bytes(sdp->device->request_queue));
return put_user(val, ip);
case SG_SET_COMMAND_Q:
result = get_user(val, ip);
if (result)
return result;
sfp->cmd_q = val ? 1 : 0;
return 0;
case SG_GET_COMMAND_Q:
return put_user((int) sfp->cmd_q, ip);
case SG_SET_KEEP_ORPHAN:
result = get_user(val, ip);
if (result)
return result;
sfp->keep_orphan = val;
return 0;
case SG_GET_KEEP_ORPHAN:
return put_user((int) sfp->keep_orphan, ip);
case SG_NEXT_CMD_LEN:
result = get_user(val, ip);
if (result)
return result;
if (val > SG_MAX_CDB_SIZE)
return -ENOMEM;
sfp->next_cmd_len = (val > 0) ? val : 0;
return 0;
case SG_GET_VERSION_NUM:
return put_user(sg_version_num, ip);
case SG_GET_ACCESS_COUNT:
/* faked - we don't have a real access count anymore */
val = (sdp->device ? 1 : 0);
return put_user(val, ip);
case SG_GET_REQUEST_TABLE:
{
sg_req_info_t *rinfo;
rinfo = kcalloc(SG_MAX_QUEUE, SZ_SG_REQ_INFO,
GFP_KERNEL);
if (!rinfo)
return -ENOMEM;
read_lock_irqsave(&sfp->rq_list_lock, iflags);
sg_fill_request_table(sfp, rinfo);
read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
#ifdef CONFIG_COMPAT
if (in_compat_syscall())
result = put_compat_request_table(p, rinfo);
else
#endif
result = copy_to_user(p, rinfo,
SZ_SG_REQ_INFO * SG_MAX_QUEUE);
result = result ? -EFAULT : 0;
kfree(rinfo);
return result;
}
case SG_EMULATED_HOST:
if (atomic_read(&sdp->detaching))
return -ENODEV;
return put_user(sdp->device->host->hostt->emulated, ip);
case SCSI_IOCTL_SEND_COMMAND:
if (atomic_read(&sdp->detaching))
return -ENODEV;
return scsi_ioctl(sdp->device, filp->f_mode & FMODE_WRITE,
cmd_in, p);
case SG_SET_DEBUG:
result = get_user(val, ip);
if (result)
return result;
sdp->sgdebug = (char) val;
return 0;
case BLKSECTGET:
return put_user(max_sectors_bytes(sdp->device->request_queue),
ip);
case BLKTRACESETUP:
return blk_trace_setup(sdp->device->request_queue, sdp->name,
MKDEV(SCSI_GENERIC_MAJOR, sdp->index),
NULL, p);
case BLKTRACESTART:
return blk_trace_startstop(sdp->device->request_queue, 1);
case BLKTRACESTOP:
return blk_trace_startstop(sdp->device->request_queue, 0);
case BLKTRACETEARDOWN:
return blk_trace_remove(sdp->device->request_queue);
case SCSI_IOCTL_GET_IDLUN:
case SCSI_IOCTL_GET_BUS_NUMBER:
case SCSI_IOCTL_PROBE_HOST:
case SG_GET_TRANSFORM:
case SG_SCSI_RESET:
if (atomic_read(&sdp->detaching))
return -ENODEV;
break;
default:
if (read_only)
return -EPERM; /* don't know so take safe approach */
break;
}
result = scsi_ioctl_block_when_processing_errors(sdp->device,
cmd_in, filp->f_flags & O_NDELAY);
if (result)
return result;
return -ENOIOCTLCMD;
}
static long
sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)
{
void __user *p = (void __user *)arg;
Sg_device *sdp;
Sg_fd *sfp;
int ret;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
ret = sg_ioctl_common(filp, sdp, sfp, cmd_in, p);
if (ret != -ENOIOCTLCMD)
return ret;
return scsi_ioctl(sdp->device, filp->f_mode & FMODE_WRITE, cmd_in, p);
}
static __poll_t
sg_poll(struct file *filp, poll_table * wait)
{
__poll_t res = 0;
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
int count = 0;
unsigned long iflags;
sfp = filp->private_data;
if (!sfp)
return EPOLLERR;
sdp = sfp->parentdp;
if (!sdp)
return EPOLLERR;
poll_wait(filp, &sfp->read_wait, wait);
read_lock_irqsave(&sfp->rq_list_lock, iflags);
list_for_each_entry(srp, &sfp->rq_list, entry) {
/* if any read waiting, flag it */
if ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned))
res = EPOLLIN | EPOLLRDNORM;
++count;
}
read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
if (atomic_read(&sdp->detaching))
res |= EPOLLHUP;
else if (!sfp->cmd_q) {
if (0 == count)
res |= EPOLLOUT | EPOLLWRNORM;
} else if (count < SG_MAX_QUEUE)
res |= EPOLLOUT | EPOLLWRNORM;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_poll: res=0x%x\n", (__force u32) res));
return res;
}
static int
sg_fasync(int fd, struct file *filp, int mode)
{
Sg_device *sdp;
Sg_fd *sfp;
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_fasync: mode=%d\n", mode));
return fasync_helper(fd, filp, mode, &sfp->async_qp);
}
static vm_fault_t
sg_vma_fault(struct vm_fault *vmf)
{
struct vm_area_struct *vma = vmf->vma;
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
rsv_schp = &sfp->reserve;
offset = vmf->pgoff << PAGE_SHIFT;
if (offset >= rsv_schp->bufflen)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
"sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
sa = vma->vm_start;
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 < length) ? len : length;
if (offset < len) {
struct page *page = rsv_schp->pages[k] + (offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
}
sa += len;
offset -= len;
}
return VM_FAULT_SIGBUS;
}
static const struct vm_operations_struct sg_mmap_vm_ops = {
.fault = sg_vma_fault,
};
static int
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, length;
int ret = 0;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
req_sz = vma->vm_end - vma->vm_start;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
"sg_mmap starting, vm_start=%p, len=%d\n",
(void *) vma->vm_start, (int) req_sz));
if (vma->vm_pgoff)
return -EINVAL; /* want no offset */
rsv_schp = &sfp->reserve;
mutex_lock(&sfp->f_mutex);
if (req_sz > rsv_schp->bufflen) {
ret = -ENOMEM; /* cannot map more than reserved buffer */
goto out;
}
sa = vma->vm_start;
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 < length) ? len : length;
sa += len;
}
sfp->mmap_called = 1;
vm_flags_set(vma, VM_IO | VM_DONTEXPAND | VM_DONTDUMP);
vma->vm_private_data = sfp;
vma->vm_ops = &sg_mmap_vm_ops;
out:
mutex_unlock(&sfp->f_mutex);
return ret;
}
static void
sg_rq_end_io_usercontext(struct work_struct *work)
{
struct sg_request *srp = container_of(work, struct sg_request, ew.work);
struct sg_fd *sfp = srp->parentfp;
sg_finish_rem_req(srp);
sg_remove_request(sfp, srp);
kref_put(&sfp->f_ref, sg_remove_sfp);
}
/*
* This function is a "bottom half" handler that is called by the mid
* level when a command is completed (or has failed).
*/
static enum rq_end_io_ret
sg_rq_end_io(struct request *rq, blk_status_t status,
const struct io_comp_batch *iob)
{
struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(rq);
struct sg_request *srp = rq->end_io_data;
Sg_device *sdp;
Sg_fd *sfp;
unsigned long iflags;
unsigned int ms;
char *sense;
int result, resid, done = 1;
if (WARN_ON(srp->done != 0))
return RQ_END_IO_NONE;
sfp = srp->parentfp;
if (WARN_ON(sfp == NULL))
return RQ_END_IO_NONE;
sdp = sfp->parentdp;
if (unlikely(atomic_read(&sdp->detaching)))
pr_info("%s: device detaching\n", __func__);
sense = scmd->sense_buffer;
result = scmd->result;
resid = scmd->resid_len;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,
"sg_cmd_done: pack_id=%d, res=0x%x\n",
srp->header.pack_id, result));
srp->header.resid = resid;
if (0 != result) {
struct scsi_sense_hdr sshdr;
srp->header.status = 0xff & result;
srp->header.masked_status = sg_status_byte(result);
srp->header.msg_status = COMMAND_COMPLETE;
srp->header.host_status = host_byte(result);
srp->header.driver_status = driver_byte(result);
if ((sdp->sgdebug > 0) &&
((CHECK_CONDITION == srp->header.masked_status) ||
(COMMAND_TERMINATED == srp->header.masked_status)))
__scsi_print_sense(sdp->device, __func__, sense,
SCSI_SENSE_BUFFERSIZE);
/* Following if statement is a patch supplied by Eric Youngdale */
if (driver_byte(result) != 0
&& scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr)
&& !scsi_sense_is_deferred(&sshdr)
&& sshdr.sense_key == UNIT_ATTENTION
&& sdp->device->removable) {
/* Detected possible disc change. Set the bit - this */
/* may be used if there are filesystems using this device */
sdp->device->changed = 1;
}
}
if (scmd->sense_len)
memcpy(srp->sense_b, scmd->sense_buffer, SCSI_SENSE_BUFFERSIZE);
/* Rely on write phase to clean out srp status values, so no "else" */
/*
* Free the request as soon as it is complete so that its resources
* can be reused without waiting for userspace to read() the
* result. But keep the associated bio (if any) around until
* blk_rq_unmap_user() can be called from user context.
*/
srp->rq = NULL;
blk_mq_free_request(rq);
write_lock_irqsave(&sfp->rq_list_lock, iflags);
if (unlikely(srp->orphan)) {
if (sfp->keep_orphan)
srp->sg_io_owned = 0;
else
done = 0;
}
srp->done = done;
ms = jiffies_to_msecs(jiffies);
srp->header.duration = (ms > srp->header.duration) ?
(ms - srp->header.duration) : 0;
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
if (likely(done)) {
/* Now wake up any sg_read() that is waiting for this
* packet.
*/
wake_up_interruptible(&sfp->read_wait);
kill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN);
kref_put(&sfp->f_ref, sg_remove_sfp);
} else {
INIT_WORK(&srp->ew.work, sg_rq_end_io_usercontext);
schedule_work(&srp->ew.work);
}
return RQ_END_IO_NONE;
}
static const struct file_operations sg_fops = {
.owner = THIS_MODULE,
.read = sg_read,
.write = sg_write,
.poll = sg_poll,
.unlocked_ioctl = sg_ioctl,
.compat_ioctl = compat_ptr_ioctl,
.open = sg_open,
.mmap = sg_mmap,
.release = sg_release,
.fasync = sg_fasync,
};
static const struct class sg_sysfs_class = {
.name = "scsi_generic"
};
static int sg_sysfs_valid = 0;
static Sg_device *
sg_alloc(struct scsi_device *scsidp)
{
struct request_queue *q = scsidp->request_queue;
Sg_device *sdp;
unsigned long iflags;
int error;
u32 k;
sdp = kzalloc_obj(Sg_device);
if (!sdp) {
sdev_printk(KERN_WARNING, scsidp, "%s: kmalloc Sg_device "
"failure\n", __func__);
return ERR_PTR(-ENOMEM);
}
idr_preload(GFP_KERNEL);
write_lock_irqsave(&sg_index_lock, iflags);
error = idr_alloc(&sg_index_idr, sdp, 0, SG_MAX_DEVS, GFP_NOWAIT);
if (error < 0) {
if (error == -ENOSPC) {
sdev_printk(KERN_WARNING, scsidp,
"Unable to attach sg device type=%d, minor number exceeds %d\n",
scsidp->type, SG_MAX_DEVS - 1);
error = -ENODEV;
} else {
sdev_printk(KERN_WARNING, scsidp, "%s: idr "
"allocation Sg_device failure: %d\n",
__func__, error);
}
goto out_unlock;
}
k = error;
SCSI_LOG_TIMEOUT(3, sdev_printk(KERN_INFO, scsidp,
"sg_alloc: dev=%d \n", k));
sprintf(sdp->name, "sg%d", k);
sdp->device = scsidp;
mutex_init(&sdp->open_rel_lock);
INIT_LIST_HEAD(&sdp->sfds);
init_waitqueue_head(&sdp->open_wait);
atomic_set(&sdp->detaching, 0);
rwlock_init(&sdp->sfd_lock);
sdp->sg_tablesize = queue_max_segments(q);
sdp->index = k;
kref_init(&sdp->d_ref);
error = 0;
out_unlock:
write_unlock_irqrestore(&sg_index_lock, iflags);
idr_preload_end();
if (error) {
kfree(sdp);
return ERR_PTR(error);
}
return sdp;
}
static int
sg_add_device(struct device *cl_dev)
{
struct scsi_device *scsidp = to_scsi_device(cl_dev->parent);
Sg_device *sdp = NULL;
struct cdev * cdev = NULL;
int error;
unsigned long iflags;
if (!blk_get_queue(scsidp->request_queue)) {
pr_warn("%s: get scsi_device queue failed\n", __func__);
return -ENODEV;
}
error = -ENOMEM;
cdev = cdev_alloc();
if (!cdev) {
pr_warn("%s: cdev_alloc failed\n", __func__);
goto out;
}
cdev->owner = THIS_MODULE;
cdev->ops = &sg_fops;
sdp = sg_alloc(scsidp);
if (IS_ERR(sdp)) {
pr_warn("%s: sg_alloc failed\n", __func__);
error = PTR_ERR(sdp);
goto out;
}
error = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1);
if (error)
goto cdev_add_err;
sdp->cdev = cdev;
if (sg_sysfs_valid) {
struct device *sg_class_member;
sg_class_member = device_create(&sg_sysfs_class, cl_dev->parent,
MKDEV(SCSI_GENERIC_MAJOR,
sdp->index),
sdp, "%s", sdp->name);
if (IS_ERR(sg_class_member)) {
pr_err("%s: device_create failed\n", __func__);
error = PTR_ERR(sg_class_member);
goto cdev_add_err;
}
error = sysfs_create_link(&scsidp->sdev_gendev.kobj,
&sg_class_member->kobj, "generic");
if (error)
pr_err("%s: unable to make symlink 'generic' back "
"to sg%d\n", __func__, sdp->index);
} else
pr_warn("%s: sg_sys Invalid\n", __func__);
sdev_printk(KERN_NOTICE, scsidp, "Attached scsi generic sg%d "
"type %d\n", sdp->index, scsidp->type);
dev_set_drvdata(cl_dev, sdp);
return 0;
cdev_add_err:
write_lock_irqsave(&sg_index_lock, iflags);
idr_remove(&sg_index_idr, sdp->index);
write_unlock_irqrestore(&sg_index_lock, iflags);
kfree(sdp);
out:
if (cdev)
cdev_del(cdev);
blk_put_queue(scsidp->request_queue);
return error;
}
static void
sg_device_destroy(struct kref *kref)
{
struct sg_device *sdp = container_of(kref, struct sg_device, d_ref);
struct request_queue *q = sdp->device->request_queue;
unsigned long flags;
/* CAUTION! Note that the device can still be found via idr_find()
* even though the refcount is 0. Therefore, do idr_remove() BEFORE
* any other cleanup.
*/
blk_trace_remove(q);
blk_put_queue(q);
write_lock_irqsave(&sg_index_lock, flags);
idr_remove(&sg_index_idr, sdp->index);
write_unlock_irqrestore(&sg_index_lock, flags);
SCSI_LOG_TIMEOUT(3,
sg_printk(KERN_INFO, sdp, "sg_device_destroy\n"));
kfree(sdp);
}
static void
sg_remove_device(struct device *cl_dev)
{
struct scsi_device *scsidp = to_scsi_device(cl_dev->parent);
Sg_device *sdp = dev_get_drvdata(cl_dev);
unsigned long iflags;
Sg_fd *sfp;
int val;
if (!sdp)
return;
/* want sdp->detaching non-zero as soon as possible */
val = atomic_inc_return(&sdp->detaching);
if (val > 1)
return; /* only want to do following once per device */
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"%s\n", __func__));
read_lock_irqsave(&sdp->sfd_lock, iflags);
list_for_each_entry(sfp, &sdp->sfds, sfd_siblings) {
wake_up_interruptible_all(&sfp->read_wait);
kill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP);
}
wake_up_interruptible_all(&sdp->open_wait);
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 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");
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))");
static int __init
init_sg(void)
{
int rc;
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;
}
static void __exit
exit_sg(void)
{
#ifdef CONFIG_SCSI_PROC_FS
remove_proc_subtree("scsi/sg", NULL);
#endif /* CONFIG_SCSI_PROC_FS */
scsi_unregister_interface(&sg_interface);
class_unregister(&sg_sysfs_class);
sg_sysfs_valid = 0;
unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
SG_MAX_DEVS);
idr_destroy(&sg_index_idr);
}
static int
sg_start_req(Sg_request *srp, unsigned char *cmd)
{
int res;
struct request *rq;
Sg_fd *sfp = srp->parentfp;
sg_io_hdr_t *hp = &srp->header;
int dxfer_len = (int) hp->dxfer_len;
int dxfer_dir = hp->dxfer_direction;
unsigned int iov_count = hp->iovec_count;
Sg_scatter_hold *req_schp = &srp->data;
Sg_scatter_hold *rsv_schp = &sfp->reserve;
struct request_queue *q = sfp->parentdp->device->request_queue;
struct rq_map_data *md, map_data;
int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? ITER_SOURCE : ITER_DEST;
struct scsi_cmnd *scmd;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_start_req: dxfer_len=%d\n",
dxfer_len));
/*
* NOTE
*
* With scsi-mq enabled, there are a fixed number of preallocated
* requests equal in number to shost->can_queue. If all of the
* preallocated requests are already in use, then scsi_alloc_request()
* will sleep until an active command completes, freeing up a request.
* Although waiting in an asynchronous interface is less than ideal, we
* do not want to use BLK_MQ_REQ_NOWAIT here because userspace might
* not expect an EWOULDBLOCK from this condition.
*/
rq = scsi_alloc_request(q, hp->dxfer_direction == SG_DXFER_TO_DEV ?
REQ_OP_DRV_OUT : REQ_OP_DRV_IN, 0);
if (IS_ERR(rq))
return PTR_ERR(rq);
scmd = blk_mq_rq_to_pdu(rq);
if (hp->cmd_len > sizeof(scmd->cmnd)) {
blk_mq_free_request(rq);
return -EINVAL;
}
memcpy(scmd->cmnd, cmd, hp->cmd_len);
scmd->cmd_len = hp->cmd_len;
srp->rq = rq;
rq->end_io_data = srp;
scmd->allowed = SG_DEFAULT_RETRIES;
if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
return 0;
if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO &&
dxfer_dir != SG_DXFER_UNKNOWN && !iov_count &&
blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len))
md = NULL;
else
md = &map_data;
if (md) {
mutex_lock(&sfp->f_mutex);
if (dxfer_len <= rsv_schp->bufflen &&
!sfp->res_in_use) {
sfp->res_in_use = 1;
sg_link_reserve(sfp, srp, dxfer_len);
} else if (hp->flags & SG_FLAG_MMAP_IO) {
res = -EBUSY; /* sfp->res_in_use == 1 */
if (dxfer_len > rsv_schp->bufflen)
res = -ENOMEM;
mutex_unlock(&sfp->f_mutex);
return res;
} else {
res = sg_build_indirect(req_schp, sfp, dxfer_len);
if (res) {
mutex_unlock(&sfp->f_mutex);
return res;
}
}
mutex_unlock(&sfp->f_mutex);
md->pages = req_schp->pages;
md->page_order = req_schp->page_order;
md->nr_entries = req_schp->k_use_sg;
md->offset = 0;
md->null_mapped = hp->dxferp ? 0 : 1;
if (dxfer_dir == SG_DXFER_TO_FROM_DEV)
md->from_user = 1;
else
md->from_user = 0;
}
res = blk_rq_map_user_io(rq, md, hp->dxferp, hp->dxfer_len,
GFP_KERNEL, iov_count, iov_count, 1, rw);
if (!res) {
srp->bio = rq->bio;
if (!md) {
req_schp->dio_in_use = 1;
hp->info |= SG_INFO_DIRECT_IO;
}
}
return res;
}
static int
sg_finish_rem_req(Sg_request *srp)
{
int ret = 0;
Sg_fd *sfp = srp->parentfp;
Sg_scatter_hold *req_schp = &srp->data;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_finish_rem_req: res_used=%d\n",
(int) srp->res_used));
if (srp->bio)
ret = blk_rq_unmap_user(srp->bio);
if (srp->rq)
blk_mq_free_request(srp->rq);
if (srp->res_used)
sg_unlink_reserve(sfp, srp);
else
sg_remove_scat(sfp, req_schp);
return ret;
}
static int
sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
{
int sg_bufflen = tablesize * sizeof(struct page *);
gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
schp->pages = kzalloc(sg_bufflen, gfp_flags);
if (!schp->pages)
return -ENOMEM;
schp->sglist_len = sg_bufflen;
return tablesize; /* number of scat_gath elements allocated */
}
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);
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;
}
static void
sg_remove_scat(Sg_fd * sfp, Sg_scatter_hold * schp)
{
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
if (schp->pages && schp->sglist_len > 0) {
if (!schp->dio_in_use) {
int k;
for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
SCSI_LOG_TIMEOUT(5,
sg_printk(KERN_INFO, sfp->parentdp,
"sg_remove_scat: k=%d, pg=0x%p\n",
k, schp->pages[k]));
__free_pages(schp->pages[k], schp->page_order);
}
kfree(schp->pages);
}
}
memset(schp, 0, sizeof (*schp));
}
static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
int k, num;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,
"sg_read_oxfer: num_read_xfer=%d\n",
num_read_xfer));
if ((!outp) || (num_read_xfer <= 0))
return 0;
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(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
if (copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
if (num_read_xfer <= 0)
break;
outp += num;
}
}
return 0;
}
static void
sg_build_reserve(Sg_fd * sfp, int req_size)
{
Sg_scatter_hold *schp = &sfp->reserve;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_build_reserve: req_size=%d\n", req_size));
do {
if (req_size < PAGE_SIZE)
req_size = PAGE_SIZE;
if (0 == sg_build_indirect(schp, sfp, req_size))
return;
else
sg_remove_scat(sfp, schp);
req_size >>= 1; /* divide by 2 */
} while (req_size > (PAGE_SIZE / 2));
}
static void
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;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_link_reserve: size=%d\n", size));
rem = size;
num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
}
if (k >= rsv_schp->k_use_sg)
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
"sg_link_reserve: BAD size\n"));
}
static void
sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
{
Sg_scatter_hold *req_schp = &srp->data;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,
"sg_unlink_reserve: req->k_use_sg=%d\n",
(int) req_schp->k_use_sg));
req_schp->k_use_sg = 0;
req_schp->bufflen = 0;
req_schp->pages = NULL;
req_schp->page_order = 0;
req_schp->sglist_len = 0;
srp->res_used = 0;
/* Called without mutex lock to avoid deadlock */
sfp->res_in_use = 0;
}
static Sg_request *
sg_get_rq_mark(Sg_fd * sfp, int pack_id, bool *busy)
{
Sg_request *resp;
unsigned long iflags;
*busy = false;
write_lock_irqsave(&sfp->rq_list_lock, iflags);
list_for_each_entry(resp, &sfp->rq_list, entry) {
/* look for requests that are not SG_IO owned */
if ((!resp->sg_io_owned) &&
((-1 == pack_id) || (resp->header.pack_id == pack_id))) {
switch (resp->done) {
case 0: /* request active */
*busy = true;
break;
case 1: /* request done; response ready to return */
resp->done = 2; /* guard against other readers */
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
return resp;
case 2: /* response already being returned */
break;
}
}
}
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
return NULL;
}
/* always adds to end of list */
static Sg_request *
sg_add_request(Sg_fd * sfp)
{
int k;
unsigned long iflags;
Sg_request *rp = sfp->req_arr;
write_lock_irqsave(&sfp->rq_list_lock, iflags);
if (!list_empty(&sfp->rq_list)) {
if (!sfp->cmd_q)
goto out_unlock;
for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) {
if (!rp->parentfp)
break;
}
if (k >= SG_MAX_QUEUE)
goto out_unlock;
}
memset(rp, 0, sizeof (Sg_request));
rp->parentfp = sfp;
rp->header.duration = jiffies_to_msecs(jiffies);
list_add_tail(&rp->entry, &sfp->rq_list);
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
return rp;
out_unlock:
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
return NULL;
}
/* Return of 1 for found; 0 for not found */
static int
sg_remove_request(Sg_fd * sfp, Sg_request * srp)
{
unsigned long iflags;
int res = 0;
if (!sfp || !srp || list_empty(&sfp->rq_list))
return res;
write_lock_irqsave(&sfp->rq_list_lock, iflags);
if (!list_empty(&srp->entry)) {
list_del(&srp->entry);
srp->parentfp = NULL;
res = 1;
}
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
/*
* If the device is detaching, wakeup any readers in case we just
* removed the last response, which would leave nothing for them to
* return other than -ENODEV.
*/
if (unlikely(atomic_read(&sfp->parentdp->detaching)))
wake_up_interruptible_all(&sfp->read_wait);
return res;
}
static Sg_fd *
sg_add_sfp(Sg_device * sdp)
{
Sg_fd *sfp;
unsigned long iflags;
int bufflen;
sfp = kzalloc_obj(*sfp, GFP_ATOMIC | __GFP_NOWARN);
if (!sfp)
return ERR_PTR(-ENOMEM);
init_waitqueue_head(&sfp->read_wait);
rwlock_init(&sfp->rq_list_lock);
INIT_LIST_HEAD(&sfp->rq_list);
kref_init(&sfp->f_ref);
mutex_init(&sfp->f_mutex);
sfp->timeout = SG_DEFAULT_TIMEOUT;
sfp->timeout_user = SG_DEFAULT_TIMEOUT_USER;
sfp->force_packid = SG_DEF_FORCE_PACK_ID;
sfp->cmd_q = SG_DEF_COMMAND_Q;
sfp->keep_orphan = SG_DEF_KEEP_ORPHAN;
sfp->parentdp = sdp;
write_lock_irqsave(&sdp->sfd_lock, iflags);
if (atomic_read(&sdp->detaching)) {
write_unlock_irqrestore(&sdp->sfd_lock, iflags);
kfree(sfp);
return ERR_PTR(-ENODEV);
}
list_add_tail(&sfp->sfd_siblings, &sdp->sfds);
write_unlock_irqrestore(&sdp->sfd_lock, iflags);
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_add_sfp: sfp=0x%p\n", sfp));
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,
"sg_add_sfp: bufflen=%d, k_use_sg=%d\n",
sfp->reserve.bufflen,
sfp->reserve.k_use_sg));
kref_get(&sdp->d_ref);
__module_get(THIS_MODULE);
return sfp;
}
static void
sg_remove_sfp_usercontext(struct work_struct *work)
{
struct sg_fd *sfp = container_of(work, struct sg_fd, ew.work);
struct sg_device *sdp = sfp->parentdp;
struct scsi_device *device = sdp->device;
Sg_request *srp;
unsigned long iflags;
/* Cleanup any responses which were never read(). */
write_lock_irqsave(&sfp->rq_list_lock, iflags);
while (!list_empty(&sfp->rq_list)) {
srp = list_first_entry(&sfp->rq_list, Sg_request, entry);
list_del(&srp->entry);
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
sg_finish_rem_req(srp);
/*
* sg_rq_end_io() uses srp->parentfp. Hence, only clear
* srp->parentfp after blk_mq_free_request() has been called.
*/
srp->parentfp = NULL;
write_lock_irqsave(&sfp->rq_list_lock, iflags);
}
write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
if (sfp->reserve.bufflen > 0) {
SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,
"sg_remove_sfp: bufflen=%d, k_use_sg=%d\n",
(int) sfp->reserve.bufflen,
(int) sfp->reserve.k_use_sg));
sg_remove_scat(sfp, &sfp->reserve);
}
SCSI_LOG_TIMEOUT(6, sg_printk(KERN_INFO, sdp,
"sg_remove_sfp: sfp=0x%p\n", sfp));
kfree(sfp);
kref_put(&sdp->d_ref, sg_device_destroy);
scsi_device_put(device);
module_put(THIS_MODULE);
}
static void
sg_remove_sfp(struct kref *kref)
{
struct sg_fd *sfp = container_of(kref, struct sg_fd, f_ref);
struct sg_device *sdp = sfp->parentdp;
unsigned long iflags;
write_lock_irqsave(&sdp->sfd_lock, iflags);
list_del(&sfp->sfd_siblings);
write_unlock_irqrestore(&sdp->sfd_lock, iflags);
INIT_WORK(&sfp->ew.work, sg_remove_sfp_usercontext);
schedule_work(&sfp->ew.work);
}
#ifdef CONFIG_SCSI_PROC_FS
static int
sg_idr_max_id(int id, void *p, void *data)
{
int *k = data;
if (*k < id)
*k = id;
return 0;
}
static int
sg_last_dev(void)
{
int k = -1;
unsigned long iflags;
read_lock_irqsave(&sg_index_lock, iflags);
idr_for_each(&sg_index_idr, sg_idr_max_id, &k);
read_unlock_irqrestore(&sg_index_lock, iflags);
return k + 1; /* origin 1 */
}
#endif
/* must be called with sg_index_lock held */
static Sg_device *sg_lookup_dev(int dev)
{
return idr_find(&sg_index_idr, dev);
}
static Sg_device *
sg_get_dev(int dev)
{
struct sg_device *sdp;
unsigned long flags;
read_lock_irqsave(&sg_index_lock, flags);
sdp = sg_lookup_dev(dev);
if (!sdp)
sdp = ERR_PTR(-ENXIO);
else if (atomic_read(&sdp->detaching)) {
/* If sdp->detaching, then the refcount may already be 0, in
* which case it would be a bug to do kref_get().
*/
sdp = ERR_PTR(-ENODEV);
} else
kref_get(&sdp->d_ref);
read_unlock_irqrestore(&sg_index_lock, flags);
return sdp;
}
#ifdef CONFIG_SCSI_PROC_FS
static int sg_proc_seq_show_int(struct seq_file *s, void *v);
static int sg_proc_single_open_adio(struct inode *inode, struct file *file);
static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer,
size_t count, loff_t *off);
static const struct proc_ops adio_proc_ops = {
.proc_open = sg_proc_single_open_adio,
.proc_read = seq_read,
.proc_lseek = seq_lseek,
.proc_write = sg_proc_write_adio,
.proc_release = single_release,
};
static int sg_proc_single_open_dressz(struct inode *inode, struct file *file);
static ssize_t sg_proc_write_dressz(struct file *filp,
const char __user *buffer, size_t count, loff_t *off);
static const struct proc_ops dressz_proc_ops = {
.proc_open = sg_proc_single_open_dressz,
.proc_read = seq_read,
.proc_lseek = seq_lseek,
.proc_write = sg_proc_write_dressz,
.proc_release = single_release,
};
static int sg_proc_seq_show_version(struct seq_file *s, void *v);
static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v);
static int sg_proc_seq_show_dev(struct seq_file *s, void *v);
static void * dev_seq_start(struct seq_file *s, loff_t *pos);
static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos);
static void dev_seq_stop(struct seq_file *s, void *v);
static const struct seq_operations dev_seq_ops = {
.start = dev_seq_start,
.next = dev_seq_next,
.stop = dev_seq_stop,
.show = sg_proc_seq_show_dev,
};
static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v);
static const struct seq_operations devstrs_seq_ops = {
.start = dev_seq_start,
.next = dev_seq_next,
.stop = dev_seq_stop,
.show = sg_proc_seq_show_devstrs,
};
static int sg_proc_seq_show_debug(struct seq_file *s, void *v);
static const struct seq_operations debug_seq_ops = {
.start = dev_seq_start,
.next = dev_seq_next,
.stop = dev_seq_stop,
.show = sg_proc_seq_show_debug,
};
static int
sg_proc_init(void)
{
struct proc_dir_entry *p;
p = proc_mkdir("scsi/sg", NULL);
if (!p)
return 1;
proc_create("allow_dio", S_IRUGO | S_IWUSR, p, &adio_proc_ops);
proc_create_seq("debug", S_IRUGO, p, &debug_seq_ops);
proc_create("def_reserved_size", S_IRUGO | S_IWUSR, p, &dressz_proc_ops);
proc_create_single("device_hdr", S_IRUGO, p, sg_proc_seq_show_devhdr);
proc_create_seq("devices", S_IRUGO, p, &dev_seq_ops);
proc_create_seq("device_strs", S_IRUGO, p, &devstrs_seq_ops);
proc_create_single("version", S_IRUGO, p, sg_proc_seq_show_version);
return 0;
}
static int sg_proc_seq_show_int(struct seq_file *s, void *v)
{
seq_printf(s, "%d\n", *((int *)s->private));
return 0;
}
static int sg_proc_single_open_adio(struct inode *inode, struct file *file)
{
return single_open(file, sg_proc_seq_show_int, &sg_allow_dio);
}
static ssize_t
sg_proc_write_adio(struct file *filp, const char __user *buffer,
size_t count, loff_t *off)
{
int err;
unsigned long num;
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
return -EACCES;
err = kstrtoul_from_user(buffer, count, 0, &num);
if (err)
return err;
sg_allow_dio = num ? 1 : 0;
return count;
}
static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)
{
return single_open(file, sg_proc_seq_show_int, &def_reserved_size);
}
static ssize_t
sg_proc_write_dressz(struct file *filp, const char __user *buffer,
size_t count, loff_t *off)
{
int err;
unsigned long k = ULONG_MAX;
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
return -EACCES;
err = kstrtoul_from_user(buffer, count, 0, &k);
if (err)
return err;
if (k <= 1048576) { /* limit "big buff" to 1 MB */
def_reserved_size = k;
return count;
}
return -ERANGE;
}
static int sg_proc_seq_show_version(struct seq_file *s, void *v)
{
seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR,
sg_version_date);
return 0;
}
static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v)
{
seq_puts(s, "host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\tonline\n");
return 0;
}
struct sg_proc_deviter {
loff_t index;
size_t max;
};
static void * dev_seq_start(struct seq_file *s, loff_t *pos)
{
struct sg_proc_deviter * it = kmalloc_obj(*it);
s->private = it;
if (! it)
return NULL;
it->index = *pos;
it->max = sg_last_dev();
if (it->index >= it->max)
return NULL;
return it;
}
static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
struct sg_proc_deviter * it = s->private;
*pos = ++it->index;
return (it->index < it->max) ? it : NULL;
}
static void dev_seq_stop(struct seq_file *s, void *v)
{
kfree(s->private);
}
static int sg_proc_seq_show_dev(struct seq_file *s, void *v)
{
struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
Sg_device *sdp;
struct scsi_device *scsidp;
unsigned long iflags;
read_lock_irqsave(&sg_index_lock, iflags);
sdp = it ? sg_lookup_dev(it->index) : NULL;
if ((NULL == sdp) || (NULL == sdp->device) ||
(atomic_read(&sdp->detaching)))
seq_puts(s, "-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n");
else {
scsidp = sdp->device;
seq_printf(s, "%d\t%d\t%d\t%llu\t%d\t%d\t%d\t%d\t%d\n",
scsidp->host->host_no, scsidp->channel,
scsidp->id, scsidp->lun, (int) scsidp->type,
1,
(int) scsidp->queue_depth,
(int) scsi_device_busy(scsidp),
(int) scsi_device_online(scsidp));
}
read_unlock_irqrestore(&sg_index_lock, iflags);
return 0;
}
static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v)
{
struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
Sg_device *sdp;
struct scsi_device *scsidp;
unsigned long iflags;
read_lock_irqsave(&sg_index_lock, iflags);
sdp = it ? sg_lookup_dev(it->index) : NULL;
scsidp = sdp ? sdp->device : NULL;
if (sdp && scsidp && (!atomic_read(&sdp->detaching)))
seq_printf(s, "%8.8s\t%16.16s\t%4.4s\n",
scsidp->vendor, scsidp->model, scsidp->rev);
else
seq_puts(s, "<no active device>\n");
read_unlock_irqrestore(&sg_index_lock, iflags);
return 0;
}
/* must be called while holding sg_index_lock */
static void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp)
{
int k, new_interface, blen, usg;
Sg_request *srp;
Sg_fd *fp;
const sg_io_hdr_t *hp;
const char * cp;
unsigned int ms;
unsigned int duration;
k = 0;
list_for_each_entry(fp, &sdp->sfds, sfd_siblings) {
k++;
read_lock(&fp->rq_list_lock); /* irqs already disabled */
seq_printf(s, " FD(%d): timeout=%dms bufflen=%d "
"(res)sgat=%d low_dma=%d\n", k,
jiffies_to_msecs(fp->timeout),
fp->reserve.bufflen,
(int) fp->reserve.k_use_sg, 0);
seq_printf(s, " cmd_q=%d f_packid=%d k_orphan=%d closed=0\n",
(int) fp->cmd_q, (int) fp->force_packid,
(int) fp->keep_orphan);
list_for_each_entry(srp, &fp->rq_list, entry) {
hp = &srp->header;
new_interface = (hp->interface_id == '\0') ? 0 : 1;
if (srp->res_used) {
if (new_interface &&
(SG_FLAG_MMAP_IO & hp->flags))
cp = " mmap>> ";
else
cp = " rb>> ";
} else {
if (SG_INFO_DIRECT_IO_MASK & hp->info)
cp = " dio>> ";
else
cp = " ";
}
seq_puts(s, cp);
blen = srp->data.bufflen;
usg = srp->data.k_use_sg;
seq_puts(s, srp->done ?
((1 == srp->done) ? "rcv:" : "fin:")
: "act:");
seq_printf(s, " id=%d blen=%d",
srp->header.pack_id, blen);
if (srp->done)
seq_printf(s, " dur=%u", hp->duration);
else {
ms = jiffies_to_msecs(jiffies);
duration = READ_ONCE(hp->duration);
if (duration)
duration = (ms > duration ?
ms - duration : 0);
seq_printf(s, " t_o/elap=%u/%u",
(new_interface ? hp->timeout :
jiffies_to_msecs(fp->timeout)),
duration);
}
seq_printf(s, "ms sgat=%d op=0x%02x\n", usg,
(int) srp->data.cmd_opcode);
}
if (list_empty(&fp->rq_list))
seq_puts(s, " No requests active\n");
read_unlock(&fp->rq_list_lock);
}
}
static int sg_proc_seq_show_debug(struct seq_file *s, void *v)
{
struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
Sg_device *sdp;
unsigned long iflags;
if (it && (0 == it->index))
seq_printf(s, "max_active_device=%d def_reserved_size=%d\n",
(int)it->max, def_reserved_size);
read_lock_irqsave(&sg_index_lock, iflags);
sdp = it ? sg_lookup_dev(it->index) : NULL;
if (NULL == sdp)
goto skip;
read_lock(&sdp->sfd_lock);
if (!list_empty(&sdp->sfds)) {
seq_printf(s, " >>> device=%s ", sdp->name);
if (atomic_read(&sdp->detaching))
seq_puts(s, "detaching pending close ");
else if (sdp->device) {
struct scsi_device *scsidp = sdp->device;
seq_printf(s, "%d:%d:%d:%llu em=%d",
scsidp->host->host_no,
scsidp->channel, scsidp->id,
scsidp->lun,
scsidp->host->hostt->emulated);
}
seq_printf(s, " sg_tablesize=%d excl=%d open_cnt=%d\n",
sdp->sg_tablesize, sdp->exclude, sdp->open_cnt);
sg_proc_debug_helper(s, sdp);
}
read_unlock(&sdp->sfd_lock);
skip:
read_unlock_irqrestore(&sg_index_lock, iflags);
return 0;
}
#endif /* CONFIG_SCSI_PROC_FS */
module_init(init_sg);
module_exit(exit_sg);
]
|
| 10/2 |
2026/05/20 22:29 |
llm |
debugger |
0m
Model:
Tokens:
input: 37429
output: 39
thoughts: 1638
Thoughts: **Analyzing the SCSI Scatter-Gather Crash**
Okay, so I've got a crash report: "UBSAN: shift-out-of-bounds" in `drivers/scsi/sg.c` at line 1888, with the telltale sign of a "shift exponent 64 is too large for 32-bit type 'int'". Immediately, I'm drawn to that shift operation, which is where the problem lies.
My initial thought is to navigate to the `sg_build_indirect` function within that file. I quickly review the code and pinpoint line 1888: `blk_size = ALIGN(blk_size, SG_SECTOR_SZ);`. Hmmm, `ALIGN` is a macro, so I need to check its definition. Following the macro expansion, I get: `(((x) + (mask)) & ~(mask))`. This part seems unlikely to cause the shift, so that is not the cause.
So, where is the shift operation? I recall the crash report pointing to the shift operation being at line 1888, so I need to verify that. After a quick scan, and after making a note that the line numbers might be off, I realize that the actual culprit is the line: `ret_sz = 1 << (PAGE_SHIFT + order);`. Bingo! It's the bit-shift that's causing the out-of-bounds error.
If `order` is large enough, then `PAGE_SHIFT + order` will exceed 32. Since `PAGE_SHIFT` is typically 12, then if `order` is 20, then the result will be 32, which is too large for the int and would cause a crash. The crash report says that the shift is by 64, so it must be a really large value for `order`. Where does this `order` come from?
The answer comes from the preceding lines: `order = get_order(num);` where `num` comes from `scatter_elem_sz`. And then I see it: `scatter_elem_sz` is a *module parameter*. Ah, this is where the vulnerability lies! The reproducer writes to `/sys/module/sg/parameters/scatter_elem_sz`. It's writing a large byte array starting with something that looks like "0\0" โ potentially, this byte array could represent a large number. I need to note that they are only writing 14 bytes into a larger buffer.
And then, I remember the declaration: `module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);` `scatter_elem_sz` is an *int*. If the input string in `/sys/module/sg/parameters/scatter_elem_sz` is a really large string representation of a value, it would get parsed into an int value. This is likely how we can control the value of `scatter_elem_sz`. Does the parsing process handle overflows? Does it clamp values, or does it lead to a wraparound? If it clamps, the problem will not be there, but if it wraps, that would cause `order` to be a very large value.
So, I need to check how `param_set_int` and the integer parsing works. That's the key to exploiting this shift-out-of-bounds vulnerability.
|
| 11/2 |
2026/05/20 22:30 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:kernel/params.c IncludeLines:true Name:param_set_int]
Results: map[SourceCode: 237: STANDARD_PARAM_DEF(int, int, "%i", kstrtoint);
SourceFile:kernel/params.c]
|
| 12/2 |
2026/05/20 22:30 |
llm |
debugger |
0m
Model:
Tokens:
input: 39897
output: 42
thoughts: 422
Thoughts: **Analyzing Potential Integer Overflow Vulnerability**
Okay, so I'm looking at this code and something's not quite right. I see that `kstrtoint` is used, and I remember that it returns `-ERANGE` on overflow. But, what happens with negative values? If someone writes "-1" to `scatter_elem_sz`, `kstrtoint` will succeed and set `scatter_elem_sz` to `-1`.
Then, we have `num = scatter_elem_sz;`, so `num` becomes `-1`. I see the `if (num < PAGE_SIZE)` check coming up. Now `-1 < 4096` is true, so that branch is taken. Consequently, `scatter_elem_sz` and `scatter_elem_sz_prev` get updated to `PAGE_SIZE`.
But wait a minute... `num` is *still* `-1`! This is where it gets interesting.
Specifically:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 scatter_elem_sz = PAGE_SIZE;
1901 scatter_elem_sz_prev = PAGE_SIZE;
1902 } else
1903 scatter_elem_sz_prev = num;
1904 }
1905
1906 order = get_order(num);
```
If `num` is `-1`, the condition `num < PAGE_SIZE` is true, and it updates `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`. But, it *doesn't* update `num`! So `num` remains at `-1`. The really important line here is `order = get_order(num);`, where `num` is `-1`. The question now becomes: what will `get_order(-1)` return? That's where the potential vulnerability lies โ what will be done with that return value? It could cause all sorts of unexpected behavior. I need to dig into the `get_order` implementation to understand the implications of feeding it a negative value.
|
| 13/2 |
2026/05/20 22:30 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/asm-generic/getorder.h IncludeLines:true 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]
|
| 14/2 |
2026/05/20 22:30 |
llm |
debugger |
0m
Model:
Tokens:
input: 41470
output: 23
thoughts: 1499
Thoughts: **Analyzing the Integer Overflow in `sg_build_indirect`**
Okay, let's break this down. The core issue seems to be an integer overflow caused by an incorrect shift operation. If `num` within `sg_build_indirect` is negative (like -1), or zero, then a 64-bit integer, `size`, within `get_order()` is incorrectly manipulated via an unsigned integer `size--`. This then causes `fls64` to return 52 in this case, and ultimately leads to `ret_sz = 1 << (PAGE_SHIFT + order)` which becomes `1 << 64`. Since `1` is a 32-bit `int`, a shift by 64 is undefined behavior, causing UBSAN to catch it.
Let's look at the scenario where `scatter_elem_sz` is 0. If `scatter_elem_sz` is set to `0`, then `num` in the function becomes `0`. The code checks if `num` is less than `PAGE_SIZE`, which it is. `scatter_elem_sz` is then set to `PAGE_SIZE`. But crucially, `num` *remains* 0! The subsequent call to `get_order(num)` ends up passing 0.
Looking at `get_order(0)` shows that the function eventually results in a returned order of 52. The comment in `get_order` clearly says the result is undefined if the size is 0. This reinforces the problem.
Now, let's connect this to the reproducer. The provided `memcpy` call has a source string that starts with `"0"`. `kstrtoint` converts this to `0`, causing `scatter_elem_sz` to be `0` through a sysfs interface.
The key part is:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 scatter_elem_sz = PAGE_SIZE;
1901 scatter_elem_sz_prev = PAGE_SIZE;
1902 } else
1903 scatter_elem_sz_prev = num;
1904 }
1905
1906 order = get_order(num);
```
While `scatter_elem_sz` is set to `PAGE_SIZE`, `num` stays at `0`. The order calculated from `get_order(num)` ends up being `52`. This is where the issue truly lies - `num` should also be set to `PAGE_SIZE` when `scatter_elem_sz` is changed.
The actual integer overflow occurs because `1` is a 32-bit `int` literal. However, shifting by 64 is *still* undefined, even with a 64-bit integer as the value, because the shift count cannot be greater than or equal to the bit width of the type.
The fix is clear: if `num < PAGE_SIZE`, we must set `num = PAGE_SIZE;`. This ensures that the calculation uses the clamped size.
If `num` is `PAGE_SIZE`, then `get_order(PAGE_SIZE)` is `0`, and the `ret_sz = 1 << (PAGE_SHIFT + order)` becomes `4096`. This is the correct value.
I should check the rest of the code for any similar instances where `scatter_elem_sz` is being used to make sure there are no other places with a similar bug.
|
| 15/2 |
2026/05/20 22:30 |
tool |
codesearch-find-references |
0m
Args: map[Name:scatter_elem_sz]
Results: map[References:<nil> TruncatedOutput:false]
|
| 16/2 |
2026/05/20 22:30 |
llm |
debugger |
1m
Model:
Tokens:
input: 43829
output: 19
thoughts: 25
Thoughts: Here's my thought process, summarized as you requested:
**Navigating the SCSI Driver's Scatter-Gather Implementation**
Okay, I'm diving into this. The task at hand involves understanding how scatter-gather I/O is handled within the SCSI subsystem. Specifically, I'm thinking about how the size of individual scatter elements is managed. To get a handle on this, the first thing I need to do is locate the relevant code. And the place to start, given the SCSI context, is almost certainly the `sg.c` file within the `drivers/scsi` directory. I'm going to search for the term `scatter_elem_sz` within that file. That should get me to the heart of the matter. It's the most logical place to begin digging into the implementation details.
|
| 17/2 |
2026/05/20 22:31 |
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=1591=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1624-
drivers/scsi/sg.c:1625:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1626-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1659=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1660-
drivers/scsi/sg.c:1661:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1662- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1667=init_sg(void)
--
drivers/scsi/sg.c-1670-
drivers/scsi/sg.c:1671: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1672: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1673: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1674- }
--
drivers/scsi/sg.c=1855=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1876-
drivers/scsi/sg.c:1877: num = scatter_elem_sz;
drivers/scsi/sg.c:1878: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1879- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1880: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1881: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1882- } else
drivers/scsi/sg.c:1883: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1884- }
--
drivers/scsi/sg.c-1892-
drivers/scsi/sg.c:1893: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1894: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1895-
--
drivers/scsi/sg.c-1899-
drivers/scsi/sg.c:1900: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1901: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1902: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1903: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1904- }
]
|
| 18/2 |
2026/05/20 22:31 |
llm |
debugger |
0m
Model:
Tokens:
input: 45067
output: 41
thoughts: 3153
Thoughts: **Analyzing `scatter_elem_sz` and Potential Integer Overflow Issues**
Okay, so I've been tracing the logic surrounding `scatter_elem_sz` in this `sg_build_indirect` loop. Initially, I noticed that `scatter_elem_sz` is used in a specific `sg_build_indirect` loop and needs some adjustment based on some comparison in the preceding code. The `scatter_elem_sz` variable is changed in the code:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 num = PAGE_SIZE;
1901 scatter_elem_sz = PAGE_SIZE;
1902 scatter_elem_sz_prev = PAGE_SIZE;
1903 } else
1904 scatter_elem_sz_prev = num;
1905 }
```
The bug may be fixed by just setting `num = PAGE_SIZE;`. Let me see what that means for the following loop:
```c
1907 retry:
1908 ret_sz = 1 << (PAGE_SHIFT + order);
1909
1910 for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1911 k++, rem_sz -= ret_sz) {
1912
1913 num = (rem_sz > scatter_elem_sz_prev) ?
1914 scatter_elem_sz_prev : rem_sz;
1915
1916 schp->pages[k] = alloc_pages(gfp_mask, order);
1917 if (!schp->pages[k])
1918 goto out;
1919
1920 if (num == scatter_elem_sz_prev) {
1921 if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1922 scatter_elem_sz = ret_sz;
1923 scatter_elem_sz_prev = ret_sz;
1924 }
1925 }
...
```
If `num` is updated to `PAGE_SIZE`, the order is computed as `0`, and the loop is correct and safe, even if `num` is assigned 4096.
I'm now investigating potential edge cases. If I were to write `-1` to `/sys/module/sg/parameters/scatter_elem_sz`, it would become negative. After the addition, everything still works, and this will be assigned 4096.
However, if `scatter_elem_sz` is set to a very large value like `0x7fffffff`, things get interesting. `order` becomes 19. If `ret_sz = 1 << (PAGE_SHIFT + order)`, there's potential for undefined behavior. This can lead to a crash because when computed as a 32-bit `int`, the shift into the sign bit will overflow and either result in a negative number or trigger an undefined behavior crash. It is most likely to crash because of a shift exponent 64 is too large for 32-bit type 'int'. The maximum order is defined as `MAX_PAGE_ORDER`. Then `alloc_pages` is supposed to fail because `order > MAX_PAGE_ORDER`. And `ret_sz` is calculated *before* `alloc_pages` which is risky.
Looking closer, if `alloc_pages` fails, `order` is decremented and the function retries. Although, `1 << 31` is not used directly. Still, `1 << 31` is UB. Should `num` be clamped to a maximum value, or be set to `PAGE_SIZE` to make it safer? Because, if `num` is very large, the undefined behavior will occur.
Given that `get_order(-1)` returns 52, I realize the crash is triggered when `num` is negative, which leads to a large `order` (52 in this case).
To mitigate this, if `num` is clamped to `PAGE_SIZE`, the order will be at most 0. If `num` is large
|
| 19/2 |
2026/05/20 22:32 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:include/asm-generic/page.h IncludeLines:true Name:PAGE_SIZE]
Results: map[SourceCode: SourceFile:]
|
| 20/2 |
2026/05/20 22:32 |
llm |
debugger |
2m
Model:
Tokens:
input: 49307
output: 47
thoughts: 28
Thoughts: Okay, here's my attempt at summarizing that thought process, keeping in mind the user is an expert:
**Finding PAGE_SIZE in the X86 Architecture Headers**
Alright, I need to get the `PAGE_SIZE` value for the x86 architecture, and I know that the low-level architecture-specific definitions are usually tucked away in the include directories. The kernel source tree is fairly well organized, so it's a good bet to start in `arch/x86/include/asm/`. Within that `asm` directory, the `page_types.h` file is the most likely candidate for definitions related to memory page sizes and types. I'll search there first. It's a fairly standard location. Let's dig in.
|
| 21/2 |
2026/05/20 22:34 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:arch/x86/include/asm/page_types.h IncludeLines:true Name:PAGE_SIZE]
Results: map[SourceCode: SourceFile:]
|
| 22/2 |
2026/05/20 22:34 |
llm |
debugger |
0m
Model:
Tokens:
input: 49565
output: 19
thoughts: 18
Thoughts: Okay, here's my summarized thought process, presented as if I were thinking it:
**Finding That PAGE_SIZE Definition**
Alright, I need to pinpoint where `PAGE_SIZE` is defined in this codebase. No need to overcomplicate things with some overly elaborate search. Let's just reach for `grepper`. It's quick, efficient, and typically does the job. It should be able to dig right to the definition I'm looking for. Let's get to it.
|
| 23/2 |
2026/05/20 22:34 |
tool |
grepper |
0m
Args: map[Expression:#define PAGE_SIZE]
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
--
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h-16-#define PAGE_SHIFT_1GB 30
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h:17:#define PAGE_SIZE_4KB _BITUL(PAGE_SHIFT_4KB)
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h:18:#define PAGE_SIZE_64KB _BITUL(PAGE_SHIFT_64KB)
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h:19:#define PAGE_SIZE_2MB _BITUL(PAGE_SHIFT_2MB)
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h:20:#define PAGE_SIZE_16MB _BITUL(PAGE_SHIFT_16MB)
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h:21:#define PAGE_SIZE_64MB _BITUL(PAGE_SHIFT_64MB)
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h:22:#define PAGE_SIZE_1GB _BITUL(PAGE_SHIFT_1GB)
drivers/accel/habanalabs/include/hw_ip/mmu/mmu_general.h-23-
--
drivers/infiniband/hw/ocrdma/ocrdma_sli.h=283=struct ocrdma_mqe {
--
drivers/infiniband/hw/ocrdma/ocrdma_sli.h-299-#define PAGE_SHIFT_4K 12
drivers/infiniband/hw/ocrdma/ocrdma_sli.h:300:#define PAGE_SIZE_4K (1 << PAGE_SHIFT_4K)
drivers/infiniband/hw/ocrdma/ocrdma_sli.h-301-
--
drivers/net/ethernet/emulex/benet/be.h=778=extern const struct ethtool_ops be_ethtool_ops;
--
drivers/net/ethernet/emulex/benet/be.h-816-#define PAGE_SHIFT_4K 12
drivers/net/ethernet/emulex/benet/be.h:817:#define PAGE_SIZE_4K (1 << PAGE_SHIFT_4K)
drivers/net/ethernet/emulex/benet/be.h-818-
--
drivers/scsi/be2iscsi/be.h=111=struct be_ctrl_info {
--
drivers/scsi/be2iscsi/be.h-146-#define PAGE_SHIFT_4K 12
drivers/scsi/be2iscsi/be.h:147:#define PAGE_SIZE_4K (1 << PAGE_SHIFT_4K)
drivers/scsi/be2iscsi/be.h-148-
--
drivers/staging/rtl8723bs/include/hal_data.h=67=enum {
--
drivers/staging/rtl8723bs/include/hal_data.h-72-
drivers/staging/rtl8723bs/include/hal_data.h:73:#define PAGE_SIZE_128 128
drivers/staging/rtl8723bs/include/hal_data.h:74:#define PAGE_SIZE_256 256
drivers/staging/rtl8723bs/include/hal_data.h:75:#define PAGE_SIZE_512 512
drivers/staging/rtl8723bs/include/hal_data.h-76-
--
drivers/staging/rtl8723bs/include/rtl8723b_hal.h=39=struct rt_firmware_hdr {
--
drivers/staging/rtl8723bs/include/rtl8723b_hal.h-76-/* TX 32K, RX 16K, Page size 128B for TX, 8B for RX */
drivers/staging/rtl8723bs/include/rtl8723b_hal.h:77:#define PAGE_SIZE_TX_8723B 128
drivers/staging/rtl8723bs/include/rtl8723b_hal.h:78:#define PAGE_SIZE_RX_8723B 8
drivers/staging/rtl8723bs/include/rtl8723b_hal.h-79-
--
include/vdso/page.h-14-
include/vdso/page.h:15:#define PAGE_SIZE (_AC(1,UL) << CONFIG_PAGE_SHIFT)
include/vdso/page.h-16-
--
lib/vdso/getrandom.c-22-#undef PAGE_MASK
lib/vdso/getrandom.c:23:#define PAGE_SIZE (1UL << CONFIG_PAGE_SHIFT)
lib/vdso/getrandom.c-24-#define PAGE_MASK (~(PAGE_SIZE - 1))
--
sound/soc/amd/acp/amd.h-50-#define ACP_SRAM_HS_CP_PTE_OFFSET 0x600
sound/soc/amd/acp/amd.h:51:#define PAGE_SIZE_4K_ENABLE 0x2
sound/soc/amd/acp/amd.h-52-
--
sound/soc/amd/ps/acp63.h-44-#define ACP_SRAM_PTE_OFFSET 0x03800000
sound/soc/amd/ps/acp63.h:45:#define PAGE_SIZE_4K_ENABLE 2
sound/soc/amd/ps/acp63.h-46-#define PDM_PTE_OFFSET 0
--
sound/soc/amd/raven/acp3x.h-41-#define ACP_SRAM_BT_CP_PTE_OFFSET 0x300
sound/soc/amd/raven/acp3x.h:42:#define PAGE_SIZE_4K_ENABLE 0x2
sound/soc/amd/raven/acp3x.h-43-#define I2S_SP_TX_MEM_WINDOW_START 0x4000000
--
sound/soc/amd/renoir/rn_acp3x.h-47-#define ACP_SRAM_PTE_OFFSET 0x02050000
sound/soc/amd/renoir/rn_acp3x.h:48:#define PAGE_SIZE_4K_ENABLE 0x2
sound/soc/amd/renoir/rn_acp3x.h-49-#define MEM_WINDOW_START 0x4000000
--
sound/soc/amd/vangogh/acp5x.h-48-#define ACP_SRAM_HS_CP_PTE_OFFSET 0x300
sound/soc/amd/vangogh/acp5x.h:49:#define PAGE_SIZE_4K_ENABLE 0x2
sound/soc/amd/vangogh/acp5x.h-50-#define I2S_SP_TX_MEM_WINDOW_START 0x4000000
--
sound/soc/amd/yc/acp6x.h-42-#define ACP_SRAM_PTE_OFFSET 0x03800000
sound/soc/amd/yc/acp6x.h:43:#define PAGE_SIZE_4K_ENABLE 2
sound/soc/amd/yc/acp6x.h-44-#define PDM_PTE_OFFSET 0
--
sound/soc/sof/amd/acp.h-47-#define ACP70_SRAM_PTE_OFFSET ACP6X_SRAM_PTE_OFFSET
sound/soc/sof/amd/acp.h:48:#define PAGE_SIZE_4K_ENABLE 0x2
sound/soc/sof/amd/acp.h-49-#define ACP_PAGE_SIZE 0x1000
--
tools/bootconfig/main.c=115=static void xbc_show_list(void)
--
tools/bootconfig/main.c-136-
tools/bootconfig/main.c:137:#define PAGE_SIZE 4096
tools/bootconfig/main.c-138-
--
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/include/linux/mm.h-11-#define PAGE_MASK (~(PAGE_SIZE - 1))
--
tools/perf/util/event.h=411=extern unsigned int proc_map_timeout;
tools/perf/util/event.h-412-
tools/perf/util/event.h:413:#define PAGE_SIZE_NAME_LEN 32
tools/perf/util/event.h-414-char *get_page_size_name(u64 size, char *str);
--
tools/sched_ext/include/scx/bpf_arena_common.bpf.h-5-#ifndef PAGE_SIZE
tools/sched_ext/include/scx/bpf_arena_common.bpf.h:6:#define PAGE_SIZE __PAGE_SIZE
tools/sched_ext/include/scx/bpf_arena_common.bpf.h-7-/*
--
tools/testing/scatterlist/linux/mm.h=11=typedef unsigned long dma_addr_t;
--
tools/testing/scatterlist/linux/mm.h-28-
tools/testing/scatterlist/linux/mm.h:29:#define PAGE_SIZE (4096)
tools/testing/scatterlist/linux/mm.h-30-#define PAGE_SHIFT (12)
--
tools/testing/selftests/bpf/bpf_arena_common.h-23-#ifndef PAGE_SIZE
tools/testing/selftests/bpf/bpf_arena_common.h:24:#define PAGE_SIZE __PAGE_SIZE
tools/testing/selftests/bpf/bpf_arena_common.h-25-/*
--
tools/testing/selftests/bpf/prog_tests/arena_htab.c-8-#include <unistd.h>
tools/testing/selftests/bpf/prog_tests/arena_htab.c:9:#define PAGE_SIZE getpagesize()
tools/testing/selftests/bpf/prog_tests/arena_htab.c-10-#endif
--
tools/testing/selftests/bpf/prog_tests/arena_list.c-8-#include <unistd.h>
tools/testing/selftests/bpf/prog_tests/arena_list.c:9:#define PAGE_SIZE getpagesize()
tools/testing/selftests/bpf/prog_tests/arena_list.c-10-#endif
--
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c-36-
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c:37:#define PAGE_SIZE 4096
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c-38-#define MB(x) (x << 20)
--
tools/testing/selftests/bpf/prog_tests/dynptr.c=16=static struct {
--
tools/testing/selftests/bpf/prog_tests/dynptr.c-55-
tools/testing/selftests/bpf/prog_tests/dynptr.c:56:#define PAGE_SIZE_64K 65536
tools/testing/selftests/bpf/prog_tests/dynptr.c-57-
--
tools/testing/selftests/bpf/prog_tests/sk_bypass_prot_mem.c-9-#include <unistd.h>
tools/testing/selftests/bpf/prog_tests/sk_bypass_prot_mem.c:10:#define PAGE_SIZE getpagesize()
tools/testing/selftests/bpf/prog_tests/sk_bypass_prot_mem.c-11-#endif
--
tools/testing/selftests/bpf/prog_tests/sockopt.c=7=static bool verbose;
--
tools/testing/selftests/bpf/prog_tests/sockopt.c-9-#ifndef PAGE_SIZE
tools/testing/selftests/bpf/prog_tests/sockopt.c:10:#define PAGE_SIZE 4096
tools/testing/selftests/bpf/prog_tests/sockopt.c-11-#endif
--
tools/testing/selftests/bpf/prog_tests/xdp_do_redirect.c=42=static int attach_tc_prog(struct bpf_tc_hook *hook, int fd)
--
tools/testing/selftests/bpf/prog_tests/xdp_do_redirect.c-69-
tools/testing/selftests/bpf/prog_tests/xdp_do_redirect.c:70:#define PAGE_SIZE_4K 4096
tools/testing/selftests/bpf/prog_tests/xdp_do_redirect.c:71:#define PAGE_SIZE_64K 65536
tools/testing/selftests/bpf/prog_tests/xdp_do_redirect.c-72-
--
tools/testing/selftests/bpf/progs/dynptr_success.c-11-
tools/testing/selftests/bpf/progs/dynptr_success.c:12:#define PAGE_SIZE_64K 65536
tools/testing/selftests/bpf/progs/dynptr_success.c-13-
--
tools/testing/selftests/bpf/progs/test_sockmap_change_tail.c-6-#ifndef PAGE_SIZE
tools/testing/selftests/bpf/progs/test_sockmap_change_tail.c:7:#define PAGE_SIZE __PAGE_SIZE
tools/testing/selftests/bpf/progs/test_sockmap_change_tail.c-8-#endif
--
tools/testing/selftests/bpf/progs/test_tc_change_tail.c-5-#ifndef PAGE_SIZE
tools/testing/selftests/bpf/progs/test_tc_change_tail.c:6:#define PAGE_SIZE __PAGE_SIZE
tools/testing/selftests/bpf/progs/test_tc_change_tail.c-7-#endif
--
tools/testing/selftests/bpf/uptr_test_common.h-7-#define MAGIC_VALUE 0xabcd1234
tools/testing/selftests/bpf/uptr_test_common.h:8:#define PAGE_SIZE 4096
tools/testing/selftests/bpf/uptr_test_common.h-9-
--
tools/testing/selftests/cgroup/lib/include/cgroup_util.h-5-#ifndef PAGE_SIZE
tools/testing/selftests/cgroup/lib/include/cgroup_util.h:6:#define PAGE_SIZE 4096
tools/testing/selftests/cgroup/lib/include/cgroup_util.h-7-#endif
--
tools/testing/selftests/coredump/coredump_test.h-13-#ifndef PAGE_SIZE
tools/testing/selftests/coredump/coredump_test.h:14:#define PAGE_SIZE 4096
tools/testing/selftests/coredump/coredump_test.h-15-#endif
--
tools/testing/selftests/coredump/coredump_test_helpers.c=29=struct _fixture_coredump_data {
--
tools/testing/selftests/coredump/coredump_test_helpers.c-35-#ifndef PAGE_SIZE
tools/testing/selftests/coredump/coredump_test_helpers.c:36:#define PAGE_SIZE 4096
tools/testing/selftests/coredump/coredump_test_helpers.c-37-#endif
--
tools/testing/selftests/coredump/stackdump_test.c-31-#ifndef PAGE_SIZE
tools/testing/selftests/coredump/stackdump_test.c:32:#define PAGE_SIZE 4096
tools/testing/selftests/coredump/stackdump_test.c-33-#endif
--
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/s390/processor.h-27-#define PAGE_MASK (~(PAGE_SIZE - 1))
--
tools/testing/selftests/kvm/include/x86/processor.h=363=static inline unsigned int x86_model(unsigned int eax)
--
tools/testing/selftests/kvm/include/x86/processor.h-370-#define PAGE_SHIFT 12
tools/testing/selftests/kvm/include/x86/processor.h:371:#define PAGE_SIZE (1ULL << PAGE_SHIFT)
tools/testing/selftests/kvm/include/x86/processor.h-372-#define PAGE_MASK (~(PAGE_SIZE-1) & PHYSICAL_PAGE_MASK)
--
tools/testing/selftests/mm/pkey-arm64.h-36-#define PKEY_BITS_PER_PKEY 4
tools/testing/selftests/mm/pkey-arm64.h:37:#define PAGE_SIZE sysconf(_SC_PAGESIZE)
tools/testing/selftests/mm/pkey-arm64.h-38-#undef HPAGE_SIZE
--
tools/testing/selftests/mm/pkey-powerpc.h-36-#define HPAGE_SIZE (1UL << 24)
tools/testing/selftests/mm/pkey-powerpc.h:37:#define PAGE_SIZE sysconf(_SC_PAGESIZE)
tools/testing/selftests/mm/pkey-powerpc.h-38-
--
tools/testing/selftests/mm/pkey-x86.h-33-#define HPAGE_SIZE (1UL<<21)
tools/testing/selftests/mm/pkey-x86.h:34:#define PAGE_SIZE 4096
tools/testing/selftests/mm/pkey-x86.h-35-#define MB (1<<20)
--
tools/testing/selftests/powerpc/benchmarks/mmap_bench.c-16-#define MEMSIZE (1UL << 27)
tools/testing/selftests/powerpc/benchmarks/mmap_bench.c:17:#define PAGE_SIZE (1UL << 16)
tools/testing/selftests/powerpc/benchmarks/mmap_bench.c-18-#define CHUNK_COUNT (MEMSIZE/PAGE_SIZE)
--
tools/testing/selftests/powerpc/pmu/sampling_tests/misc.c-18-
tools/testing/selftests/powerpc/pmu/sampling_tests/misc.c:19:#define PAGE_SIZE sysconf(_SC_PAGESIZE)
tools/testing/selftests/powerpc/pmu/sampling_tests/misc.c-20-
--
tools/testing/selftests/powerpc/syscalls/rtas_filter.c-33-#define BLOCK_SIZE 4096
tools/testing/selftests/powerpc/syscalls/rtas_filter.c:34:#define PAGE_SIZE 4096
tools/testing/selftests/powerpc/syscalls/rtas_filter.c-35-#define MAX_PAGES 64
--
tools/testing/selftests/proc/proc-pid-vm.c=102=struct elf64_phdr {
--
tools/testing/selftests/proc/proc-pid-vm.c-113-#ifdef __x86_64__
tools/testing/selftests/proc/proc-pid-vm.c:114:#define PAGE_SIZE 4096
tools/testing/selftests/proc/proc-pid-vm.c-115-#define VADDR (1UL << 32)
--
tools/testing/selftests/ptrace/peeksiginfo.c=26=static int sys_ptrace(int request, pid_t pid, void *addr, void *data)
--
tools/testing/selftests/ptrace/peeksiginfo.c-35-#ifndef PAGE_SIZE
tools/testing/selftests/ptrace/peeksiginfo.c:36:#define PAGE_SIZE sysconf(_SC_PAGESIZE)
tools/testing/selftests/ptrace/peeksiginfo.c-37-#endif
--
tools/testing/selftests/resctrl/fill_buf.c-21-#define CL_SIZE (64)
tools/testing/selftests/resctrl/fill_buf.c:22:#define PAGE_SIZE (4 * 1024)
tools/testing/selftests/resctrl/fill_buf.c-23-#define MB (1024 * 1024)
--
tools/testing/selftests/sgx/defines.h-10-
tools/testing/selftests/sgx/defines.h:11:#define PAGE_SIZE 4096
tools/testing/selftests/sgx/defines.h-12-#define PAGE_MASK (~(PAGE_SIZE - 1))
--
tools/testing/selftests/x86/lam.c-61-
tools/testing/selftests/x86/lam.c:62:#define PAGE_SIZE (4 << 10)
tools/testing/selftests/x86/lam.c-63-
--
tools/testing/selftests/x86/nx_stack.c-37-
tools/testing/selftests/x86/nx_stack.c:38:#define PAGE_SIZE 4096
tools/testing/selftests/x86/nx_stack.c-39-
--
tools/testing/selftests/x86/test_mremap_vdso.c-24-
tools/testing/selftests/x86/test_mremap_vdso.c:25:#define PAGE_SIZE 4096
tools/testing/selftests/x86/test_mremap_vdso.c-26-
--
tools/testing/selftests/x86/test_shadow_stack.c-60-#define SS_SIZE 0x200000
tools/testing/selftests/x86/test_shadow_stack.c:61:#define PAGE_SIZE 0x1000
tools/testing/selftests/x86/test_shadow_stack.c-62-
--
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-1742-#define MAX_PAGE_ORDER 10 /* usually */
tools/testing/vsock/vsock_test.c:1743:#define PAGE_SIZE 4096
tools/testing/vsock/vsock_test.c-1744-
--
tools/testing/vsock/vsock_test_zerocopy.c-27-#ifndef PAGE_SIZE
tools/testing/vsock/vsock_test_zerocopy.c:28:#define PAGE_SIZE 4096
tools/testing/vsock/vsock_test_zerocopy.c-29-#endif
--
tools/testing/vsock/vsock_uring_test.c-23-#ifndef PAGE_SIZE
tools/testing/vsock/vsock_uring_test.c:24:#define PAGE_SIZE 4096
tools/testing/vsock/vsock_uring_test.c-25-#endif
--
tools/virtio/linux/kernel.h-26-
tools/virtio/linux/kernel.h:27:#define PAGE_SIZE getpagesize()
tools/virtio/linux/kernel.h-28-#define PAGE_MASK (~(PAGE_SIZE-1))
--
tools/virtio/virtio-trace/trace-agent.c-16-
tools/virtio/virtio-trace/trace-agent.c:17:#define PAGE_SIZE (sysconf(_SC_PAGE_SIZE))
tools/virtio/virtio-trace/trace-agent.c-18-#define PIPE_DEF_BUFS 16
]
|
| 24/2 |
2026/05/20 22:34 |
llm |
debugger |
1m
Model:
Tokens:
input: 56752
output: 48
thoughts: 10769
Thoughts: **Analysis of Potential Shift-Out-of-Bounds in SCSI Scatter-Gather List Processing**
Alright, let's break this down. It seems we have a potential vulnerability in the SCSI scatter-gather list processing within the `sg` driver. The issue stems from an unhandled edge case when the `scatter_elem_sz` module parameter is set to either zero or a very large value (or when a negative value is passed). This vulnerability could lead to a shift-out-of-bounds error, triggering UBSAN.
Here's the path: the bug originates when userspace writes "0" (or a negative number, which is effectively "0" after `kstrtoint` processing) to the `/sys/module/sg/parameters/scatter_elem_sz` sysfs entry. This sysfs write calls the function `param_set_int`. After the value is set, it triggers code execution that leads to the following:
1. A sysfs write such as `echo "0" > /sys/module/sg/parameters/scatter_elem_sz`.
2. Later, a user opens a device using the `sg_open` function. This function calls `sg_add_sfp`, which calls `sg_build_reserve`.
3. `sg_build_reserve` calls `sg_build_indirect`, where the core vulnerability lies.
Let's zoom in on `sg_build_indirect`:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 // Missing: num = PAGE_SIZE;
1901 scatter_elem_sz = PAGE_SIZE;
1902 scatter_elem_sz_prev = PAGE_SIZE;
1903 } else
1904 scatter_elem_sz_prev = num;
1905 }
1906
1907 order = get_order(num);
```
The problem is the missing `num = PAGE_SIZE;` assignment within the `if (num < PAGE_SIZE)` block. If `scatter_elem_sz` is set to 0, `num` is 0. The code enters the `if` block, sets `scatter_elem_sz` and `scatter_elem_sz_prev` to `PAGE_SIZE`, but *doesn't* update `num` to `PAGE_SIZE`. Then `order = get_order(0)` is called. The `get_order` function expects a size, subtracts 1, right-shifts by `PAGE_SHIFT` (12), and then calculates the most significant bit. It calculates this with the internal function, `fls64()`. When the size is zero, this translates to `0xffffffffffffffffUL`. After shifting this value, the result is `0x000fffffffffffffUL`. The `fls64` then returns `52` (since the 52nd bit from the *left* is the most significant bit that is set in `0x000fffffffffffffUL`). So, in this case, `order = 52`.
The line:
```c
1908 ret_sz = 1 << (PAGE_SHIFT + order);
```
becomes `ret_sz = 1 << (12 + 52) = 1 << 64;` which leads to the crash, due to the shift count being larger than the bit width of an `int`, triggering undefined behavior. The compiler, with UBSAN enabled, correctly flags this as a shift-out-of-bounds error.
Moreover, if we write a large positive value (e.g., `0x7fffffff`) to the sysfs entry, we get `order = 19`. The offending line becomes `ret_sz = 1 << (12 + 19) = 1 << 31;` which also constitutes undefined behavior, as it shifts into the sign bit of a signed integer, even though it doesn't cause a crash with UBSAN, and can still create a bug. This, again, because 1 is a signed 32-bit `int`, while `PAGE_SHIFT + order` (31) is equivalent to shifting 1 into the sign bit. Although this does not immediately cause a crash (if `MAX_ORDER` is big enough to allow the allocation), the resulting negative value of ret_sz can lead to unexpected behavior later on
|
| 25/2 |
2026/05/20 22:36 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/asm-generic/bitops/fls64.h IncludeLines:true Name:fls64]
Results: map[SourceCode: 397: static __always_inline __attribute_const__ int fls64(__u64 x)
398: {
399: int bitpos = -1;
400:
401: if (__builtin_constant_p(x))
402: return x ? 64 - __builtin_clzll(x) : 0;
403: /*
404: * AMD64 says BSRQ won't clobber the dest reg if x==0; Intel64 says the
405: * dest reg is undefined if x==0, but their CPU architect says its
406: * value is written to set it to the same as before.
407: */
408: asm("bsrq %1,%q0"
409: : "+r" (bitpos)
410: : ASM_INPUT_RM (x));
411: return bitpos + 1;
412: }
SourceFile:arch/x86/include/asm/bitops.h]
|
| 26/2 |
2026/05/20 22:36 |
llm |
debugger |
0m
Model:
Tokens:
input: 68897
output: 1227
thoughts: 926
Thoughts: **Root Cause Analysis and Fix for Scatter Element Size Issue**
Okay, let's break this down. It seems the core problem lies in how the `scatter_elem_sz` parameter is handled in the `sg` driver, specifically when a value is written to it via sysfs. I've tracked down the issue to a shift-out-of-bounds error that can be triggered when a user writes either zero or a negative value to `/sys/module/sg/parameters/scatter_elem_sz`.
Here's the detailed breakdown:
First, let's see where this all starts, a user writes a value to `/sys/module/sg/parameters/scatter_elem_sz`, it leads to a call into `sg_open`, which eventually calls `sg_build_reserve` and then `sg_build_indirect`. Within `sg_build_indirect`, the following snippet is key:
```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
```
So, let's say the user writes a value of 0. Then, `num` is assigned `0`. The `if (num < PAGE_SIZE)` condition is met. `scatter_elem_sz` and `scatter_elem_sz_prev` are updated to `PAGE_SIZE`. *However*, the local variable `num` is **not** updated. The code then calls `get_order(num)`. Since `num` is still 0, `get_order(0)` evaluates to `52` (the code likely calculates the position of the highest set bit, which is effectively bit 52 for 0).
Then, this line causes the crash:
```c
ret_sz = 1 << (PAGE_SHIFT + order);
```
Because `PAGE_SHIFT` is 12 and `order` is 52, the calculation becomes `1 << (12 + 52)`, which is `1 << 64`. This is where the UBSAN warning (and crash) occurs. The issue is that `1` is a 32-bit signed integer. Shifting a 32-bit integer by 64 bits is undefined behavior.
Now, let's consider another edge case. If `num` is negative, let's say `-1`. This then is clamped to `0x000fffffffffffffUL` after the bitwise shift. This scenario leads to the same outcome, `get_order` returns 52, and the shift by 64 bits causes the crash.
Also, just for completeness, note that if the user writes a large, positive value (e.g., `0x7fffffff`), `order` becomes `19`, and the problematic line evaluates to `1 << (12 + 19)` or `1 << 31`, which is undefined behavior for a signed 32-bit integer (potentially triggering a similar issue).
The suggested fix is spot-on:
```c
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1897,6 +1897,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1905,7 +1906,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = 1UL << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
```
This diff fixes *both* issues. First, `num` is correctly updated to `
|
| 27/1 |
2026/05/20 22:36 |
action |
kernel-scratch-checkouter |
0m
Results: map[KernelScratchSrc:/app/workdir/cache/tmp/tmp2427695448]
|
| 28/1 |
2026/05/20 22:36 |
loop |
|
40m
|
| 29/2 |
2026/05/20 22:36 |
iteration |
0 |
40m
|
| 30/3 |
2026/05/20 22:36 |
agent |
patch-generator |
5m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with creating a fix for a kernel bug.
You will be given a crash report, and an initial explanation of the root cause done by another
kernel expert.
Use the codeeditor tool to do code edits.
Note: you will not see your changes when looking at the code using codesearch tools.
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/d5a02ed91a4f019017141f71e695c75b27c3612e/drivers/scsi/sg.c:1888:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 0 UID: 0 PID: 6185 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+0x385/0x410 lib/ubsan.c:494
sg_build_indirect+0x549/0x850 drivers/scsi/sg.c:1888
sg_build_reserve drivers/scsi/sg.c:1998 [inline]
sg_add_sfp drivers/scsi/sg.c:2178 [inline]
sg_open+0x122a/0x1a40 drivers/scsi/sg.c:349
chrdev_open+0x4cd/0x5e0 fs/char_dev.c:411
do_dentry_open+0x785/0x14e0 fs/open.c:947
vfs_open+0x3b/0x340 fs/open.c:1079
do_open fs/namei.c:4699 [inline]
path_openat+0x2e08/0x3860 fs/namei.c:4858
do_file_open+0x23e/0x4a0 fs/namei.c:4887
do_sys_openat2+0x113/0x200 fs/open.c:1364
do_sys_open fs/open.c:1370 [inline]
__do_sys_openat fs/open.c:1386 [inline]
__se_sys_openat fs/open.c:1381 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1381
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f72e679ce59
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:00007f72e75e3028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007f72e6a15fa0 RCX: 00007f72e679ce59
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007f72e6832d6f R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f72e6a16038 R14: 00007f72e6a15fa0 R15: 00007ffe5f34f718
</TASK>
---[ end trace ]---
The explanation of the root cause of the bug is:
An excellent catch by syzkaller. The root cause of this crash is a missing local variable update after clamping a module parameter, combined with an unsafe bitwise shift on a signed 32-bit integer.
### Root Cause Analysis
The `sg` driver exposes the `scatter_elem_sz` module parameter, which can be modified at runtime by a privileged user via `/sys/module/sg/parameters/scatter_elem_sz`.
1. **The Sysfs Write:**
The syzkaller reproducer writes the string `"0"` to this sysfs file. The kernel parses this using `kstrtoint` and sets the global variable `scatter_elem_sz` to `0`. (Writing a negative value like `"-1"` would have the same effect).
2. **The Trigger:**
The reproducer then opens `/dev/sg0`. This invokes `sg_open()`, which calls `sg_add_sfp()`, and subsequently `sg_build_reserve()` and `sg_build_indirect()`.
3. **The Missing Variable Update:**
In `sg_build_indirect()`, the code reads `scatter_elem_sz` into a local variable `num` and attempts to clamp it to a minimum of `PAGE_SIZE`:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 scatter_elem_sz = PAGE_SIZE;
1901 scatter_elem_sz_prev = PAGE_SIZE;
1902 } else
1903 scatter_elem_sz_prev = num;
1904 }
1905
1906 order = get_order(num);
```
Notice that while the global `scatter_elem_sz` and `scatter_elem_sz_prev` are correctly clamped to `PAGE_SIZE`, **the local variable `num` is never updated**. Thus, `num` remains `0` (or negative).
4. **The `get_order()` Underflow:**
The code then calls `order = get_order(num);` where `num` is `0`.
Inside `get_order(unsigned long size)`, the size is decremented (`size--`), which underflows `0` to `0xffffffffffffffffUL`. It is then shifted right by `PAGE_SHIFT` (12), resulting in `0x000fffffffffffffUL`. The `fls64()` of this value is `52`. Thus, `get_order(0)` returns `52`.
5. **The UBSAN Shift-Out-Of-Bounds:**
Immediately after, the code calculates the return size:
```c
1907 retry:
1908 ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT` being `12` and `order` being `52`, the expression evaluates to `1 << 64`. Since the literal `1` is a signed 32-bit `int`, shifting it by 64 is undefined behavior and triggers the exact UBSAN warning seen in the crash: `shift exponent 64 is too large for 32-bit type 'int'`.
*(Note: There is also a secondary bug here. If a user intentionally writes a very large valid value like `0x7fffffff` to `scatter_elem_sz`, `order` becomes `19`. The expression `1 << (12 + 19)` evaluates to `1 << 31`, which shifts a bit into the sign bit of a signed 32-bit integerโalso undefined behavior in C).*
### Proposed Fix
To fix this, we need to update `num` to `PAGE_SIZE` when clamping, and change the literal `1` to `1UL` to prevent any undefined behavior when `order` is legitimately large.
```c
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1897,6 +1897,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1905,7 +1906,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = 1UL << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
```
Reply: I have applied the fix and also improved upon the initially proposed solution.
### What I did in the patch:
1. **Fixed the missing variable update:** I added `num = PAGE_SIZE;` inside the clamping block in `sg_build_indirect()`. This ensures that `num` is never 0 or negative when passed to `get_order()`. Passing 0 to `get_order()` was the root cause of the bug, as it underflows and returns a very large order (e.g., 52), which then caused the shift-out-of-bounds.
2. **Used a safer and more idiomatic size calculation:** Instead of changing `1` to `1UL` as proposed in the initial explanation, I changed the expression to `PAGE_SIZE << order`.
- The initially proposed fix `1UL << (PAGE_SHIFT + order)` would **still trigger undefined behavior** if `PAGE_SHIFT + order >= 64` (which was exactly the case here: 12 + 52 = 64, and shifting a 64-bit integer by 64 or more is UB in C).
- `PAGE_SIZE << order` shifts by `order` (which is at most 52), so it is strictly well-defined even if `order` was somehow 52.
- More importantly, `PAGE_SIZE << order` is the standard, idiomatic way in the kernel to calculate the byte size of an allocation given its page order.
3. **Applied the pattern consistently across the file:** I searched for other occurrences of the unsafe `1 << (PAGE_SHIFT + order)` pattern in `drivers/scsi/sg.c` and found four other places (`sg_vma_fault`, `sg_mmap`, `sg_read_oxfer`, and `sg_link_reserve`). While those specific places were practically safe because their `page_order` is bounded by `MAX_PAGE_ORDER`, I updated them to use `PAGE_SIZE << order` as well for consistency, robustness, and to prevent any future undefined behavior if the code is refactored.
|
| 31/4 |
2026/05/20 22:36 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 6603
output: 19
thoughts: 236
Thoughts: **Analyzing a Shift-Out-of-Bounds Crash in SCSI Driver**
Okay, so I'm looking at a crash report, and it seems like we have a UBSAN shift-out-of-bounds error specifically around `drivers/scsi/sg.c:1888`, give or take a few lines. That's usually pretty easy to identify, and in this case, the error message clearly points to a shift exponent being too large for an integer type. The message indicates "shift exponent 64 is too large for 32-bit type 'int'".
Digging deeper, the root cause seems to be in how `scatter_elem_sz` is being handled. I see that the value of `scatter_elem_sz` is first read into a variable called `num`. If this `num` is smaller than `PAGE_SIZE`, both `scatter_elem_sz` and a previous value `scatter_elem_sz_prev` get updated to `PAGE_SIZE`. The problem is, `num` itself *isn't* updated, leaving the original, smaller value in place.
That's a textbook problem. Then, later, the code calls `get_order(num)` with this now un-updated `num`, which is either 0 or negative. That's going to cause a problem. `get_order(0)` is returning a large value, something like 52, which is... suspicious, but can happen. Then, the next line calculates `ret_sz = 1 << (PAGE_SHIFT + order)`. So, we're shifting 1 left by a number that's equal to 12 (the PAGE_SHIFT) + 52 (the large order value), which is 64. And that is where the out-of-bounds error is happening, as it shifts 1 too far for a 32-bit int.
Now I need to go examine that section of `drivers/scsi/sg.c` around line 1888 and see how this is being triggered in the real world.
|
| 32/4 |
2026/05/20 22:37 |
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=1591=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1624-
drivers/scsi/sg.c:1625:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1626-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1659=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1660-
drivers/scsi/sg.c:1661:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1662- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1667=init_sg(void)
--
drivers/scsi/sg.c-1670-
drivers/scsi/sg.c:1671: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1672: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1673: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1674- }
--
drivers/scsi/sg.c=1855=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1876-
drivers/scsi/sg.c:1877: num = scatter_elem_sz;
drivers/scsi/sg.c:1878: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1879- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1880: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1881: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1882- } else
drivers/scsi/sg.c:1883: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1884- }
--
drivers/scsi/sg.c-1892-
drivers/scsi/sg.c:1893: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1894: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1895-
--
drivers/scsi/sg.c-1899-
drivers/scsi/sg.c:1900: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1901: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1902: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1903: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1904- }
]
|
| 33/4 |
2026/05/20 22:37 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 8328
output: 42
thoughts: 22
Thoughts: Here's my take on the thought process:
**Diving into the SCSI Subsystem: Investigating sg_build_indirect**
Alright, time to dig into this SCSI issue. I'm going to start by getting my bearings and heading straight for the `sg_build_indirect` function. That's in the `drivers/scsi/sg.c` file, right? It's where I'd expect to find the low-level stuff for scatter-gather operations, which is always a good place to start when chasing down SCSI driver behavior. I'm thinking this likely deals with constructing the indirect lists for command execution, but I need to confirm and get a closer look at its specific implementation to see how it might tie into the problem at hand.
|
| 34/4 |
2026/05/20 22:37 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c IncludeLines:true Name:sg_build_indirect]
Results: map[SourceCode:1854: static int
1855: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1856: {
1857: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1858: int sg_tablesize = sfp->parentdp->sg_tablesize;
1859: int blk_size = buff_size, order;
1860: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1861:
1862: if (blk_size < 0)
1863: return -EFAULT;
1864: if (0 == blk_size)
1865: ++blk_size; /* don't know why */
1866: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1867: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1868: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1869: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1870: buff_size, blk_size));
1871:
1872: /* N.B. ret_sz carried into this block ... */
1873: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1874: if (mx_sc_elems < 0)
1875: return mx_sc_elems; /* most likely -ENOMEM */
1876:
1877: num = scatter_elem_sz;
1878: if (unlikely(num != scatter_elem_sz_prev)) {
1879: if (num < PAGE_SIZE) {
1880: scatter_elem_sz = PAGE_SIZE;
1881: scatter_elem_sz_prev = PAGE_SIZE;
1882: } else
1883: scatter_elem_sz_prev = num;
1884: }
1885:
1886: order = get_order(num);
1887: retry:
1888: ret_sz = 1 << (PAGE_SHIFT + order);
1889:
1890: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1891: k++, rem_sz -= ret_sz) {
1892:
1893: num = (rem_sz > scatter_elem_sz_prev) ?
1894: scatter_elem_sz_prev : rem_sz;
1895:
1896: schp->pages[k] = alloc_pages(gfp_mask, order);
1897: if (!schp->pages[k])
1898: goto out;
1899:
1900: if (num == scatter_elem_sz_prev) {
1901: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1902: scatter_elem_sz = ret_sz;
1903: scatter_elem_sz_prev = ret_sz;
1904: }
1905: }
1906:
1907: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1908: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1909: k, num, ret_sz));
1910: } /* end of for loop */
1911:
1912: schp->page_order = order;
1913: schp->k_use_sg = k;
1914: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1915: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1916: k, rem_sz));
1917:
1918: schp->bufflen = blk_size;
1919: if (rem_sz > 0) /* must have failed */
1920: return -ENOMEM;
1921: return 0;
1922: out:
1923: for (i = 0; i < k; i++)
1924: __free_pages(schp->pages[i], order);
1925:
1926: if (--order >= 0)
1927: goto retry;
1928:
1929: return -ENOMEM;
1930: }
SourceFile:drivers/scsi/sg.c]
|
| 35/4 |
2026/05/20 22:37 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 9892
output: 153
thoughts: 2347
Thoughts: **Analysis of Potential Integer Overflow in SCSI Driver Code**
Okay, so I've been looking at this potential integer overflow in the SCSI driver code, specifically within `sg_build_indirect`. The problem seems to stem from how the `ret_sz` variable, which represents the size of the scatter/gather element, is calculated. It's currently done using a left bit shift: `ret_sz = 1 << (PAGE_SHIFT + order)`.
My initial thought was that if `order` is large enough, and `PAGE_SHIFT` is also large enough, then `PAGE_SHIFT + order` could result in a value that, when shifted left, would overflow the `ret_sz` variable (an `int`). In the worst case this could make `ret_sz` negative, which would cause an issue with the later logic in the loop, where it is subtracted from a `rem_sz`, potentially leading to an infinite loop, or worse.
I started digging deeper by tracking how `scatter_elem_sz` gets its size and its use with `get_order`. I've found that `scatter_elem_sz` gets its value from `num`, that in turn, can be controlled by userspace.
It's using `alloc_pages`, which is fine, as it's passed the `order` which is bounded by `MAX_PAGE_ORDER`. So, while the order *could* be large if `scatter_elem_sz` is large (up to 0x7fffffff), `alloc_pages` would likely fail for large orders, and the code includes a retry mechanism, decrementing the `order` until `alloc_pages` succeeds or until a maximum number of retries is reached.
The UBSAN warning highlights undefined behavior if `PAGE_SHIFT + order` >= 32. This means a 32-bit `int`, with a shift of 31 is undefined, for a signed integer.
The question then became, how do we fix it? The key insight is that `alloc_pages` *will* fail for excessively large `order` values, so the *bug* may not be exploitable, but the undefined behavior is still present. To fix this, I think using an unsigned literal would make the expression safe.
Furthermore, I considered whether to change `ret_sz` to `unsigned int` or `size_t` but determined that it's consistent within the code as `rem_sz`, `buff_size`, and `blk_size` are all also `int`'s. So, changing `ret_sz` would mean changing the signature of the functions, and I'd prefer a simpler fix.
Then it hit me! Rather than `1 << (PAGE_SHIFT + order)`, why not just use `PAGE_SIZE << order`? This is *much* cleaner and does the exact same calculation, but without the risk of undefined behavior. `PAGE_SIZE` is already defined as `1UL << PAGE_SHIFT`!
So, the optimal fix is to replace `ret_sz = 1 << (PAGE_SHIFT + order)` with `ret_sz = PAGE_SIZE << order`. This is the clearest and safest approach.
|
| 36/4 |
2026/05/20 22:37 |
tool |
codeeditor |
0m
Args: map[CurrentCode: 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; NewCode: order = get_order(num);
retry:
ret_sz = PAGE_SIZE << order;
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems; SourceFile:drivers/scsi/sg.c]
Results:
|
| 37/4 |
2026/05/20 22:37 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 13082
output: 209
thoughts: 13
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Addressing the `num` Update Issue**
Right, let's circle back to that nagging issue with `num`. It looks like I was overlooking a crucial update mechanism somewhere. I need to be more precise in tracking how that variable is intended to be modified in this context. It is clearly not behaving as it should. There are likely several potential locations where this can happen, and I need to identify which is the offending code to then address it properly. I will start by thoroughly inspecting the relevant code sections that interact with `num`. I will probably begin by tracing the call stack, but it will be a deep dive. I will need to consider any loops, conditional statements, and function calls that might affect the value of `num`, and carefully evaluate the logic within each. Ensuring the correctness of this update is paramount for the overall functionality, so this deserves my full attention. This will be a meticulous process, but essential to get the code to perform correctly.
|
| 38/4 |
2026/05/20 22:38 |
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;
} NewCode: 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;
} SourceFile:drivers/scsi/sg.c]
Results:
|
| 39/4 |
2026/05/20 22:38 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 13534
output: 23
thoughts: 8
Thoughts: Okay, let's dive into this. I need to get a clear picture of the changes, so the first thing I'm going to do is examine that patch diff. I need to understand what's been modified and how, so I can assess its impact quickly and effectively. Knowing what was changed is the jumping off point for all further analysis.
|
| 40/4 |
2026/05/20 22:38 |
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 74cd4e8a6..0dcd6632e 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1855,76 +1855,77 @@ 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) {
+ 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);
+ ret_sz = PAGE_SIZE << 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;
}
]
|
| 41/4 |
2026/05/20 22:38 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 14741
output: 19
thoughts: 931
Thoughts: **Analyzing Potential Integer Overflow and Infinite Loops in Memory Allocation**
Okay, let's break this down step-by-step. My initial concern was centered around potential integer overflows when calculating memory block sizes. Specifically, I was worried about the expression `PAGE_SIZE << order`. Since `PAGE_SIZE` is an `unsigned long`, and if `order` is a large value like 52 (which happens with `num = 0`), I would get something like `1UL << 64`, which is undefined behavior for a 64-bit `unsigned long`. But wait a minute, the code uses `get_order(0)` if `num = 0`. This sets order to 52.
I realized the shift amount is 52. So `PAGE_SIZE << 52` should be a perfectly well-defined C operation. The bits at the 12th position will just shift out resulting in a value of zero because the shift amount, while large, is still less than the bitsize. However, the expression `1UL << (PAGE_SHIFT + order)` does lead to undefined behavior.
My second thought was, if the returned size `ret_sz` becomes 0, subtracting it from `rem_sz` results in an infinite loop. But the value of `num` is updated in the loop and set to at least `PAGE_SIZE`. Therefore, `order` can NEVER equal 52 again, so the edge case will not occur.
The code handles cases where `scatter_elem_sz` is negative or very large. If `scatter_elem_sz` is set to `-1` for example, it will set `num` to at least `PAGE_SIZE`. Therefore, `num` will be at least `PAGE_SIZE`. And `get_order(num)` will return a reasonable `order`. If it is `0x7fffffff`, `get_order(0x7fffffff)` would return 19.
Now I am calculating `PAGE_SIZE << 19`. The problem is that the `ret_sz` can be a negative number, but it goes through several retries and becomes positive. Therefore, no issues should occur. So far, the overflow checks seem robust.
Now I'm asking myself, are there any other places where `scatter_elem_sz` is used that could introduce issues? I need to review the entire function.
|
| 42/4 |
2026/05/20 22:38 |
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=1591=sg_remove_device(struct device *cl_dev)
--
drivers/scsi/sg.c-1624-
drivers/scsi/sg.c:1625:module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR);
drivers/scsi/sg.c-1626-module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
--
drivers/scsi/sg.c=1659=MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);
drivers/scsi/sg.c-1660-
drivers/scsi/sg.c:1661:MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element "
drivers/scsi/sg.c-1662- "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))");
--
drivers/scsi/sg.c=1667=init_sg(void)
--
drivers/scsi/sg.c-1670-
drivers/scsi/sg.c:1671: if (scatter_elem_sz < PAGE_SIZE) {
drivers/scsi/sg.c:1672: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1673: scatter_elem_sz_prev = scatter_elem_sz;
drivers/scsi/sg.c-1674- }
--
drivers/scsi/sg.c=1855=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1876-
drivers/scsi/sg.c:1877: num = scatter_elem_sz;
drivers/scsi/sg.c:1878: if (unlikely(num != scatter_elem_sz_prev)) {
drivers/scsi/sg.c-1879- if (num < PAGE_SIZE) {
drivers/scsi/sg.c:1880: scatter_elem_sz = PAGE_SIZE;
drivers/scsi/sg.c:1881: scatter_elem_sz_prev = PAGE_SIZE;
drivers/scsi/sg.c-1882- } else
drivers/scsi/sg.c:1883: scatter_elem_sz_prev = num;
drivers/scsi/sg.c-1884- }
--
drivers/scsi/sg.c-1892-
drivers/scsi/sg.c:1893: num = (rem_sz > scatter_elem_sz_prev) ?
drivers/scsi/sg.c:1894: scatter_elem_sz_prev : rem_sz;
drivers/scsi/sg.c-1895-
--
drivers/scsi/sg.c-1899-
drivers/scsi/sg.c:1900: if (num == scatter_elem_sz_prev) {
drivers/scsi/sg.c:1901: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
drivers/scsi/sg.c:1902: scatter_elem_sz = ret_sz;
drivers/scsi/sg.c:1903: scatter_elem_sz_prev = ret_sz;
drivers/scsi/sg.c-1904- }
]
|
| 43/4 |
2026/05/20 22:38 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 17227
output: 17
thoughts: 1839
Thoughts: **Analyzing Potential Integer Overflow in `sg_build_indirect`**
Okay, so I was looking over `sg_build_indirect` and noticed something about how `scatter_elem_sz` is handled. Specifically, it involves the potential for `ret_sz` (the size of a page allocation) to be negative. Initially, I thought this could lead to `scatter_elem_sz` not being updated, but then I realized the comparison `ret_sz > scatter_elem_sz_prev` would always be false if `ret_sz` is negative, preventing the update. I initially believed it would be a problem if `scatter_elem_sz` reached its maximum value (`0x7fffffff`), which could lead to `ret_sz` being negative and not updating. But after tracking the variables I found out it does not lead to any update failures.
I started to dig deeper, questioning if this negative `ret_sz` could cause other issues. I considered how `rem_sz -= ret_sz` would behave if `ret_sz` was negative, possibly leading to an infinite loop if the subtraction caused an integer overflow. However, after carefully considering various scenarios, I realized that even if `ret_sz` becomes negative, the integer subtraction *always* results in a negative value for `rem_sz`, which would terminate the loop as it does not meet the necessary criteria to continue. So, the issue is not an infinite loop. The only remaining problem is that printing a negative `ret_sz` within a logging statement is just a cosmetic issue.
I went back to analyze how `scatter_elem_sz` might be incorrectly clamped. I looked at the part of `sg_build_indirect` that adjusts the size if it's less than `PAGE_SIZE`. It updates the `scatter_elem_sz` to be equal to `PAGE_SIZE` if this happens, and after tracing this I came to the conclusion this solves the potential bug.
Given the analysis, I don't see any critical issues, and my reasoning shows that it is robust and safe. I'll need to do a broader search for similar potential integer issues in `sg.c`, but so far, I think this specific case in `sg_build_indirect` is handled correctly, with potential logging anomalies.
|
| 44/4 |
2026/05/20 22:39 |
tool |
grepper |
0m
Args: map[Expression:get_order]
Results: map[Output:
Full output is too long, showing 500 out of 3130 lines.
Use more precise expression if possible.
[arch/alpha/kernel/pci_iommu.c=405=static void *alpha_pci_alloc_coherent(struct device *dev, size_t size,
--
arch/alpha/kernel/pci_iommu.c-410- void *cpu_addr;
arch/alpha/kernel/pci_iommu.c:411: long order = get_order(size);
arch/alpha/kernel/pci_iommu.c-412-
--
arch/alpha/kernel/pci_iommu.c=450=static void alpha_pci_free_coherent(struct device *dev, size_t size,
--
arch/alpha/kernel/pci_iommu.c-455- dma_unmap_single(&pdev->dev, dma_addr, size, DMA_BIDIRECTIONAL);
arch/alpha/kernel/pci_iommu.c:456: free_pages((unsigned long)cpu_addr, get_order(size));
arch/alpha/kernel/pci_iommu.c-457-
--
arch/arm/mm/dma-mapping.c=141=static struct page *__dma_alloc_buffer(struct device *dev, size_t size,
--
arch/arm/mm/dma-mapping.c-143-{
arch/arm/mm/dma-mapping.c:144: unsigned long order = get_order(size);
arch/arm/mm/dma-mapping.c-145- struct page *page, *p, *e;
--
arch/arm/mm/dma-mapping.c=391=static void *__alloc_from_contiguous(struct device *dev, size_t size,
--
arch/arm/mm/dma-mapping.c-395-{
arch/arm/mm/dma-mapping.c:396: unsigned long order = get_order(size);
arch/arm/mm/dma-mapping.c-397- size_t count = size >> PAGE_SHIFT;
--
arch/arm/mm/dma-mapping.c=754=static inline dma_addr_t __alloc_iova(struct dma_iommu_mapping *mapping,
--
arch/arm/mm/dma-mapping.c-756-{
arch/arm/mm/dma-mapping.c:757: unsigned int order = get_order(size);
arch/arm/mm/dma-mapping.c-758- unsigned int align = 0;
--
arch/arm/mm/dma-mapping.c=850=static struct page **__iommu_alloc_buffer(struct device *dev, size_t size,
--
arch/arm/mm/dma-mapping.c-865- {
arch/arm/mm/dma-mapping.c:866: unsigned long order = get_order(size);
arch/arm/mm/dma-mapping.c-867- struct page *page;
--
arch/arm/mm/mmu.c=726=static void *__init late_alloc(unsigned long sz)
--
arch/arm/mm/mmu.c-728- void *ptdesc = pagetable_alloc(GFP_PGTABLE_KERNEL & ~__GFP_HIGHMEM,
arch/arm/mm/mmu.c:729: get_order(sz));
arch/arm/mm/mmu.c-730-
--
arch/arm64/kvm/arm.c=2066=static unsigned long nvhe_percpu_order(void)
--
arch/arm64/kvm/arm.c-2069-
arch/arm64/kvm/arm.c:2070: return size ? get_order(size) : 0;
arch/arm64/kvm/arm.c-2071-}
--
arch/arm64/kvm/arm.c=2073=static size_t pkvm_host_sve_state_order(void)
arch/arm64/kvm/arm.c-2074-{
arch/arm64/kvm/arm.c:2075: return get_order(pkvm_host_sve_state_size());
arch/arm64/kvm/arm.c-2076-}
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c=84=static void *host_s2_zalloc_pages_exact(size_t size)
arch/arm64/kvm/hyp/nvhe/mem_protect.c-85-{
arch/arm64/kvm/hyp/nvhe/mem_protect.c:86: void *addr = hyp_alloc_pages(&host_s2_pool, get_order(size));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-87-
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c-94- */
arch/arm64/kvm/hyp/nvhe/mem_protect.c:95: WARN_ON(size != (PAGE_SIZE << get_order(size)));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-96-
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c=185=static void *guest_s2_zalloc_pages_exact(size_t size)
arch/arm64/kvm/hyp/nvhe/mem_protect.c-186-{
arch/arm64/kvm/hyp/nvhe/mem_protect.c:187: void *addr = hyp_alloc_pages(¤t_vm->pool, get_order(size));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-188-
arch/arm64/kvm/hyp/nvhe/mem_protect.c:189: WARN_ON(size != (PAGE_SIZE << get_order(size)));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-190- hyp_split_page(hyp_virt_to_page(addr));
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c=195=static void guest_s2_free_pages_exact(void *addr, unsigned long size)
arch/arm64/kvm/hyp/nvhe/mem_protect.c-196-{
arch/arm64/kvm/hyp/nvhe/mem_protect.c:197: u8 order = get_order(size);
arch/arm64/kvm/hyp/nvhe/mem_protect.c-198- unsigned int i;
--
arch/arm64/kvm/hyp/nvhe/page_alloc.c=223=int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned int nr_pages,
--
arch/arm64/kvm/hyp/nvhe/page_alloc.c-231- pool->max_order = min(MAX_PAGE_ORDER,
arch/arm64/kvm/hyp/nvhe/page_alloc.c:232: get_order(nr_pages << PAGE_SHIFT));
arch/arm64/kvm/hyp/nvhe/page_alloc.c-233- for (i = 0; i <= pool->max_order; i++)
--
arch/arm64/mm/mmu.c=1431=static void free_hotplug_page_range(struct page *page, size_t size,
--
arch/arm64/mm/mmu.c-1437- WARN_ON(PageReserved(page));
arch/arm64/mm/mmu.c:1438: __free_pages(page, get_order(size));
arch/arm64/mm/mmu.c-1439- }
--
arch/loongarch/kernel/irq.c=108=void __init init_IRQ(void)
--
arch/loongarch/kernel/irq.c-110- int i;
arch/loongarch/kernel/irq.c:111: unsigned int order = get_order(IRQ_STACK_SIZE);
arch/loongarch/kernel/irq.c-112- struct page *page;
--
arch/loongarch/mm/tlb.c=266=static void setup_tlb_handler(int cpu)
--
arch/loongarch/mm/tlb.c-298-
arch/loongarch/mm/tlb.c:299: page = alloc_pages_node(cpu_to_node(cpu), GFP_ATOMIC, get_order(vec_sz));
arch/loongarch/mm/tlb.c-300- if (!page)
--
arch/m68k/sun3/sun3dvma.c=317=void *dvma_malloc_align(unsigned long len, unsigned long align)
--
arch/m68k/sun3/sun3dvma.c-328-
arch/m68k/sun3/sun3dvma.c:329: if((kaddr = __get_free_pages(GFP_ATOMIC, get_order(len))) == 0)
arch/m68k/sun3/sun3dvma.c-330- return NULL;
--
arch/m68k/sun3/sun3dvma.c-332- if((baddr = (unsigned long)dvma_map_align(kaddr, len, align)) == 0) {
arch/m68k/sun3/sun3dvma.c:333: free_pages(kaddr, get_order(len));
arch/m68k/sun3/sun3dvma.c-334- return NULL;
--
arch/m68k/sun3/sun3dvma.c-340- dvma_unmap((void *)baddr);
arch/m68k/sun3/sun3dvma.c:341: free_pages(kaddr, get_order(len));
arch/m68k/sun3/sun3dvma.c-342- return NULL;
--
arch/mips/include/asm/mach-generic/floppy.h=115=static inline unsigned long fd_dma_mem_alloc(unsigned long size)
arch/mips/include/asm/mach-generic/floppy.h-116-{
arch/mips/include/asm/mach-generic/floppy.h:117: return __get_dma_pages(GFP_KERNEL, get_order(size));
arch/mips/include/asm/mach-generic/floppy.h-118-}
--
arch/mips/include/asm/mach-generic/floppy.h=120=static inline void fd_dma_mem_free(unsigned long addr, unsigned long size)
arch/mips/include/asm/mach-generic/floppy.h-121-{
arch/mips/include/asm/mach-generic/floppy.h:122: free_pages(addr, get_order(size));
arch/mips/include/asm/mach-generic/floppy.h-123-}
--
arch/mips/include/asm/mach-jazz/floppy.h=104=static inline unsigned long fd_dma_mem_alloc(unsigned long size)
--
arch/mips/include/asm/mach-jazz/floppy.h-107-
arch/mips/include/asm/mach-jazz/floppy.h:108: mem = __get_dma_pages(GFP_KERNEL, get_order(size));
arch/mips/include/asm/mach-jazz/floppy.h-109- if(!mem)
--
arch/mips/include/asm/mach-jazz/floppy.h=116=static inline void fd_dma_mem_free(unsigned long addr, unsigned long size)
--
arch/mips/include/asm/mach-jazz/floppy.h-118- vdma_free(vdma_phys2log(CPHYSADDR(addr)));
arch/mips/include/asm/mach-jazz/floppy.h:119: free_pages(addr, get_order(size));
arch/mips/include/asm/mach-jazz/floppy.h-120-}
--
arch/mips/jazz/jazzdma.c=64=static int __init vdma_init(void)
--
arch/mips/jazz/jazzdma.c-71- pgtbl = (VDMA_PGTBL_ENTRY *)__get_free_pages(GFP_KERNEL | GFP_DMA,
arch/mips/jazz/jazzdma.c:72: get_order(VDMA_PGTBL_SIZE));
arch/mips/jazz/jazzdma.c-73- BUG_ON(!pgtbl);
--
arch/mips/jazz/jazzdma.c=491=static void *jazz_dma_alloc(struct device *dev, size_t size,
--
arch/mips/jazz/jazzdma.c-500- size = PAGE_ALIGN(size);
arch/mips/jazz/jazzdma.c:501: page = alloc_pages(gfp, get_order(size));
arch/mips/jazz/jazzdma.c-502- if (!page)
--
arch/mips/jazz/jazzdma.c-512-out_free_pages:
arch/mips/jazz/jazzdma.c:513: __free_pages(page, get_order(size));
arch/mips/jazz/jazzdma.c-514- return NULL;
--
arch/mips/jazz/jazzdma.c=517=static void jazz_dma_free(struct device *dev, size_t size, void *vaddr,
--
arch/mips/jazz/jazzdma.c-520- vdma_free(dma_handle);
arch/mips/jazz/jazzdma.c:521: __free_pages(virt_to_page(vaddr), get_order(size));
arch/mips/jazz/jazzdma.c-522-}
--
arch/mips/kernel/irq.c=53=void __init init_IRQ(void)
--
arch/mips/kernel/irq.c-55- int i;
arch/mips/kernel/irq.c:56: unsigned int order = get_order(IRQ_STACK_SIZE);
arch/mips/kernel/irq.c-57-
--
arch/parisc/include/asm/floppy.h=151=static unsigned long dma_mem_alloc(unsigned long size)
arch/parisc/include/asm/floppy.h-152-{
arch/parisc/include/asm/floppy.h:153: return __get_dma_pages(GFP_KERNEL, get_order(size));
arch/parisc/include/asm/floppy.h-154-}
--
arch/parisc/include/asm/floppy.h=165=static void _fd_dma_mem_free(unsigned long addr, unsigned long size)
--
arch/parisc/include/asm/floppy.h-169- else
arch/parisc/include/asm/floppy.h:170: free_pages(addr, get_order(size));
arch/parisc/include/asm/floppy.h-171-}
--
arch/parisc/kernel/pci-dma.c-33-#include <asm/io.h>
arch/parisc/kernel/pci-dma.c:34:#include <asm/page.h> /* get_order */
arch/parisc/kernel/pci-dma.c-35-#include <linux/uaccess.h>
--
arch/parisc/kernel/pci-dma.c=374=pcxl_dma_init(void)
--
arch/parisc/kernel/pci-dma.c-381- pcxl_res_map = (char *)__get_free_pages(GFP_KERNEL,
arch/parisc/kernel/pci-dma.c:382: get_order(pcxl_res_size));
arch/parisc/kernel/pci-dma.c-383- memset(pcxl_res_map, 0, pcxl_res_size);
--
arch/parisc/kernel/pci-dma.c=401=void *arch_dma_alloc(struct device *dev, size_t size,
--
arch/parisc/kernel/pci-dma.c-410-
arch/parisc/kernel/pci-dma.c:411: order = get_order(size);
arch/parisc/kernel/pci-dma.c-412- size = 1 << (order + PAGE_SHIFT);
--
arch/parisc/kernel/pci-dma.c=423=void arch_dma_free(struct device *dev, size_t size, void *vaddr,
--
arch/parisc/kernel/pci-dma.c-425-{
arch/parisc/kernel/pci-dma.c:426: int order = get_order(size);
arch/parisc/kernel/pci-dma.c-427-
--
arch/powerpc/include/asm/iommu.h=96=struct iommu_table {
--
arch/powerpc/include/asm/iommu.h-126-
arch/powerpc/include/asm/iommu.h:127:/* Pure 2^n version of get_order */
arch/powerpc/include/asm/iommu.h-128-static inline __attribute_const__
--
arch/powerpc/kernel/iommu.c=912=void *iommu_alloc_coherent(struct device *dev, struct iommu_table *tbl,
--
arch/powerpc/kernel/iommu.c-923- size = PAGE_ALIGN(size);
arch/powerpc/kernel/iommu.c:924: order = get_order(size);
arch/powerpc/kernel/iommu.c-925-
--
arch/powerpc/kernel/iommu.c=962=void iommu_free_coherent(struct iommu_table *tbl, size_t size,
--
arch/powerpc/kernel/iommu.c-971- size = PAGE_ALIGN(size);
arch/powerpc/kernel/iommu.c:972: free_pages((unsigned long)vaddr, get_order(size));
arch/powerpc/kernel/iommu.c-973- }
--
arch/powerpc/mm/book3s64/radix_pgtable.c=820=static void __meminit remove_pmd_table(pmd_t *pmd_start, unsigned long addr,
--
arch/powerpc/mm/book3s64/radix_pgtable.c-838- if (!direct)
arch/powerpc/mm/book3s64/radix_pgtable.c:839: free_vmemmap_pages(pmd_page(*pmd), altmap, get_order(PMD_SIZE));
arch/powerpc/mm/book3s64/radix_pgtable.c-840- pte_clear(&init_mm, addr, (pte_t *)pmd);
--
arch/powerpc/mm/book3s64/radix_pgtable.c-844- else if (!direct && vmemmap_pmd_is_unused(addr, next)) {
arch/powerpc/mm/book3s64/radix_pgtable.c:845: free_vmemmap_pages(pmd_page(*pmd), altmap, get_order(PMD_SIZE));
arch/powerpc/mm/book3s64/radix_pgtable.c-846- pte_clear(&init_mm, addr, (pte_t *)pmd);
--
arch/powerpc/mm/init_64.c=203=static int __meminit __vmemmap_populate(unsigned long start, unsigned long end, int node,
--
arch/powerpc/mm/init_64.c-253- int nr_pfns = page_size >> PAGE_SHIFT;
arch/powerpc/mm/init_64.c:254: unsigned long page_order = get_order(page_size);
arch/powerpc/mm/init_64.c-255-
--
arch/powerpc/mm/init_64.c=320=static void __ref __vmemmap_free(unsigned long start, unsigned long end,
--
arch/powerpc/mm/init_64.c-323- unsigned long page_size = 1 << mmu_psize_defs[mmu_vmemmap_psize].shift;
arch/powerpc/mm/init_64.c:324: unsigned long page_order = get_order(page_size);
arch/powerpc/mm/init_64.c-325- unsigned long alt_start = ~0, alt_end = ~0;
--
arch/powerpc/perf/imc-pmu.c=599=static int core_imc_mem_init(int cpu, int size)
--
arch/powerpc/perf/imc-pmu.c-615- GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
arch/powerpc/perf/imc-pmu.c:616: __GFP_NOWARN, get_order(size));
arch/powerpc/perf/imc-pmu.c-617- if (!page)
--
arch/powerpc/perf/imc-pmu.c-627- if (rc) {
arch/powerpc/perf/imc-pmu.c:628: free_pages((u64)mem_info->vbase, get_order(size));
arch/powerpc/perf/imc-pmu.c-629- mem_info->vbase = NULL;
--
arch/powerpc/perf/imc-pmu.c=920=static int thread_imc_mem_alloc(int cpu_id, int size)
--
arch/powerpc/perf/imc-pmu.c-932- GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
arch/powerpc/perf/imc-pmu.c:933: __GFP_NOWARN, get_order(size));
arch/powerpc/perf/imc-pmu.c-934- if (!page)
--
arch/powerpc/perf/imc-pmu.c=1205=static int trace_imc_mem_alloc(int cpu_id, int size)
--
arch/powerpc/perf/imc-pmu.c-1215- GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
arch/powerpc/perf/imc-pmu.c:1216: __GFP_NOWARN, get_order(size));
arch/powerpc/perf/imc-pmu.c-1217- if (!page)
--
arch/powerpc/perf/imc-pmu.c=1568=static void cleanup_all_core_imc_memory(void)
--
arch/powerpc/perf/imc-pmu.c-1576- if (ptr[i].vbase)
arch/powerpc/perf/imc-pmu.c:1577: free_pages((u64)ptr[i].vbase, get_order(size));
arch/powerpc/perf/imc-pmu.c-1578- }
--
arch/powerpc/perf/imc-pmu.c=1598=static void cleanup_all_thread_imc_memory(void)
arch/powerpc/perf/imc-pmu.c-1599-{
arch/powerpc/perf/imc-pmu.c:1600: int i, order = get_order(thread_imc_mem_size);
arch/powerpc/perf/imc-pmu.c-1601-
--
arch/powerpc/perf/imc-pmu.c=1609=static void cleanup_all_trace_imc_memory(void)
arch/powerpc/perf/imc-pmu.c-1610-{
arch/powerpc/perf/imc-pmu.c:1611: int i, order = get_order(trace_imc_mem_size);
arch/powerpc/perf/imc-pmu.c-1612-
--
arch/powerpc/platforms/cell/spufs/inode.c=633=static void spufs_exit_isolated_loader(void)
--
arch/powerpc/platforms/cell/spufs/inode.c-635- free_pages((unsigned long) isolated_loader,
arch/powerpc/platforms/cell/spufs/inode.c:636: get_order(isolated_loader_size));
arch/powerpc/platforms/cell/spufs/inode.c-637-}
--
arch/powerpc/platforms/cell/spufs/inode.c=640=spufs_init_isolated_loader(void)
--
arch/powerpc/platforms/cell/spufs/inode.c-655- /* the loader must be align on a 16 byte boundary */
arch/powerpc/platforms/cell/spufs/inode.c:656: isolated_loader = (char *)__get_free_pages(GFP_KERNEL, get_order(size));
arch/powerpc/platforms/cell/spufs/inode.c-657- if (!isolated_loader)
--
arch/powerpc/platforms/powernv/pci-ioda-tce.c=216=static void pnv_pci_ioda2_table_do_free_pages(__be64 *addr,
--
arch/powerpc/platforms/powernv/pci-ioda-tce.c-236-
arch/powerpc/platforms/powernv/pci-ioda-tce.c:237: free_pages(addr_ul, get_order(size << 3));
arch/powerpc/platforms/powernv/pci-ioda-tce.c-238-}
--
arch/powerpc/platforms/powernv/pci-ioda.c=1053=static int pnv_pci_ioda_dma_64bit_bypass(struct pnv_ioda_pe *pe)
--
arch/powerpc/platforms/powernv/pci-ioda.c-1072- table_pages = alloc_pages_node(pe->phb->hose->node, GFP_KERNEL,
arch/powerpc/platforms/powernv/pci-ioda.c:1073: get_order(table_size));
arch/powerpc/platforms/powernv/pci-ioda.c-1074- if (!table_pages)
--
arch/powerpc/platforms/ps3/system-bus.c=505=static void * ps3_alloc_coherent(struct device *_dev, size_t size,
--
arch/powerpc/platforms/ps3/system-bus.c-515-
arch/powerpc/platforms/ps3/system-bus.c:516: virt_addr = __get_free_pages(flag, get_order(size));
arch/powerpc/platforms/ps3/system-bus.c-517-
--
arch/powerpc/platforms/ps3/system-bus.c-536-clean_alloc:
arch/powerpc/platforms/ps3/system-bus.c:537: free_pages(virt_addr, get_order(size));
arch/powerpc/platforms/ps3/system-bus.c-538-clean_none:
--
arch/powerpc/platforms/ps3/system-bus.c=543=static void ps3_free_coherent(struct device *_dev, size_t size, void *vaddr,
--
arch/powerpc/platforms/ps3/system-bus.c-548- ps3_dma_unmap(dev->d_region, dma_handle, size);
arch/powerpc/platforms/ps3/system-bus.c:549: free_pages((unsigned long)vaddr, get_order(size));
arch/powerpc/platforms/ps3/system-bus.c-550-}
--
arch/riscv/kernel/unaligned_access_speed.c-20-#define MISALIGNED_BUFFER_SIZE 0x4000
arch/riscv/kernel/unaligned_access_speed.c:21:#define MISALIGNED_BUFFER_ORDER get_order(MISALIGNED_BUFFER_SIZE)
arch/riscv/kernel/unaligned_access_speed.c-22-#define MISALIGNED_COPY_SIZE ((MISALIGNED_BUFFER_SIZE / 2) - 0x80)
--
arch/riscv/kvm/aia_imsic.c=1090=int kvm_riscv_vcpu_aia_imsic_init(struct kvm_vcpu *vcpu)
--
arch/riscv/kvm/aia_imsic.c-1115- swfile_page = alloc_pages(GFP_KERNEL | __GFP_ZERO,
arch/riscv/kvm/aia_imsic.c:1116: get_order(sizeof(*imsic->swfile)));
arch/riscv/kvm/aia_imsic.c-1117- if (!swfile_page) {
--
arch/riscv/kvm/aia_imsic.c-1139- free_pages((unsigned long)imsic->swfile,
arch/riscv/kvm/aia_imsic.c:1140: get_order(sizeof(*imsic->swfile)));
arch/riscv/kvm/aia_imsic.c-1141-fail_free_imsic:
--
arch/riscv/kvm/aia_imsic.c=1147=void kvm_riscv_vcpu_aia_imsic_cleanup(struct kvm_vcpu *vcpu)
--
arch/riscv/kvm/aia_imsic.c-1161- free_pages((unsigned long)imsic->swfile,
arch/riscv/kvm/aia_imsic.c:1162: get_order(sizeof(*imsic->swfile)));
arch/riscv/kvm/aia_imsic.c-1163-
--
arch/riscv/kvm/mmu.c=536=int kvm_riscv_mmu_alloc_pgd(struct kvm *kvm)
--
arch/riscv/kvm/mmu.c-545- pgd_page = alloc_pages(GFP_KERNEL | __GFP_ZERO,
arch/riscv/kvm/mmu.c:546: get_order(kvm_riscv_gstage_pgd_size));
arch/riscv/kvm/mmu.c-547- if (!pgd_page)
--
arch/riscv/kvm/mmu.c=556=void kvm_riscv_mmu_free_pgd(struct kvm *kvm)
--
arch/riscv/kvm/mmu.c-573- if (pgd)
arch/riscv/kvm/mmu.c:574: free_pages((unsigned long)pgd, get_order(kvm_riscv_gstage_pgd_size));
arch/riscv/kvm/mmu.c-575-}
--
arch/riscv/kvm/nacl.c=81=void kvm_riscv_nacl_exit(void)
--
arch/riscv/kvm/nacl.c-95- free_pages((unsigned long)nacl->shmem,
arch/riscv/kvm/nacl.c:96: get_order(SBI_NACL_SHMEM_SIZE));
arch/riscv/kvm/nacl.c-97- nacl->shmem = NULL;
--
arch/riscv/kvm/nacl.c=114=int kvm_riscv_nacl_init(void)
--
arch/riscv/kvm/nacl.c-141- shmem_page = alloc_pages(GFP_KERNEL | __GFP_ZERO,
arch/riscv/kvm/nacl.c:142: get_order(SBI_NACL_SHMEM_SIZE));
arch/riscv/kvm/nacl.c-143- if (!shmem_page) {
--
arch/riscv/mm/init.c=1553=static void __meminit free_vmemmap_storage(struct page *page, size_t size,
--
arch/riscv/mm/init.c-1555-{
arch/riscv/mm/init.c:1556: int order = get_order(size);
arch/riscv/mm/init.c-1557-
--
arch/s390/kvm/gmap.c=701=int gmap_link(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, struct guest_fault *f,
--
arch/s390/kvm/gmap.c-711- order = folio_order(page_folio(f->page));
arch/s390/kvm/gmap.c:712: if (order >= get_order(_REGION3_SIZE) && gmap_2g_allowed(gmap, f, slot))
arch/s390/kvm/gmap.c-713- level = TABLE_TYPE_REGION3;
arch/s390/kvm/gmap.c:714: else if (order >= get_order(_SEGMENT_SIZE) && gmap_1m_allowed(gmap, f, slot))
arch/s390/kvm/gmap.c-715- level = TABLE_TYPE_SEGMENT;
--
arch/s390/kvm/pci.c=52=static int zpci_setup_aipb(u8 nisc)
--
arch/s390/kvm/pci.c-66- zpci_aif_sbv = aift->sbv;
arch/s390/kvm/pci.c:67: size = get_order(PAGE_ALIGN(ZPCI_NR_DEVICES *
arch/s390/kvm/pci.c-68- sizeof(struct zpci_gaite)));
--
arch/s390/kvm/pv.c=228=int kvm_s390_pv_destroy_cpu(struct kvm_vcpu *vcpu, u16 *rc, u16 *rrc)
--
arch/s390/kvm/pv.c-243- free_pages(vcpu->arch.pv.stor_base,
arch/s390/kvm/pv.c:244: get_order(uv_info.guest_cpu_stor_len));
arch/s390/kvm/pv.c-245-
--
arch/s390/kvm/pv.c=262=int kvm_s390_pv_create_cpu(struct kvm_vcpu *vcpu, u16 *rc, u16 *rrc)
--
arch/s390/kvm/pv.c-274- vcpu->arch.pv.stor_base = __get_free_pages(GFP_KERNEL_ACCOUNT,
arch/s390/kvm/pv.c:275: get_order(uv_info.guest_cpu_stor_len));
arch/s390/kvm/pv.c-276- if (!vcpu->arch.pv.stor_base)
--
arch/s390/kvm/pv.c-288- free_pages(vcpu->arch.pv.stor_base,
arch/s390/kvm/pv.c:289: get_order(uv_info.guest_cpu_stor_len));
arch/s390/kvm/pv.c-290- return -ENOMEM;
--
arch/s390/kvm/pv.c=319=static void kvm_s390_pv_dealloc_vm(struct kvm *kvm)
--
arch/s390/kvm/pv.c-322- free_pages(kvm->arch.pv.stor_base,
arch/s390/kvm/pv.c:323: get_order(uv_info.guest_base_stor_len));
arch/s390/kvm/pv.c-324- kvm_s390_clear_pv_state(kvm);
--
arch/s390/kvm/pv.c=327=static int kvm_s390_pv_alloc_vm(struct kvm *kvm)
--
arch/s390/kvm/pv.c-333- kvm->arch.pv.stor_var = NULL;
arch/s390/kvm/pv.c:334: kvm->arch.pv.stor_base = __get_free_pages(GFP_KERNEL_ACCOUNT, get_order(base));
arch/s390/kvm/pv.c-335- if (!kvm->arch.pv.stor_base)
--
arch/s390/kvm/pv.c=376=static int kvm_s390_pv_dispose_one_leftover(struct kvm *kvm,
--
arch/s390/kvm/pv.c-395- */
arch/s390/kvm/pv.c:396: free_pages(leftover->stor_base, get_order(uv_info.guest_base_stor_len));
arch/s390/kvm/pv.c-397- free_pages(leftover->old_gmap_table, CRST_ALLOC_ORDER);
--
arch/s390/mm/vmem.c=168=static int __ref modify_pte_table(pmd_t *pmd, unsigned long addr,
--
arch/s390/mm/vmem.c-182- if (!direct)
arch/s390/mm/vmem.c:183: vmem_free_pages((unsigned long)pfn_to_virt(pte_pfn(*pte)), get_order(PAGE_SIZE), altmap);
arch/s390/mm/vmem.c-184- pte_clear(&init_mm, addr, pte);
--
arch/s390/mm/vmem.c=223=static int __ref modify_pmd_table(pud_t *pud, unsigned long addr,
--
arch/s390/mm/vmem.c-242- if (!direct)
arch/s390/mm/vmem.c:243: vmem_free_pages(pmd_deref(*pmd), get_order(PMD_SIZE), altmap);
arch/s390/mm/vmem.c-244- pmd_clear(pmd);
--
arch/s390/mm/vmem.c-246- } else if (!direct && vmemmap_unuse_sub_pmd(addr, next)) {
arch/s390/mm/vmem.c:247: vmem_free_pages(pmd_deref(*pmd), get_order(PMD_SIZE), altmap);
arch/s390/mm/vmem.c-248- pmd_clear(pmd);
--
arch/s390/mm/vmem.c=315=static int modify_pud_table(p4d_t *p4d, unsigned long addr, unsigned long end,
--
arch/s390/mm/vmem.c-333- if (!direct)
arch/s390/mm/vmem.c:334: vmem_free_pages(pud_deref(*pud), get_order(PUD_SIZE), altmap);
arch/s390/mm/vmem.c-335- pud_clear(pud);
--
arch/s390/pci/pci_clp.c=92=static void *clp_alloc_block(gfp_t gfp_mask)
arch/s390/pci/pci_clp.c-93-{
arch/s390/pci/pci_clp.c:94: return (void *) __get_free_pages(gfp_mask, get_order(CLP_BLK_SIZE));
arch/s390/pci/pci_clp.c-95-}
--
arch/s390/pci/pci_clp.c=97=static void clp_free_block(void *ptr)
arch/s390/pci/pci_clp.c-98-{
arch/s390/pci/pci_clp.c:99: free_pages((unsigned long) ptr, get_order(CLP_BLK_SIZE));
arch/s390/pci/pci_clp.c-100-}
--
arch/sh/kernel/cpu/sh4/sq.c=143=unsigned long sq_remap(unsigned long phys, unsigned int size,
--
arch/sh/kernel/cpu/sh4/sq.c-170- page = bitmap_find_free_region(sq_bitmap, 0x04000000 >> PAGE_SHIFT,
arch/sh/kernel/cpu/sh4/sq.c:171: get_order(map->size));
arch/sh/kernel/cpu/sh4/sq.c-172- if (unlikely(page < 0)) {
--
arch/sh/kernel/cpu/sh4/sq.c=207=void sq_unmap(unsigned long vaddr)
--
arch/sh/kernel/cpu/sh4/sq.c-222- page = (map->sq_addr - P4SEG_STORE_QUE) >> PAGE_SHIFT;
arch/sh/kernel/cpu/sh4/sq.c:223: bitmap_release_region(sq_bitmap, page, get_order(map->size));
arch/sh/kernel/cpu/sh4/sq.c-224-
--
arch/sparc/kernel/iommu.c=93=int iommu_table_init(struct iommu *iommu, int tsbsize,
--
arch/sparc/kernel/iommu.c-131- /* Now allocate and setup the IOMMU page table itself. */
arch/sparc/kernel/iommu.c:132: order = get_order(tsbsize);
arch/sparc/kernel/iommu.c-133- page = alloc_pages_node(numa_node, GFP_KERNEL, order);
--
arch/sparc/kernel/iommu.c=197=static void *dma_4u_alloc_coherent(struct device *dev, size_t size,
--
arch/sparc/kernel/iommu.c-208- size = IO_PAGE_ALIGN(size);
arch/sparc/kernel/iommu.c:209: order = get_order(size);
arch/sparc/kernel/iommu.c-210- if (order >= 10)
--
arch/sparc/kernel/iommu.c=246=static void dma_4u_free_coherent(struct device *dev, size_t size,
--
arch/sparc/kernel/iommu.c-257-
arch/sparc/kernel/iommu.c:258: order = get_order(size);
arch/sparc/kernel/iommu.c-259- if (order < 10)
--
arch/sparc/kernel/irq_64.c=1016=static void __init alloc_one_queue(unsigned long *pa_ptr, unsigned long qmask)
--
arch/sparc/kernel/irq_64.c-1018- unsigned long size = PAGE_ALIGN(qmask + 1);
arch/sparc/kernel/irq_64.c:1019: unsigned long order = get_order(size);
arch/sparc/kernel/irq_64.c-1020- unsigned long p;
--
arch/sparc/kernel/irq_64.c=1091=static void __init irq_ivector_init(void)
--
arch/sparc/kernel/irq_64.c-1103- size = sizeof(struct ino_bucket) * ivecs;
arch/sparc/kernel/irq_64.c:1104: order = get_order(size);
arch/sparc/kernel/irq_64.c-1105- ivector_table = (struct ino_bucket *)
--
arch/sparc/kernel/ldc.c=975=static int alloc_queue(const char *name, unsigned long num_entries,
--
arch/sparc/kernel/ldc.c-981- size = num_entries * LDC_PACKET_SIZE;
arch/sparc/kernel/ldc.c:982: order = get_order(size);
arch/sparc/kernel/ldc.c-983-
--
arch/sparc/kernel/ldc.c=999=static void free_queue(unsigned long num_entries, struct ldc_packet *q)
--
arch/sparc/kernel/ldc.c-1006- size = num_entries * LDC_PACKET_SIZE;
arch/sparc/kernel/ldc.c:1007: order = get_order(size);
arch/sparc/kernel/ldc.c-1008-
--
arch/sparc/kernel/ldc.c=1041=static int ldc_iommu_init(const char *name, struct ldc_channel *lp)
--
arch/sparc/kernel/ldc.c-1065-
]
]
|
| 45/4 |
2026/05/20 22:39 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 31379
output: 25
thoughts: 101
Thoughts: **Debugging a Subtle Memory Allocation Issue**
Okay, so the `get_order` function, that's used *everywhere*, and it seems that's where the problem is manifesting. Specifically, this bug is buried deep inside `sg_build_indirect`, and it looks like a variable called `num` isn't being updated correctly after it's being "clamped". This leads to a call to `get_order(0)`, which...wait, it *returns* 52? That can't be right. That's just asking for trouble. `PAGE_SIZE << 52` or `1 << (PAGE_SHIFT + 52)`. That's an enormous allocation! We need to understand *why* `get_order(0)` is returning 52. Let me check the implementation of that function *right now*. Time to dive into the code.
|
| 46/4 |
2026/05/20 22:39 |
tool |
grepper |
0m
Error:
Args: map[Expression:static inline __attribute_const__ int get_order]
Results:
|
| 47/4 |
2026/05/20 22:39 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 31710
output: 18
thoughts: 12
Thoughts: Okay, here's my summary, presented as a stream of thought:
**Finding the `get_order` Definition**
Right, so I need to understand this `get_order` function. It's crucial for the task at hand, I can feel it. Let's start with a focused search. Time to dive into the codebase and locate where `get_order` is defined. Knowing its signature, inputs, and outputs is the foundation for understanding how this part of the system operates. Once I've got that, I can really start to trace its behavior and figure out the intricate details. Let's see what we can find.
|
| 48/4 |
2026/05/20 22:39 |
tool |
grepper |
0m
Args: map[Expression:int get_order]
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-{
--
mm/internal.h=1605=bool touch_pmd(struct vm_area_struct *vma, unsigned long addr,
--
mm/internal.h-1611- */
mm/internal.h:1612:static inline int get_order_from_str(const char *size_str,
mm/internal.h-1613- unsigned long valid_orders)
]
|
| 49/4 |
2026/05/20 22:39 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 32052
output: 42
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 my hands dirty. Let's see what's actually going on with this paging business, starting at the lowest level, the assembly-generic code, specifically `include/asm-generic/getorder.h`. I need to understand how the system's calculating the order for page allocation. I'm assuming there's some bit-twiddling magic happening in there. Knowing the nuances of `getorder` is fundamental for performance tuning and debugging memory allocation issues, especially when working with NUMA systems or high-performance networking drivers. I'm hoping to refresh my understanding of the algorithm and consider if any optimizations are possible given the current hardware context. This header likely contains the core logic for translating physical page sizes to the power-of-two order used by the kernel's memory management. I suspect there might be architecture-specific conditional compilation within, which will be interesting to dissect.
|
| 50/4 |
2026/05/20 22:39 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/asm-generic/getorder.h IncludeLines:true 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]
|
| 51/4 |
2026/05/20 22:39 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 32921
output: 42
thoughts: 1972
Thoughts: **Analyzing Potential Issues with `scatter_elem_sz` in SCSI Driver**
Okay, let's break this down. Initially, I was concerned about `get_order(0)` leading to undefined behavior due to bitwise shifts. The code seemed to calculate a `ret_sz` based on the result of `get_order()`, potentially leading to a massive `PAGE_SIZE` multiple. Specifically, if `size` becomes 0, there would be potentially infinite loop. However, after carefully tracing the execution flow and the integer sizes, it looks like there aren't any undefined behaviours if `scatter_elem_sz` is set to zero, because the condition in the code is changed:
```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;
}
```
If `scatter_elem_sz` becomes 0, `num` will be set to `PAGE_SIZE` and that should resolve the previous issue.
I then considered the scenario where `scatter_elem_sz` could be negative and discovered that the code safely handles it by setting `num` to `PAGE_SIZE` in such cases.
Next, I investigated the case when `scatter_elem_sz` is equal to `0x7fffffff` and concluded that the result of the `ret_sz` calculation is `-2147483648`, which is then decremented to a positive number, it shouldn't be an issue and it will work fine.
I then considered the bitwise shift operations more carefully. I got concerned about the assignment of an unsigned long to an int, potentially leading to undefined behavior or at least a warning. However, after researching the C standards and the implementation on the Linux kernel, the assignment from unsigned long to int is implementation-defined. Specifically, GCC handles it as a wrap-around, which is well-defined and not undefined behavior. To be really safe, I can change the declaration of the type to a `size_t` or `unsigned int` instead.
I also thought about the possibility of controlling the range of `scatter_elem_sz` to mitigate any possible issues and came to the conclusion that limiting the size to a reasonable value is probably a good practice. I looked at `sg_build_indirect`, where `num` is also used:
```c
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
```
It is a good idea to limit the maximum value that `num` takes, so that a large value does not create memory issues.
The good news is that the existing code handles this large order gracefully with the fallback to smaller page allocations. So, while it's important to understand the potential edge cases and the behavior of the bitwise shift operations, the existing mechanisms for handling large orders seem robust. The initial concern about undefined behavior in bitwise shifts has been addressed, and the current code, with appropriate checks and fallback mechanisms, appears to be relatively safe regarding the values of the `scatter_elem_sz`.
|
| 52/4 |
2026/05/20 22:39 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c IncludeLines:true Name:sg_build_indirect]
Results: map[SourceCode:1854: static int
1855: sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1856: {
1857: int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems;
1858: int sg_tablesize = sfp->parentdp->sg_tablesize;
1859: int blk_size = buff_size, order;
1860: gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN | __GFP_ZERO;
1861:
1862: if (blk_size < 0)
1863: return -EFAULT;
1864: if (0 == blk_size)
1865: ++blk_size; /* don't know why */
1866: /* round request up to next highest SG_SECTOR_SZ byte boundary */
1867: blk_size = ALIGN(blk_size, SG_SECTOR_SZ);
1868: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
1869: "sg_build_indirect: buff_size=%d, blk_size=%d\n",
1870: buff_size, blk_size));
1871:
1872: /* N.B. ret_sz carried into this block ... */
1873: mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1874: if (mx_sc_elems < 0)
1875: return mx_sc_elems; /* most likely -ENOMEM */
1876:
1877: num = scatter_elem_sz;
1878: if (unlikely(num != scatter_elem_sz_prev)) {
1879: if (num < PAGE_SIZE) {
1880: scatter_elem_sz = PAGE_SIZE;
1881: scatter_elem_sz_prev = PAGE_SIZE;
1882: } else
1883: scatter_elem_sz_prev = num;
1884: }
1885:
1886: order = get_order(num);
1887: retry:
1888: ret_sz = 1 << (PAGE_SHIFT + order);
1889:
1890: for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
1891: k++, rem_sz -= ret_sz) {
1892:
1893: num = (rem_sz > scatter_elem_sz_prev) ?
1894: scatter_elem_sz_prev : rem_sz;
1895:
1896: schp->pages[k] = alloc_pages(gfp_mask, order);
1897: if (!schp->pages[k])
1898: goto out;
1899:
1900: if (num == scatter_elem_sz_prev) {
1901: if (unlikely(ret_sz > scatter_elem_sz_prev)) {
1902: scatter_elem_sz = ret_sz;
1903: scatter_elem_sz_prev = ret_sz;
1904: }
1905: }
1906:
1907: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1908: "sg_build_indirect: k=%d, num=%d, ret_sz=%d\n",
1909: k, num, ret_sz));
1910: } /* end of for loop */
1911:
1912: schp->page_order = order;
1913: schp->k_use_sg = k;
1914: SCSI_LOG_TIMEOUT(5, sg_printk(KERN_INFO, sfp->parentdp,
1915: "sg_build_indirect: k_use_sg=%d, rem_sz=%d\n",
1916: k, rem_sz));
1917:
1918: schp->bufflen = blk_size;
1919: if (rem_sz > 0) /* must have failed */
1920: return -ENOMEM;
1921: return 0;
1922: out:
1923: for (i = 0; i < k; i++)
1924: __free_pages(schp->pages[i], order);
1925:
1926: if (--order >= 0)
1927: goto retry;
1928:
1929: return -ENOMEM;
1930: }
SourceFile:drivers/scsi/sg.c]
|
| 53/4 |
2026/05/20 22:39 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 37000
output: 23
thoughts: 16
Thoughts: Okay, here's my thought process as a first-person summary, keeping in mind my expertise:
**Checking My Work**
Hold on a second... didn't I just go through this file? I could swear I made those changes. Okay, before I get carried away and potentially re-do work I've already done, the first thing I need to do is verify the state of the current code. I need to make sure I don't waste time on redundant edits. Time to pull up the current version and take a quick look. It's best to check and confirm rather than assume. Let's make sure my prior modifications are reflected here.
|
| 54/4 |
2026/05/20 22:39 |
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 74cd4e8a6..0dcd6632e 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1855,76 +1855,77 @@ 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) {
+ 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);
+ ret_sz = PAGE_SIZE << 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;
}
]
|
| 55/4 |
2026/05/20 22:39 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 38281
output: 20
thoughts: 482
Thoughts: **Analyzing the Patch's Arithmetic**
Okay, the patch looks clean, but I need to understand the reasoning behind the change. The original explanation suggests updating `num` to `PAGE_SIZE` when clamping and replacing `1` with `1UL` to avoid undefined behavior with potentially large `order` values. My fix uses `PAGE_SIZE << order` instead of `1UL << (PAGE_SHIFT + order)`. My initial thought is, why is this better?
Let's break it down. `PAGE_SIZE` is already an `unsigned long` (or potentially `unsigned int` depending on the architecture, though usually `unsigned long` on 64-bit). But wait... `PAGE_SIZE` is *defined* as `(1UL << PAGE_SHIFT)`. So, `PAGE_SIZE << order` becomes `(1UL << PAGE_SHIFT) << order`. This *should* be equivalent to `1UL << (PAGE_SHIFT + order)`. The advantage is that it side-steps any potential undefined behavior if `PAGE_SHIFT + order >= 64`.
Hold on... if `PAGE_SHIFT + order` is indeed >= 64, then `1UL << (PAGE_SHIFT + order)` *is* undefined behavior. But `PAGE_SIZE << order` avoids this because if `order` is 52 (as an extreme example), then `PAGE_SIZE << 52` shifts by 52 which is certainly less than 64. So it's well-defined. But given the nature of clamping `num` to be at least `PAGE_SIZE`, the value of `order` will never actually reach 52.
Let's consider the maximum valid `order`. Thatโs determined by `get_order(0x7fffffff)` which is 19. That means `PAGE_SHIFT + order` is at most `12 + 19 = 31`. This makes `1UL << 31` perfectly well-defined. Actually, `1U << 31` is also well-defined.
However, thinking it over, `PAGE_SIZE << order` is actually the *more* idiomatic style in the kernel when calculating an allocation's size based on the order. It's much clearer; it directly expresses "the size of `order` pages", which is precisely what the code is doing.
Now, let's take a quick look: are there any *other* instances of `1 << (PAGE_SHIFT + order)` in this `sg.c` file? Just to make sure we're consistent...
|
| 56/4 |
2026/05/20 22:40 |
tool |
grepper |
0m
Args: map[Expression:1 << \(PAGE_SHIFT]
Results: map[Output:arch/loongarch/mm/page.S=12=SYM_FUNC_START(clear_page)
arch/loongarch/mm/page.S:13: lu12i.w t0, 1 << (PAGE_SHIFT - 12)
arch/loongarch/mm/page.S-14- PTR_ADD t0, t0, a0
--
arch/loongarch/mm/page.S=40=SYM_FUNC_START(copy_page)
arch/loongarch/mm/page.S:41: lu12i.w t8, 1 << (PAGE_SHIFT - 12)
arch/loongarch/mm/page.S-42- PTR_ADD t8, t8, a0
--
arch/sh/kernel/sys_sh.c=41=asmlinkage long sys_mmap2(unsigned long addr, unsigned long len,
--
arch/sh/kernel/sys_sh.c-48- */
arch/sh/kernel/sys_sh.c:49: if (pgoff & ((1 << (PAGE_SHIFT - 12)) - 1))
arch/sh/kernel/sys_sh.c-50- return -EINVAL;
--
drivers/block/zram/zram_drv.c=519=struct zram_rb_req {
--
drivers/block/zram/zram_drv.c-534-
drivers/block/zram/zram_drv.c:535:#define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
drivers/block/zram/zram_drv.c-536-static ssize_t bd_stat_show(struct device *dev, struct device_attribute *attr,
--
drivers/char/xillybus/xillyusb.c=487=static struct xillyusb_endpoint
--
drivers/char/xillybus/xillyusb.c-512- ep->order = order;
drivers/char/xillybus/xillyusb.c:513: ep->buffer_size = 1 << (PAGE_SHIFT + order);
drivers/char/xillybus/xillyusb.c-514- ep->outstanding_urbs = 0;
--
drivers/crypto/ccp/sev-dev.c=2177=static int sev_ioctl_do_get_id2(struct sev_issue_cmd *argp)
--
drivers/crypto/ccp/sev-dev.c-2197- * it may change in the future. The allocation size is limited
drivers/crypto/ccp/sev-dev.c:2198: * to 1 << (PAGE_SHIFT + MAX_PAGE_ORDER) by the page allocator.
drivers/crypto/ccp/sev-dev.c-2199- * If the allocation fails, simply return ENOMEM rather than
--
drivers/crypto/hisilicon/sgl.c=57=struct hisi_acc_sgl_pool *hisi_acc_create_sgl_pool(struct device *dev,
--
drivers/crypto/hisilicon/sgl.c-75- */
drivers/crypto/hisilicon/sgl.c:76: block_size = 1 << (PAGE_SHIFT + MAX_PAGE_ORDER < 32 ?
drivers/crypto/hisilicon/sgl.c-77- PAGE_SHIFT + MAX_PAGE_ORDER : 31);
--
drivers/net/ethernet/mellanox/mlx4/main.c=292=static inline void mlx4_set_num_reserved_uars(struct mlx4_dev *dev,
--
drivers/net/ethernet/mellanox/mlx4/main.c-302- dev_cap->reserved_uars /
drivers/net/ethernet/mellanox/mlx4/main.c:303: (1 << (PAGE_SHIFT - dev->uar_page_shift)));
drivers/net/ethernet/mellanox/mlx4/main.c-304-}
--
drivers/net/ethernet/sun/niu.c=4441=static void niu_size_rbr(struct niu *np, struct rx_ring_info *rp)
--
drivers/net/ethernet/sun/niu.c-4447- rp->rbr_block_size = 1 << bss;
drivers/net/ethernet/sun/niu.c:4448: rp->rbr_blocks_per_page = 1 << (PAGE_SHIFT-bss);
drivers/net/ethernet/sun/niu.c-4449-
--
drivers/scsi/sg.c=1217=sg_vma_fault(struct vm_fault *vmf)
--
drivers/scsi/sg.c-1234- sa = vma->vm_start;
drivers/scsi/sg.c:1235: length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
drivers/scsi/sg.c-1236- for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
--
drivers/scsi/sg.c=1257=sg_mmap(struct file *filp, struct vm_area_struct *vma)
--
drivers/scsi/sg.c-1280- sa = vma->vm_start;
drivers/scsi/sg.c:1281: length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
drivers/scsi/sg.c-1282- for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
--
drivers/scsi/sg.c=1855=sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
--
drivers/scsi/sg.c-1887-retry:
drivers/scsi/sg.c:1888: ret_sz = 1 << (PAGE_SHIFT + order);
drivers/scsi/sg.c-1889-
--
drivers/scsi/sg.c=1956=sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
--
drivers/scsi/sg.c-1966-
drivers/scsi/sg.c:1967: num = 1 << (PAGE_SHIFT + schp->page_order);
drivers/scsi/sg.c-1968- for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
--
drivers/scsi/sg.c=2007=sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
--
drivers/scsi/sg.c-2017-
drivers/scsi/sg.c:2018: num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
drivers/scsi/sg.c-2019- for (k = 0; k < rsv_schp->k_use_sg; k++) {
--
fs/hfs/inode.c=67=static bool hfs_release_folio(struct folio *folio, gfp_t mask)
--
fs/hfs/inode.c-106- nidx = folio->index << (PAGE_SHIFT - tree->node_size_shift);
fs/hfs/inode.c:107: i = 1 << (PAGE_SHIFT - tree->node_size_shift);
fs/hfs/inode.c-108- spin_lock(&tree->hash_lock);
--
fs/hfsplus/inode.c=62=static bool hfsplus_release_folio(struct folio *folio, gfp_t mask)
--
fs/hfsplus/inode.c-104- (PAGE_SHIFT - tree->node_size_shift);
fs/hfsplus/inode.c:105: i = 1 << (PAGE_SHIFT - tree->node_size_shift);
fs/hfsplus/inode.c-106- spin_lock(&tree->hash_lock);
--
fs/jbd2/journal.c=2675=int jbd2_journal_blocks_per_folio(struct inode *inode)
fs/jbd2/journal.c-2676-{
fs/jbd2/journal.c:2677: return 1 << (PAGE_SHIFT + mapping_max_folio_order(inode->i_mapping) -
fs/jbd2/journal.c-2678- inode->i_sb->s_blocksize_bits);
--
fs/nilfs2/file.c=46=static vm_fault_t nilfs_page_mkwrite(struct vm_fault *vmf)
--
fs/nilfs2/file.c-106- }
fs/nilfs2/file.c:107: nilfs_set_file_dirty(inode, 1 << (PAGE_SHIFT - inode->i_blkbits));
fs/nilfs2/file.c-108- nilfs_transaction_commit(inode->i_sb);
--
fs/ocfs2/aops.c=489=static void ocfs2_figure_cluster_boundaries(struct ocfs2_super *osb,
--
fs/ocfs2/aops.c-498-
fs/ocfs2/aops.c:499: cpp = 1 << (PAGE_SHIFT - osb->s_clustersize_bits);
fs/ocfs2/aops.c-500-
--
fs/ocfs2/aops.c=1094=static int ocfs2_write_cluster(struct address_space *mapping,
--
fs/ocfs2/aops.c-1171- if (wc->w_folios[i] == NULL) {
fs/ocfs2/aops.c:1172: p_blkno += (1 << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits));
fs/ocfs2/aops.c-1173- continue;
--
fs/ufs/balloc.c=234=static void ufs_change_blocknr(struct inode *inode, sector_t beg,
--
fs/ufs/balloc.c-239- const unsigned blks_per_page =
fs/ufs/balloc.c:240: 1 << (PAGE_SHIFT - inode->i_blkbits);
fs/ufs/balloc.c-241- const unsigned mask = blks_per_page - 1;
--
fs/ufs/inode.c=1033=static int ufs_alloc_lastblock(struct inode *inode, loff_t size)
--
fs/ufs/inode.c-1058-
fs/ufs/inode.c:1059: end = lastfrag & ((1 << (PAGE_SHIFT - inode->i_blkbits)) - 1);
fs/ufs/inode.c-1060- bh = folio_buffers(folio);
--
include/linux/blkdev.h=276=static inline dev_t disk_devt(struct gendisk *disk)
--
include/linux/blkdev.h-282-/*
include/linux/blkdev.h:283: * We should strive for 1 << (PAGE_SHIFT + MAX_PAGECACHE_ORDER)
include/linux/blkdev.h-284- * however we constrain this to what we can validate and test.
--
kernel/dma/pool.c=79=static int atomic_pool_expand(struct gen_pool *pool, size_t pool_size,
--
kernel/dma/pool.c-90- do {
kernel/dma/pool.c:91: pool_size = 1 << (PAGE_SHIFT + order);
kernel/dma/pool.c-92- if (cma_in_zone(gfp))
--
kernel/dma/swiotlb.c-55-
kernel/dma/swiotlb.c:56:#define SLABS_PER_PAGE (1 << (PAGE_SHIFT - IO_TLB_SHIFT))
kernel/dma/swiotlb.c-57-
--
mm/execmem.c=89=struct execmem_cache {
--
mm/execmem.c-99-/* mark entries in busy_areas that should be freed asynchronously */
mm/execmem.c:100:#define PENDING_FREE_MASK (1 << (PAGE_SHIFT - 1))
mm/execmem.c-101-
]
|
| 57/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 42549
output: 43
thoughts: 355
Thoughts: **Analyzing Potential Integer Overflow in `drivers/scsi/sg.c`**
Okay, so I'm digging into `drivers/scsi/sg.c` and immediately spot a pattern: multiple instances of `1 << (PAGE_SHIFT + order)`. My initial thought is to scrutinize each one. Let's start with `sg_vma_fault`:
```c
length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
```
Then `sg_mmap`:
```c
length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
```
And `sg_read_oxfer`:
```c
num = 1 << (PAGE_SHIFT + schp->page_order);
```
Followed by `sg_link_reserve`:
```c
num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
```
Aha! `page_order` is the *actual* allocation order. It should be constrained by `MAX_PAGE_ORDER`, right? Okay, so that's either 10 or 11. That means `PAGE_SHIFT + page_order` will be at most `12 + 11 = 23`. Therefore, `1 << 23` is completely within the safe bounds of a 32-bit signed integer. It won't overflow or cause any undefined behavior here. It was the issue in `sg_build_indirect` that made `order` be 52 that triggered undefined behavior, due to `get_order(0)`.
Now, the question is: even though it's safe, should I make these consistent for the sake of clarity? `PAGE_SIZE << order` is arguably more readable, and it may be worth it for consistency. Now let's see about `sg_vma_fault` again.
|
| 58/4 |
2026/05/20 22:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c IncludeLines:true Name:sg_vma_fault]
Results: map[SourceCode:1216: static vm_fault_t
1217: sg_vma_fault(struct vm_fault *vmf)
1218: {
1219: struct vm_area_struct *vma = vmf->vma;
1220: Sg_fd *sfp;
1221: unsigned long offset, len, sa;
1222: Sg_scatter_hold *rsv_schp;
1223: int k, length;
1224:
1225: if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
1226: return VM_FAULT_SIGBUS;
1227: rsv_schp = &sfp->reserve;
1228: offset = vmf->pgoff << PAGE_SHIFT;
1229: if (offset >= rsv_schp->bufflen)
1230: return VM_FAULT_SIGBUS;
1231: SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
1232: "sg_vma_fault: offset=%lu, scatg=%d\n",
1233: offset, rsv_schp->k_use_sg));
1234: sa = vma->vm_start;
1235: length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
1236: for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
1237: len = vma->vm_end - sa;
1238: len = (len < length) ? len : length;
1239: if (offset < len) {
1240: struct page *page = rsv_schp->pages[k] + (offset >> PAGE_SHIFT);
1241: get_page(page); /* increment page count */
1242: vmf->page = page;
1243: return 0; /* success */
1244: }
1245: sa += len;
1246: offset -= len;
1247: }
1248:
1249: return VM_FAULT_SIGBUS;
1250: }
SourceFile:drivers/scsi/sg.c]
|
| 59/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 44012
output: 41
thoughts: 80
Thoughts: **Analyzing Memory Allocation Logic**
Okay, so I'm looking at this line: `length = 1 << (PAGE_SHIFT + rsv_schp->page_order);`. I can see that this calculates the length, and the use of the left bit-shift operation seems fine here. Given that `page_order` has a defined maximum, `MAX_PAGE_ORDER`, this particular expression shouldn't cause any issues from a numerical perspective. It should be safe. However, my immediate thought is that it could be made more readable and less prone to subtle errors, and the intent would be clearer with a direct multiplication.
I think changing it to `PAGE_SIZE << rsv_schp->page_order` is more straightforward and expresses the scaling based on page order more explicitly. It's a cleaner representation, and for something like memory calculation where clarity is paramount, I lean toward this option. Before I commit to anything, I want to confirm that this change doesn't break any existing function calls. I should check `sg_mmap` to see where it might be being used.
|
| 60/4 |
2026/05/20 22:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c IncludeLines:true Name:sg_mmap]
Results: map[SourceCode:1256: static int
1257: sg_mmap(struct file *filp, struct vm_area_struct *vma)
1258: {
1259: Sg_fd *sfp;
1260: unsigned long req_sz, len, sa;
1261: Sg_scatter_hold *rsv_schp;
1262: int k, length;
1263: int ret = 0;
1264:
1265: if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
1266: return -ENXIO;
1267: req_sz = vma->vm_end - vma->vm_start;
1268: SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
1269: "sg_mmap starting, vm_start=%p, len=%d\n",
1270: (void *) vma->vm_start, (int) req_sz));
1271: if (vma->vm_pgoff)
1272: return -EINVAL; /* want no offset */
1273: rsv_schp = &sfp->reserve;
1274: mutex_lock(&sfp->f_mutex);
1275: if (req_sz > rsv_schp->bufflen) {
1276: ret = -ENOMEM; /* cannot map more than reserved buffer */
1277: goto out;
1278: }
1279:
1280: sa = vma->vm_start;
1281: length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
1282: for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) {
1283: len = vma->vm_end - sa;
1284: len = (len < length) ? len : length;
1285: sa += len;
1286: }
1287:
1288: sfp->mmap_called = 1;
1289: vm_flags_set(vma, VM_IO | VM_DONTEXPAND | VM_DONTDUMP);
1290: vma->vm_private_data = sfp;
1291: vma->vm_ops = &sg_mmap_vm_ops;
1292: out:
1293: mutex_unlock(&sfp->f_mutex);
1294: return ret;
1295: }
SourceFile:drivers/scsi/sg.c]
|
| 61/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 45109
output: 43
thoughts: 12
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Initial Assessment: A Focused Query**
Right, let's start with a specific point. I'm going to take a look at `sg_read_oxfer`. I immediately think "read" and "oxfer", so it would appear to be a function, likely within our system, that is intended to read something, perhaps a structure or a file, associated with "oxfer". Given my familiarity with our codebase and data infrastructure, I know "oxfer" is likely a core element. Itโs either a file format, a data structure, or some critical piece of our infrastructure thatโs associated with "oxfer". The term "sg" suggests this could be part of a sub-group, or potentially even "Storage Group" -- indicating this function is likely dealing with data persistence, reading from storage itself, or handling interactions with an external system. I need to understand what this `sg_read_oxfer` call is attempting to do, and I'll immediately start from there.
|
| 62/4 |
2026/05/20 22:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c IncludeLines:true Name:sg_read_oxfer]
Results: map[SourceCode:1955: static int
1956: sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
1957: {
1958: Sg_scatter_hold *schp = &srp->data;
1959: int k, num;
1960:
1961: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,
1962: "sg_read_oxfer: num_read_xfer=%d\n",
1963: num_read_xfer));
1964: if ((!outp) || (num_read_xfer <= 0))
1965: return 0;
1966:
1967: num = 1 << (PAGE_SHIFT + schp->page_order);
1968: for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) {
1969: if (num > num_read_xfer) {
1970: if (copy_to_user(outp, page_address(schp->pages[k]),
1971: num_read_xfer))
1972: return -EFAULT;
1973: break;
1974: } else {
1975: if (copy_to_user(outp, page_address(schp->pages[k]),
1976: num))
1977: return -EFAULT;
1978: num_read_xfer -= num;
1979: if (num_read_xfer <= 0)
1980: break;
1981: outp += num;
1982: }
1983: }
1984:
1985: return 0;
1986: }
SourceFile:drivers/scsi/sg.c]
|
| 63/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 45944
output: 42
thoughts: 11
Thoughts: Okay, here's my attempt at summarizing that thought process, keeping in mind I'm speaking to an expert:
**Checking `sg_link_reserve`**
Right, let's take a look at `sg_link_reserve`. I'm starting here because... well, I suspect there might be something happening related to that particular function or variable. It's usually the first place I look when dealing with this kind of issue, knowing the system like I do. I have a hunch, based on the recent changes and the symptoms we're observing, that it's likely involved. Time to see if the values make sense, if it's behaving as expected, and whether it's the root cause or just another data point. Gotta verify my assumptions.
|
| 64/4 |
2026/05/20 22:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/scsi/sg.c IncludeLines:true Name:sg_link_reserve]
Results: map[SourceCode:2006: static void
2007: sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
2008: {
2009: Sg_scatter_hold *req_schp = &srp->data;
2010: Sg_scatter_hold *rsv_schp = &sfp->reserve;
2011: int k, num, rem;
2012:
2013: srp->res_used = 1;
2014: SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
2015: "sg_link_reserve: size=%d\n", size));
2016: rem = size;
2017:
2018: num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
2019: for (k = 0; k < rsv_schp->k_use_sg; k++) {
2020: if (rem <= num) {
2021: req_schp->k_use_sg = k + 1;
2022: req_schp->sglist_len = rsv_schp->sglist_len;
2023: req_schp->pages = rsv_schp->pages;
2024:
2025: req_schp->bufflen = size;
2026: req_schp->page_order = rsv_schp->page_order;
2027: break;
2028: } else
2029: rem -= num;
2030: }
2031:
2032: if (k >= rsv_schp->k_use_sg)
2033: SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
2034: "sg_link_reserve: BAD size\n"));
2035: }
SourceFile:drivers/scsi/sg.c]
|
| 65/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 46717
output: 17
thoughts: 272
Thoughts: **Analyzing Potential Overflow and `get_order` Calls**
Okay, let's break this down. Because `page_order` is capped by `MAX_PAGE_ORDER`, which is either 10 or 11, the expression `PAGE_SHIFT + page_order` will never exceed 23. This means that `1 << 23` evaluates to 8388608, which is easily representable within a 32-bit signed integer. I'm certain there's no overflow or undefined behavior in those sections of code.
Though, for consistency's sake, perhaps I should change them to `PAGE_SIZE << ...`, but it's not strictly a bug to fix. The real issue was definitely in `sg_build_indirect` because `order` could hit 52 due to `get_order(0)`. The `get_order(0)` call was possible because `num` wasn't updated to `PAGE_SIZE` when `scatter_elem_sz` was 0. That's the core problem.
Wait a minute, I need to be thorough. Is there *any* other place in the code where `get_order` is called with a value that could potentially be zero? Now that I've ensured `num` is updated to at least `PAGE_SIZE` in `sg_build_indirect`, I'm confident `get_order(num)` will never receive 0 there. I need to make sure though. Are there any other invocations of `get_order` within `sg.c`? That's the question I need to answer.
|
| 66/4 |
2026/05/20 22:40 |
tool |
grepper |
0m
Args: map[Expression:get_order]
Results: map[Output:
Full output is too long, showing 500 out of 3130 lines.
Use more precise expression if possible.
[arch/alpha/kernel/pci_iommu.c=405=static void *alpha_pci_alloc_coherent(struct device *dev, size_t size,
--
arch/alpha/kernel/pci_iommu.c-410- void *cpu_addr;
arch/alpha/kernel/pci_iommu.c:411: long order = get_order(size);
arch/alpha/kernel/pci_iommu.c-412-
--
arch/alpha/kernel/pci_iommu.c=450=static void alpha_pci_free_coherent(struct device *dev, size_t size,
--
arch/alpha/kernel/pci_iommu.c-455- dma_unmap_single(&pdev->dev, dma_addr, size, DMA_BIDIRECTIONAL);
arch/alpha/kernel/pci_iommu.c:456: free_pages((unsigned long)cpu_addr, get_order(size));
arch/alpha/kernel/pci_iommu.c-457-
--
arch/arm/mm/dma-mapping.c=141=static struct page *__dma_alloc_buffer(struct device *dev, size_t size,
--
arch/arm/mm/dma-mapping.c-143-{
arch/arm/mm/dma-mapping.c:144: unsigned long order = get_order(size);
arch/arm/mm/dma-mapping.c-145- struct page *page, *p, *e;
--
arch/arm/mm/dma-mapping.c=391=static void *__alloc_from_contiguous(struct device *dev, size_t size,
--
arch/arm/mm/dma-mapping.c-395-{
arch/arm/mm/dma-mapping.c:396: unsigned long order = get_order(size);
arch/arm/mm/dma-mapping.c-397- size_t count = size >> PAGE_SHIFT;
--
arch/arm/mm/dma-mapping.c=754=static inline dma_addr_t __alloc_iova(struct dma_iommu_mapping *mapping,
--
arch/arm/mm/dma-mapping.c-756-{
arch/arm/mm/dma-mapping.c:757: unsigned int order = get_order(size);
arch/arm/mm/dma-mapping.c-758- unsigned int align = 0;
--
arch/arm/mm/dma-mapping.c=850=static struct page **__iommu_alloc_buffer(struct device *dev, size_t size,
--
arch/arm/mm/dma-mapping.c-865- {
arch/arm/mm/dma-mapping.c:866: unsigned long order = get_order(size);
arch/arm/mm/dma-mapping.c-867- struct page *page;
--
arch/arm/mm/mmu.c=726=static void *__init late_alloc(unsigned long sz)
--
arch/arm/mm/mmu.c-728- void *ptdesc = pagetable_alloc(GFP_PGTABLE_KERNEL & ~__GFP_HIGHMEM,
arch/arm/mm/mmu.c:729: get_order(sz));
arch/arm/mm/mmu.c-730-
--
arch/arm64/kvm/arm.c=2066=static unsigned long nvhe_percpu_order(void)
--
arch/arm64/kvm/arm.c-2069-
arch/arm64/kvm/arm.c:2070: return size ? get_order(size) : 0;
arch/arm64/kvm/arm.c-2071-}
--
arch/arm64/kvm/arm.c=2073=static size_t pkvm_host_sve_state_order(void)
arch/arm64/kvm/arm.c-2074-{
arch/arm64/kvm/arm.c:2075: return get_order(pkvm_host_sve_state_size());
arch/arm64/kvm/arm.c-2076-}
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c=84=static void *host_s2_zalloc_pages_exact(size_t size)
arch/arm64/kvm/hyp/nvhe/mem_protect.c-85-{
arch/arm64/kvm/hyp/nvhe/mem_protect.c:86: void *addr = hyp_alloc_pages(&host_s2_pool, get_order(size));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-87-
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c-94- */
arch/arm64/kvm/hyp/nvhe/mem_protect.c:95: WARN_ON(size != (PAGE_SIZE << get_order(size)));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-96-
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c=185=static void *guest_s2_zalloc_pages_exact(size_t size)
arch/arm64/kvm/hyp/nvhe/mem_protect.c-186-{
arch/arm64/kvm/hyp/nvhe/mem_protect.c:187: void *addr = hyp_alloc_pages(¤t_vm->pool, get_order(size));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-188-
arch/arm64/kvm/hyp/nvhe/mem_protect.c:189: WARN_ON(size != (PAGE_SIZE << get_order(size)));
arch/arm64/kvm/hyp/nvhe/mem_protect.c-190- hyp_split_page(hyp_virt_to_page(addr));
--
arch/arm64/kvm/hyp/nvhe/mem_protect.c=195=static void guest_s2_free_pages_exact(void *addr, unsigned long size)
arch/arm64/kvm/hyp/nvhe/mem_protect.c-196-{
arch/arm64/kvm/hyp/nvhe/mem_protect.c:197: u8 order = get_order(size);
arch/arm64/kvm/hyp/nvhe/mem_protect.c-198- unsigned int i;
--
arch/arm64/kvm/hyp/nvhe/page_alloc.c=223=int hyp_pool_init(struct hyp_pool *pool, u64 pfn, unsigned int nr_pages,
--
arch/arm64/kvm/hyp/nvhe/page_alloc.c-231- pool->max_order = min(MAX_PAGE_ORDER,
arch/arm64/kvm/hyp/nvhe/page_alloc.c:232: get_order(nr_pages << PAGE_SHIFT));
arch/arm64/kvm/hyp/nvhe/page_alloc.c-233- for (i = 0; i <= pool->max_order; i++)
--
arch/arm64/mm/mmu.c=1431=static void free_hotplug_page_range(struct page *page, size_t size,
--
arch/arm64/mm/mmu.c-1437- WARN_ON(PageReserved(page));
arch/arm64/mm/mmu.c:1438: __free_pages(page, get_order(size));
arch/arm64/mm/mmu.c-1439- }
--
arch/loongarch/kernel/irq.c=108=void __init init_IRQ(void)
--
arch/loongarch/kernel/irq.c-110- int i;
arch/loongarch/kernel/irq.c:111: unsigned int order = get_order(IRQ_STACK_SIZE);
arch/loongarch/kernel/irq.c-112- struct page *page;
--
arch/loongarch/mm/tlb.c=266=static void setup_tlb_handler(int cpu)
--
arch/loongarch/mm/tlb.c-298-
arch/loongarch/mm/tlb.c:299: page = alloc_pages_node(cpu_to_node(cpu), GFP_ATOMIC, get_order(vec_sz));
arch/loongarch/mm/tlb.c-300- if (!page)
--
arch/m68k/sun3/sun3dvma.c=317=void *dvma_malloc_align(unsigned long len, unsigned long align)
--
arch/m68k/sun3/sun3dvma.c-328-
arch/m68k/sun3/sun3dvma.c:329: if((kaddr = __get_free_pages(GFP_ATOMIC, get_order(len))) == 0)
arch/m68k/sun3/sun3dvma.c-330- return NULL;
--
arch/m68k/sun3/sun3dvma.c-332- if((baddr = (unsigned long)dvma_map_align(kaddr, len, align)) == 0) {
arch/m68k/sun3/sun3dvma.c:333: free_pages(kaddr, get_order(len));
arch/m68k/sun3/sun3dvma.c-334- return NULL;
--
arch/m68k/sun3/sun3dvma.c-340- dvma_unmap((void *)baddr);
arch/m68k/sun3/sun3dvma.c:341: free_pages(kaddr, get_order(len));
arch/m68k/sun3/sun3dvma.c-342- return NULL;
--
arch/mips/include/asm/mach-generic/floppy.h=115=static inline unsigned long fd_dma_mem_alloc(unsigned long size)
arch/mips/include/asm/mach-generic/floppy.h-116-{
arch/mips/include/asm/mach-generic/floppy.h:117: return __get_dma_pages(GFP_KERNEL, get_order(size));
arch/mips/include/asm/mach-generic/floppy.h-118-}
--
arch/mips/include/asm/mach-generic/floppy.h=120=static inline void fd_dma_mem_free(unsigned long addr, unsigned long size)
arch/mips/include/asm/mach-generic/floppy.h-121-{
arch/mips/include/asm/mach-generic/floppy.h:122: free_pages(addr, get_order(size));
arch/mips/include/asm/mach-generic/floppy.h-123-}
--
arch/mips/include/asm/mach-jazz/floppy.h=104=static inline unsigned long fd_dma_mem_alloc(unsigned long size)
--
arch/mips/include/asm/mach-jazz/floppy.h-107-
arch/mips/include/asm/mach-jazz/floppy.h:108: mem = __get_dma_pages(GFP_KERNEL, get_order(size));
arch/mips/include/asm/mach-jazz/floppy.h-109- if(!mem)
--
arch/mips/include/asm/mach-jazz/floppy.h=116=static inline void fd_dma_mem_free(unsigned long addr, unsigned long size)
--
arch/mips/include/asm/mach-jazz/floppy.h-118- vdma_free(vdma_phys2log(CPHYSADDR(addr)));
arch/mips/include/asm/mach-jazz/floppy.h:119: free_pages(addr, get_order(size));
arch/mips/include/asm/mach-jazz/floppy.h-120-}
--
arch/mips/jazz/jazzdma.c=64=static int __init vdma_init(void)
--
arch/mips/jazz/jazzdma.c-71- pgtbl = (VDMA_PGTBL_ENTRY *)__get_free_pages(GFP_KERNEL | GFP_DMA,
arch/mips/jazz/jazzdma.c:72: get_order(VDMA_PGTBL_SIZE));
arch/mips/jazz/jazzdma.c-73- BUG_ON(!pgtbl);
--
arch/mips/jazz/jazzdma.c=491=static void *jazz_dma_alloc(struct device *dev, size_t size,
--
arch/mips/jazz/jazzdma.c-500- size = PAGE_ALIGN(size);
arch/mips/jazz/jazzdma.c:501: page = alloc_pages(gfp, get_order(size));
arch/mips/jazz/jazzdma.c-502- if (!page)
--
arch/mips/jazz/jazzdma.c-512-out_free_pages:
arch/mips/jazz/jazzdma.c:513: __free_pages(page, get_order(size));
arch/mips/jazz/jazzdma.c-514- return NULL;
--
arch/mips/jazz/jazzdma.c=517=static void jazz_dma_free(struct device *dev, size_t size, void *vaddr,
--
arch/mips/jazz/jazzdma.c-520- vdma_free(dma_handle);
arch/mips/jazz/jazzdma.c:521: __free_pages(virt_to_page(vaddr), get_order(size));
arch/mips/jazz/jazzdma.c-522-}
--
arch/mips/kernel/irq.c=53=void __init init_IRQ(void)
--
arch/mips/kernel/irq.c-55- int i;
arch/mips/kernel/irq.c:56: unsigned int order = get_order(IRQ_STACK_SIZE);
arch/mips/kernel/irq.c-57-
--
arch/parisc/include/asm/floppy.h=151=static unsigned long dma_mem_alloc(unsigned long size)
arch/parisc/include/asm/floppy.h-152-{
arch/parisc/include/asm/floppy.h:153: return __get_dma_pages(GFP_KERNEL, get_order(size));
arch/parisc/include/asm/floppy.h-154-}
--
arch/parisc/include/asm/floppy.h=165=static void _fd_dma_mem_free(unsigned long addr, unsigned long size)
--
arch/parisc/include/asm/floppy.h-169- else
arch/parisc/include/asm/floppy.h:170: free_pages(addr, get_order(size));
arch/parisc/include/asm/floppy.h-171-}
--
arch/parisc/kernel/pci-dma.c-33-#include <asm/io.h>
arch/parisc/kernel/pci-dma.c:34:#include <asm/page.h> /* get_order */
arch/parisc/kernel/pci-dma.c-35-#include <linux/uaccess.h>
--
arch/parisc/kernel/pci-dma.c=374=pcxl_dma_init(void)
--
arch/parisc/kernel/pci-dma.c-381- pcxl_res_map = (char *)__get_free_pages(GFP_KERNEL,
arch/parisc/kernel/pci-dma.c:382: get_order(pcxl_res_size));
arch/parisc/kernel/pci-dma.c-383- memset(pcxl_res_map, 0, pcxl_res_size);
--
arch/parisc/kernel/pci-dma.c=401=void *arch_dma_alloc(struct device *dev, size_t size,
--
arch/parisc/kernel/pci-dma.c-410-
arch/parisc/kernel/pci-dma.c:411: order = get_order(size);
arch/parisc/kernel/pci-dma.c-412- size = 1 << (order + PAGE_SHIFT);
--
arch/parisc/kernel/pci-dma.c=423=void arch_dma_free(struct device *dev, size_t size, void *vaddr,
--
arch/parisc/kernel/pci-dma.c-425-{
arch/parisc/kernel/pci-dma.c:426: int order = get_order(size);
arch/parisc/kernel/pci-dma.c-427-
--
arch/powerpc/include/asm/iommu.h=96=struct iommu_table {
--
arch/powerpc/include/asm/iommu.h-126-
arch/powerpc/include/asm/iommu.h:127:/* Pure 2^n version of get_order */
arch/powerpc/include/asm/iommu.h-128-static inline __attribute_const__
--
arch/powerpc/kernel/iommu.c=912=void *iommu_alloc_coherent(struct device *dev, struct iommu_table *tbl,
--
arch/powerpc/kernel/iommu.c-923- size = PAGE_ALIGN(size);
arch/powerpc/kernel/iommu.c:924: order = get_order(size);
arch/powerpc/kernel/iommu.c-925-
--
arch/powerpc/kernel/iommu.c=962=void iommu_free_coherent(struct iommu_table *tbl, size_t size,
--
arch/powerpc/kernel/iommu.c-971- size = PAGE_ALIGN(size);
arch/powerpc/kernel/iommu.c:972: free_pages((unsigned long)vaddr, get_order(size));
arch/powerpc/kernel/iommu.c-973- }
--
arch/powerpc/mm/book3s64/radix_pgtable.c=820=static void __meminit remove_pmd_table(pmd_t *pmd_start, unsigned long addr,
--
arch/powerpc/mm/book3s64/radix_pgtable.c-838- if (!direct)
arch/powerpc/mm/book3s64/radix_pgtable.c:839: free_vmemmap_pages(pmd_page(*pmd), altmap, get_order(PMD_SIZE));
arch/powerpc/mm/book3s64/radix_pgtable.c-840- pte_clear(&init_mm, addr, (pte_t *)pmd);
--
arch/powerpc/mm/book3s64/radix_pgtable.c-844- else if (!direct && vmemmap_pmd_is_unused(addr, next)) {
arch/powerpc/mm/book3s64/radix_pgtable.c:845: free_vmemmap_pages(pmd_page(*pmd), altmap, get_order(PMD_SIZE));
arch/powerpc/mm/book3s64/radix_pgtable.c-846- pte_clear(&init_mm, addr, (pte_t *)pmd);
--
arch/powerpc/mm/init_64.c=203=static int __meminit __vmemmap_populate(unsigned long start, unsigned long end, int node,
--
arch/powerpc/mm/init_64.c-253- int nr_pfns = page_size >> PAGE_SHIFT;
arch/powerpc/mm/init_64.c:254: unsigned long page_order = get_order(page_size);
arch/powerpc/mm/init_64.c-255-
--
arch/powerpc/mm/init_64.c=320=static void __ref __vmemmap_free(unsigned long start, unsigned long end,
--
arch/powerpc/mm/init_64.c-323- unsigned long page_size = 1 << mmu_psize_defs[mmu_vmemmap_psize].shift;
arch/powerpc/mm/init_64.c:324: unsigned long page_order = get_order(page_size);
arch/powerpc/mm/init_64.c-325- unsigned long alt_start = ~0, alt_end = ~0;
--
arch/powerpc/perf/imc-pmu.c=599=static int core_imc_mem_init(int cpu, int size)
--
arch/powerpc/perf/imc-pmu.c-615- GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
arch/powerpc/perf/imc-pmu.c:616: __GFP_NOWARN, get_order(size));
arch/powerpc/perf/imc-pmu.c-617- if (!page)
--
arch/powerpc/perf/imc-pmu.c-627- if (rc) {
arch/powerpc/perf/imc-pmu.c:628: free_pages((u64)mem_info->vbase, get_order(size));
arch/powerpc/perf/imc-pmu.c-629- mem_info->vbase = NULL;
--
arch/powerpc/perf/imc-pmu.c=920=static int thread_imc_mem_alloc(int cpu_id, int size)
--
arch/powerpc/perf/imc-pmu.c-932- GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
arch/powerpc/perf/imc-pmu.c:933: __GFP_NOWARN, get_order(size));
arch/powerpc/perf/imc-pmu.c-934- if (!page)
--
arch/powerpc/perf/imc-pmu.c=1205=static int trace_imc_mem_alloc(int cpu_id, int size)
--
arch/powerpc/perf/imc-pmu.c-1215- GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
arch/powerpc/perf/imc-pmu.c:1216: __GFP_NOWARN, get_order(size));
arch/powerpc/perf/imc-pmu.c-1217- if (!page)
--
arch/powerpc/perf/imc-pmu.c=1568=static void cleanup_all_core_imc_memory(void)
--
arch/powerpc/perf/imc-pmu.c-1576- if (ptr[i].vbase)
arch/powerpc/perf/imc-pmu.c:1577: free_pages((u64)ptr[i].vbase, get_order(size));
arch/powerpc/perf/imc-pmu.c-1578- }
--
arch/powerpc/perf/imc-pmu.c=1598=static void cleanup_all_thread_imc_memory(void)
arch/powerpc/perf/imc-pmu.c-1599-{
arch/powerpc/perf/imc-pmu.c:1600: int i, order = get_order(thread_imc_mem_size);
arch/powerpc/perf/imc-pmu.c-1601-
--
arch/powerpc/perf/imc-pmu.c=1609=static void cleanup_all_trace_imc_memory(void)
arch/powerpc/perf/imc-pmu.c-1610-{
arch/powerpc/perf/imc-pmu.c:1611: int i, order = get_order(trace_imc_mem_size);
arch/powerpc/perf/imc-pmu.c-1612-
--
arch/powerpc/platforms/cell/spufs/inode.c=633=static void spufs_exit_isolated_loader(void)
--
arch/powerpc/platforms/cell/spufs/inode.c-635- free_pages((unsigned long) isolated_loader,
arch/powerpc/platforms/cell/spufs/inode.c:636: get_order(isolated_loader_size));
arch/powerpc/platforms/cell/spufs/inode.c-637-}
--
arch/powerpc/platforms/cell/spufs/inode.c=640=spufs_init_isolated_loader(void)
--
arch/powerpc/platforms/cell/spufs/inode.c-655- /* the loader must be align on a 16 byte boundary */
arch/powerpc/platforms/cell/spufs/inode.c:656: isolated_loader = (char *)__get_free_pages(GFP_KERNEL, get_order(size));
arch/powerpc/platforms/cell/spufs/inode.c-657- if (!isolated_loader)
--
arch/powerpc/platforms/powernv/pci-ioda-tce.c=216=static void pnv_pci_ioda2_table_do_free_pages(__be64 *addr,
--
arch/powerpc/platforms/powernv/pci-ioda-tce.c-236-
arch/powerpc/platforms/powernv/pci-ioda-tce.c:237: free_pages(addr_ul, get_order(size << 3));
arch/powerpc/platforms/powernv/pci-ioda-tce.c-238-}
--
arch/powerpc/platforms/powernv/pci-ioda.c=1053=static int pnv_pci_ioda_dma_64bit_bypass(struct pnv_ioda_pe *pe)
--
arch/powerpc/platforms/powernv/pci-ioda.c-1072- table_pages = alloc_pages_node(pe->phb->hose->node, GFP_KERNEL,
arch/powerpc/platforms/powernv/pci-ioda.c:1073: get_order(table_size));
arch/powerpc/platforms/powernv/pci-ioda.c-1074- if (!table_pages)
--
arch/powerpc/platforms/ps3/system-bus.c=505=static void * ps3_alloc_coherent(struct device *_dev, size_t size,
--
arch/powerpc/platforms/ps3/system-bus.c-515-
arch/powerpc/platforms/ps3/system-bus.c:516: virt_addr = __get_free_pages(flag, get_order(size));
arch/powerpc/platforms/ps3/system-bus.c-517-
--
arch/powerpc/platforms/ps3/system-bus.c-536-clean_alloc:
arch/powerpc/platforms/ps3/system-bus.c:537: free_pages(virt_addr, get_order(size));
arch/powerpc/platforms/ps3/system-bus.c-538-clean_none:
--
arch/powerpc/platforms/ps3/system-bus.c=543=static void ps3_free_coherent(struct device *_dev, size_t size, void *vaddr,
--
arch/powerpc/platforms/ps3/system-bus.c-548- ps3_dma_unmap(dev->d_region, dma_handle, size);
arch/powerpc/platforms/ps3/system-bus.c:549: free_pages((unsigned long)vaddr, get_order(size));
arch/powerpc/platforms/ps3/system-bus.c-550-}
--
arch/riscv/kernel/unaligned_access_speed.c-20-#define MISALIGNED_BUFFER_SIZE 0x4000
arch/riscv/kernel/unaligned_access_speed.c:21:#define MISALIGNED_BUFFER_ORDER get_order(MISALIGNED_BUFFER_SIZE)
arch/riscv/kernel/unaligned_access_speed.c-22-#define MISALIGNED_COPY_SIZE ((MISALIGNED_BUFFER_SIZE / 2) - 0x80)
--
arch/riscv/kvm/aia_imsic.c=1090=int kvm_riscv_vcpu_aia_imsic_init(struct kvm_vcpu *vcpu)
--
arch/riscv/kvm/aia_imsic.c-1115- swfile_page = alloc_pages(GFP_KERNEL | __GFP_ZERO,
arch/riscv/kvm/aia_imsic.c:1116: get_order(sizeof(*imsic->swfile)));
arch/riscv/kvm/aia_imsic.c-1117- if (!swfile_page) {
--
arch/riscv/kvm/aia_imsic.c-1139- free_pages((unsigned long)imsic->swfile,
arch/riscv/kvm/aia_imsic.c:1140: get_order(sizeof(*imsic->swfile)));
arch/riscv/kvm/aia_imsic.c-1141-fail_free_imsic:
--
arch/riscv/kvm/aia_imsic.c=1147=void kvm_riscv_vcpu_aia_imsic_cleanup(struct kvm_vcpu *vcpu)
--
arch/riscv/kvm/aia_imsic.c-1161- free_pages((unsigned long)imsic->swfile,
arch/riscv/kvm/aia_imsic.c:1162: get_order(sizeof(*imsic->swfile)));
arch/riscv/kvm/aia_imsic.c-1163-
--
arch/riscv/kvm/mmu.c=536=int kvm_riscv_mmu_alloc_pgd(struct kvm *kvm)
--
arch/riscv/kvm/mmu.c-545- pgd_page = alloc_pages(GFP_KERNEL | __GFP_ZERO,
arch/riscv/kvm/mmu.c:546: get_order(kvm_riscv_gstage_pgd_size));
arch/riscv/kvm/mmu.c-547- if (!pgd_page)
--
arch/riscv/kvm/mmu.c=556=void kvm_riscv_mmu_free_pgd(struct kvm *kvm)
--
arch/riscv/kvm/mmu.c-573- if (pgd)
arch/riscv/kvm/mmu.c:574: free_pages((unsigned long)pgd, get_order(kvm_riscv_gstage_pgd_size));
arch/riscv/kvm/mmu.c-575-}
--
arch/riscv/kvm/nacl.c=81=void kvm_riscv_nacl_exit(void)
--
arch/riscv/kvm/nacl.c-95- free_pages((unsigned long)nacl->shmem,
arch/riscv/kvm/nacl.c:96: get_order(SBI_NACL_SHMEM_SIZE));
arch/riscv/kvm/nacl.c-97- nacl->shmem = NULL;
--
arch/riscv/kvm/nacl.c=114=int kvm_riscv_nacl_init(void)
--
arch/riscv/kvm/nacl.c-141- shmem_page = alloc_pages(GFP_KERNEL | __GFP_ZERO,
arch/riscv/kvm/nacl.c:142: get_order(SBI_NACL_SHMEM_SIZE));
arch/riscv/kvm/nacl.c-143- if (!shmem_page) {
--
arch/riscv/mm/init.c=1553=static void __meminit free_vmemmap_storage(struct page *page, size_t size,
--
arch/riscv/mm/init.c-1555-{
arch/riscv/mm/init.c:1556: int order = get_order(size);
arch/riscv/mm/init.c-1557-
--
arch/s390/kvm/gmap.c=701=int gmap_link(struct kvm_s390_mmu_cache *mc, struct gmap *gmap, struct guest_fault *f,
--
arch/s390/kvm/gmap.c-711- order = folio_order(page_folio(f->page));
arch/s390/kvm/gmap.c:712: if (order >= get_order(_REGION3_SIZE) && gmap_2g_allowed(gmap, f, slot))
arch/s390/kvm/gmap.c-713- level = TABLE_TYPE_REGION3;
arch/s390/kvm/gmap.c:714: else if (order >= get_order(_SEGMENT_SIZE) && gmap_1m_allowed(gmap, f, slot))
arch/s390/kvm/gmap.c-715- level = TABLE_TYPE_SEGMENT;
--
arch/s390/kvm/pci.c=52=static int zpci_setup_aipb(u8 nisc)
--
arch/s390/kvm/pci.c-66- zpci_aif_sbv = aift->sbv;
arch/s390/kvm/pci.c:67: size = get_order(PAGE_ALIGN(ZPCI_NR_DEVICES *
arch/s390/kvm/pci.c-68- sizeof(struct zpci_gaite)));
--
arch/s390/kvm/pv.c=228=int kvm_s390_pv_destroy_cpu(struct kvm_vcpu *vcpu, u16 *rc, u16 *rrc)
--
arch/s390/kvm/pv.c-243- free_pages(vcpu->arch.pv.stor_base,
arch/s390/kvm/pv.c:244: get_order(uv_info.guest_cpu_stor_len));
arch/s390/kvm/pv.c-245-
--
arch/s390/kvm/pv.c=262=int kvm_s390_pv_create_cpu(struct kvm_vcpu *vcpu, u16 *rc, u16 *rrc)
--
arch/s390/kvm/pv.c-274- vcpu->arch.pv.stor_base = __get_free_pages(GFP_KERNEL_ACCOUNT,
arch/s390/kvm/pv.c:275: get_order(uv_info.guest_cpu_stor_len));
arch/s390/kvm/pv.c-276- if (!vcpu->arch.pv.stor_base)
--
arch/s390/kvm/pv.c-288- free_pages(vcpu->arch.pv.stor_base,
arch/s390/kvm/pv.c:289: get_order(uv_info.guest_cpu_stor_len));
arch/s390/kvm/pv.c-290- return -ENOMEM;
--
arch/s390/kvm/pv.c=319=static void kvm_s390_pv_dealloc_vm(struct kvm *kvm)
--
arch/s390/kvm/pv.c-322- free_pages(kvm->arch.pv.stor_base,
arch/s390/kvm/pv.c:323: get_order(uv_info.guest_base_stor_len));
arch/s390/kvm/pv.c-324- kvm_s390_clear_pv_state(kvm);
--
arch/s390/kvm/pv.c=327=static int kvm_s390_pv_alloc_vm(struct kvm *kvm)
--
arch/s390/kvm/pv.c-333- kvm->arch.pv.stor_var = NULL;
arch/s390/kvm/pv.c:334: kvm->arch.pv.stor_base = __get_free_pages(GFP_KERNEL_ACCOUNT, get_order(base));
arch/s390/kvm/pv.c-335- if (!kvm->arch.pv.stor_base)
--
arch/s390/kvm/pv.c=376=static int kvm_s390_pv_dispose_one_leftover(struct kvm *kvm,
--
arch/s390/kvm/pv.c-395- */
arch/s390/kvm/pv.c:396: free_pages(leftover->stor_base, get_order(uv_info.guest_base_stor_len));
arch/s390/kvm/pv.c-397- free_pages(leftover->old_gmap_table, CRST_ALLOC_ORDER);
--
arch/s390/mm/vmem.c=168=static int __ref modify_pte_table(pmd_t *pmd, unsigned long addr,
--
arch/s390/mm/vmem.c-182- if (!direct)
arch/s390/mm/vmem.c:183: vmem_free_pages((unsigned long)pfn_to_virt(pte_pfn(*pte)), get_order(PAGE_SIZE), altmap);
arch/s390/mm/vmem.c-184- pte_clear(&init_mm, addr, pte);
--
arch/s390/mm/vmem.c=223=static int __ref modify_pmd_table(pud_t *pud, unsigned long addr,
--
arch/s390/mm/vmem.c-242- if (!direct)
arch/s390/mm/vmem.c:243: vmem_free_pages(pmd_deref(*pmd), get_order(PMD_SIZE), altmap);
arch/s390/mm/vmem.c-244- pmd_clear(pmd);
--
arch/s390/mm/vmem.c-246- } else if (!direct && vmemmap_unuse_sub_pmd(addr, next)) {
arch/s390/mm/vmem.c:247: vmem_free_pages(pmd_deref(*pmd), get_order(PMD_SIZE), altmap);
arch/s390/mm/vmem.c-248- pmd_clear(pmd);
--
arch/s390/mm/vmem.c=315=static int modify_pud_table(p4d_t *p4d, unsigned long addr, unsigned long end,
--
arch/s390/mm/vmem.c-333- if (!direct)
arch/s390/mm/vmem.c:334: vmem_free_pages(pud_deref(*pud), get_order(PUD_SIZE), altmap);
arch/s390/mm/vmem.c-335- pud_clear(pud);
--
arch/s390/pci/pci_clp.c=92=static void *clp_alloc_block(gfp_t gfp_mask)
arch/s390/pci/pci_clp.c-93-{
arch/s390/pci/pci_clp.c:94: return (void *) __get_free_pages(gfp_mask, get_order(CLP_BLK_SIZE));
arch/s390/pci/pci_clp.c-95-}
--
arch/s390/pci/pci_clp.c=97=static void clp_free_block(void *ptr)
arch/s390/pci/pci_clp.c-98-{
arch/s390/pci/pci_clp.c:99: free_pages((unsigned long) ptr, get_order(CLP_BLK_SIZE));
arch/s390/pci/pci_clp.c-100-}
--
arch/sh/kernel/cpu/sh4/sq.c=143=unsigned long sq_remap(unsigned long phys, unsigned int size,
--
arch/sh/kernel/cpu/sh4/sq.c-170- page = bitmap_find_free_region(sq_bitmap, 0x04000000 >> PAGE_SHIFT,
arch/sh/kernel/cpu/sh4/sq.c:171: get_order(map->size));
arch/sh/kernel/cpu/sh4/sq.c-172- if (unlikely(page < 0)) {
--
arch/sh/kernel/cpu/sh4/sq.c=207=void sq_unmap(unsigned long vaddr)
--
arch/sh/kernel/cpu/sh4/sq.c-222- page = (map->sq_addr - P4SEG_STORE_QUE) >> PAGE_SHIFT;
arch/sh/kernel/cpu/sh4/sq.c:223: bitmap_release_region(sq_bitmap, page, get_order(map->size));
arch/sh/kernel/cpu/sh4/sq.c-224-
--
arch/sparc/kernel/iommu.c=93=int iommu_table_init(struct iommu *iommu, int tsbsize,
--
arch/sparc/kernel/iommu.c-131- /* Now allocate and setup the IOMMU page table itself. */
arch/sparc/kernel/iommu.c:132: order = get_order(tsbsize);
arch/sparc/kernel/iommu.c-133- page = alloc_pages_node(numa_node, GFP_KERNEL, order);
--
arch/sparc/kernel/iommu.c=197=static void *dma_4u_alloc_coherent(struct device *dev, size_t size,
--
arch/sparc/kernel/iommu.c-208- size = IO_PAGE_ALIGN(size);
arch/sparc/kernel/iommu.c:209: order = get_order(size);
arch/sparc/kernel/iommu.c-210- if (order >= 10)
--
arch/sparc/kernel/iommu.c=246=static void dma_4u_free_coherent(struct device *dev, size_t size,
--
arch/sparc/kernel/iommu.c-257-
arch/sparc/kernel/iommu.c:258: order = get_order(size);
arch/sparc/kernel/iommu.c-259- if (order < 10)
--
arch/sparc/kernel/irq_64.c=1016=static void __init alloc_one_queue(unsigned long *pa_ptr, unsigned long qmask)
--
arch/sparc/kernel/irq_64.c-1018- unsigned long size = PAGE_ALIGN(qmask + 1);
arch/sparc/kernel/irq_64.c:1019: unsigned long order = get_order(size);
arch/sparc/kernel/irq_64.c-1020- unsigned long p;
--
arch/sparc/kernel/irq_64.c=1091=static void __init irq_ivector_init(void)
--
arch/sparc/kernel/irq_64.c-1103- size = sizeof(struct ino_bucket) * ivecs;
arch/sparc/kernel/irq_64.c:1104: order = get_order(size);
arch/sparc/kernel/irq_64.c-1105- ivector_table = (struct ino_bucket *)
--
arch/sparc/kernel/ldc.c=975=static int alloc_queue(const char *name, unsigned long num_entries,
--
arch/sparc/kernel/ldc.c-981- size = num_entries * LDC_PACKET_SIZE;
arch/sparc/kernel/ldc.c:982: order = get_order(size);
arch/sparc/kernel/ldc.c-983-
--
arch/sparc/kernel/ldc.c=999=static void free_queue(unsigned long num_entries, struct ldc_packet *q)
--
arch/sparc/kernel/ldc.c-1006- size = num_entries * LDC_PACKET_SIZE;
arch/sparc/kernel/ldc.c:1007: order = get_order(size);
arch/sparc/kernel/ldc.c-1008-
--
arch/sparc/kernel/ldc.c=1041=static int ldc_iommu_init(const char *name, struct ldc_channel *lp)
--
arch/sparc/kernel/ldc.c-1065-
]
]
|
| 67/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 59164
output: 165
thoughts: 1784
Thoughts: **Analyzing and Refining the Scatter/Gather Implementation**
Okay, so I've been digging into this `sg.c` code, specifically around the `sg_build_indirect` function. I initially fixed that `sg_build_indirect` bug, and it looks good, but let's thoroughly vet this.
I'm double-checking the size calculations. The key part is that `ret_sz` is an `int`, while `PAGE_SIZE << order` is an `unsigned long`. The assignment *seems* fine since we're casting down. But what happens if `PAGE_SIZE << order` overflows `INT_MAX`? I ran through the numbers. With a potential `order` of 19, `PAGE_SIZE << 19` gives us `-2147483648`, which is the negative of `INT_MAX + 1` due to the int overflow. The subsequent call to `alloc_pages` would then fail, which is correct, since the order will be decremented and tried again until it's smaller than `MAX_PAGE_ORDER`. When `order` reaches 10, the calculation will fit into the int range and we're good. So the `ret_sz` variable is okay here.
Next, I need to look for related issues. I'm focusing on where `scatter_elem_sz` is being used and could potentially cause problems. Looking again at `sg_build_indirect`:
```c
num = (rem_sz > scatter_elem_sz_prev) ?
scatter_elem_sz_prev : rem_sz;
```
`num` is limited by `rem_sz` which is limited by `blk_size`. `blk_size` is based on `buff_size`, passed from user space, but it's constrained by some max request size. The only potential concern is that the `buff_size` is an `int`. If `buff_size` is very large, the `blk_size` could be large, but `rem_sz` is at most `blk_size`, so `num` is always bounded.
But, what if `scatter_elem_sz` is set to a negative value or very large value? If `scatter_elem_sz` is `-1`, then `num` would become `-1`. The check in the `sg_build_indirect` code is there to prevent this, ensuring that it's no smaller than `PAGE_SIZE`. With a large number, say `0x7fffffff`, we calculate the order and, it overflows `INT_MAX`, and ends up as a large negative number. Again, the calculation of the order would handle this, the page allocation would fail, the order is decremented, and we're good. If `scatter_elem_sz` is `0x80000000`, which is the smallest `int`, then `num` becomes `PAGE_SIZE`, so we're safe. The fix *is* robust.
Now, let's craft an explanation for the fix. The initial explanation correctly identified the missing `num` update and the UB. However, the proposed fix of `1UL << (PAGE_SHIFT + order)` is also not correct. If `PAGE_SHIFT + order >= 64`, which happens when `get_order(0)` gives 52, and `PAGE_SHIFT` is 12 (52 + 12 = 64), then there is undefined behavior (shifting a 64-bit integer by 64 is UB in C). My fix is using `PAGE_SIZE << order`, which avoids this UB. I'm using `PAGE_SIZE << 52`, which is well-defined. The important point is that the local `num` variable is now updated in the code, which prevents us from ever calling `get_order(0)`, and so the UB is avoided. `PAGE_SIZE << order` is both idiomatic and mathematically accurate for describing the size of the allocation.
So, I'm going to explain this as follows:
1. The crucial fix involves the addition of the local variable update `num = PAGE_SIZE`, which addresses a missing update in the original code. This prevents the code from calling `get_order(0)`, which, when passed a small number, returns a large number due to integer underflow, and causes a shift-out-of-bounds error.
2. Instead of using the proposed `1UL << (PAGE_SHIFT + order)` fix, which is still subject to undefined behavior (UB), I'm changing the calculation to `PAGE_SIZE << order`. This is the preferred kernel idiom for computing an allocation size given its order, and it sidesteps potential UB that could
|
| 68/4 |
2026/05/20 22:40 |
tool |
codeeditor |
0m
Error:
Args: map[CurrentCode: sa = vma->vm_start;
length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { NewCode: sa = vma->vm_start;
length = PAGE_SIZE << rsv_schp->page_order;
for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { SourceFile:drivers/scsi/sg.c]
Results:
|
| 69/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 62166
output: 237
thoughts: 30
Thoughts: Okay, here's my take on those thoughts, framed as if they're my own:
**Analyzing the Function Match**
Right, so the results just flagged both `sg_vma_fault` and `sg_mmap`. Excellent. A double hit like that suggests there's a strong connection there. We're clearly dealing with something related to memory management, specifically how scatter-gather lists interact with virtual memory areas and memory mapping. Let's dig into each of those functions individually and see what the overlap tells us. This'll probably be key in understanding the deeper issue, and where the solution is going to lie.
|
| 70/4 |
2026/05/20 22:40 |
tool |
codeeditor |
0m
Args: map[CurrentCode: sa = vma->vm_start;
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 < length) ? len : length;
if (offset < len) { NewCode: sa = vma->vm_start;
length = PAGE_SIZE << 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 < length) ? len : length;
if (offset < len) { SourceFile:drivers/scsi/sg.c]
Results:
|
| 71/4 |
2026/05/20 22:40 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 62574
output: 231
thoughts: 7
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Delving into `sg_mmap`**
Right, so we're talking about `sg_mmap` now. My immediate focus is on how this interacts with the scatter-gather lists, and how it's being used to map physical memory into user space within the context of the SCSI generic interface. Specifically, I'm thinking about the potential for DMA operations and the importance of ensuring coherent memory access, especially when dealing with hardware that might have its own caching mechanisms. I'm wondering if there are any specific subtleties here relating to different architectures โ is this implementation fully portable? I need to be sure it handles potential issues around bus mastering and memory barriers correctly. I'm also considering the implications of memory protection โ what safeguards are in place to prevent user space from accessing areas of physical memory it shouldnโt? Are there robust bounds checks and permission verifications happening here? From an optimization perspective, Iโm mentally mapping out how we can minimize the overhead of this mapping process โ is there a way to pre-populate relevant page tables or cache the necessary metadata for faster subsequent access? Thinking about potential security vulnerabilities here, it's very important to note that access control is key, and needs to be thoroughly vetted.
|
| 72/4 |
2026/05/20 22:41 |
tool |
codeeditor |
0m
Args: map[CurrentCode: sa = vma->vm_start;
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 < length) ? len : length;
sa += len; NewCode: sa = vma->vm_start;
length = PAGE_SIZE << 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 < length) ? len : length;
sa += len; SourceFile:drivers/scsi/sg.c]
Results:
|
| 73/4 |
2026/05/20 22:41 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 63099
output: 179
thoughts: 9
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Analyzing the Query: `sg_read_oxfer`**
Alright, the query "sg_read_oxfer" pops up. Immediately, I'm parsing it. "sg" is likely a short form, probably related to storage or SCSI. It's concise. "read" is, of course, a clear verb; a fundamental operation. The final portion, "oxfer," is what requires the immediate attention. This is likely an identifier specific to a device, subsystem, or perhaps even a data structure. Based on this very little information, I might jump to several potential areas:
* **Storage Access Layer**: Could this be a low-level operation using the SCSI Generic (sg) interface for direct access to a storage device.
* **A specific implementation**: Is this related to a proprietary storage controller?
* **A tool/library**: Is this related to some storage tool/library that has an oxen (ox) prefix for a specific feature, like the oxen file system.
* **A bug or edge case**: Perhaps something has gone wrong and this query is pointing to something that I would otherwise have assumed was not present.
The first step is going to be to see if I can cross-reference this in my mental catalog and/or documentation or log files that I am actively watching. I need more context to narrow down the possibilities. Is this a system call? A function call? A command-line argument? My next move depends entirely on that. I'm going to have to make some quick deductions based on the situation and proceed from there. "sg_read_oxfer" - I need to understand that "oxfer" part quickly.
|
| 74/4 |
2026/05/20 22:41 |
tool |
codeeditor |
0m
Args: map[CurrentCode: if ((!outp) || (num_read_xfer <= 0))
return 0;
num = 1 << (PAGE_SHIFT + schp->page_order);
for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { NewCode: if ((!outp) || (num_read_xfer <= 0))
return 0;
num = PAGE_SIZE << schp->page_order;
for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { SourceFile:drivers/scsi/sg.c]
Results:
|
| 75/4 |
2026/05/20 22:41 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 63672
output: 137
thoughts: 8
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Analyzing the `sg_link_reserve` Operation**
Alright, let's break down this `sg_link_reserve` call. My first thought is always to consider its context within the broader system. I'm immediately running through the possible data structures involved - is it interacting with a shared resource, a specific file system structure, perhaps a lock manager? Knowing the underlying architecture is critical here.
Next, I'm thinking about the parameters. What data is being passed *into* `sg_link_reserve`? What kind of flags or options are likely controlling its behavior? Are we talking about a simple reservation, or something more complex, like a multi-level reservation that potentially spans multiple data structures or processes? I'll need to dissect the input data types to determine any constraints.
Then comes the "what does it *do*?" phase. Is it allocating something, de-allocating, checking permissions, setting metadata, incrementing a counter? Itโs not just about functionality; it's about the *mechanism*. Does it acquire an exclusive lock, or does it try for a non-blocking one? Is this atomic, or are there potential race conditions I need to consider? Is error handling well implemented? What are the potential failure modes and how are they signaled back? Thinking through the system's reaction to failure is key to ensuring reliability.
Finally, I'll need to assess its potential impact on performance. Is this a frequent operation? Is it expected to scale? Does this impact latency, and what's the expected overhead from the calling context? Are there any obvious bottlenecks or opportunities for optimization? I'll also try to think of potential security implications as this is a core part of the code base.
This isnโt just about *understanding* the function call; it's about understanding its *role* within the larger system and its potential impact on the overall architecture. That's the mindset I'm bringing to this analysis.
|
| 76/4 |
2026/05/20 22:41 |
tool |
codeeditor |
0m
Args: map[CurrentCode: rem = size;
num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
for (k = 0; k < rsv_schp->k_use_sg; k++) { NewCode: rem = size;
num = PAGE_SIZE << rsv_schp->page_order;
for (k = 0; k < rsv_schp->k_use_sg; k++) { SourceFile:drivers/scsi/sg.c]
Results:
|
| 77/4 |
2026/05/20 22:41 |
llm |
patch-generator |
1m
Model:
Tokens:
input: 64260
output: 23
thoughts: 7
Thoughts: Okay, I'm ready to dive into that "diff" and give you my expert take. Here's my thought process:
**Diving into the Code Change**
Alright, a diff is in front of me, which means we're looking at a comparison between two versions of some code, config, or data. My first instinct is to zoom in on the most crucial areas of the changes โ those likely to have the biggest impact, or where I expect potential problems. I immediately start scanning for:
* **Core Logic Alterations:** What fundamental algorithms or data structures have been modified? That's always my primary focus.
* **Dependency Updates:** Any changes to external libraries or APIs? Those can introduce breaking changes or security vulnerabilities if not carefully vetted.
* **Performance Implications:** Is the change likely to speed things up, slow things down, or introduce any new bottlenecks? I'm looking for anything that could impact throughput or latency.
* **Security Concerns:** Did the change touch any areas related to authentication, authorization, or data handling? Any red flags there are going to get my immediate attention.
* **Error Handling:** Are there any new error conditions, and how are they being handled? Proper error management is critical, and often an afterthought that can be improved.
* **Edge Cases:** I'm mentally testing the changes against scenarios. Any potential edge cases I can see? The diff is likely to show what the developer tested, so I can use that to formulate my own tests.
* **Stylistic Changes:** Does the code follow our style guide? Consistency is crucial for maintainability.
Now, as I go through the diff, I'm already formulating test cases, potential follow-up questions, and likely refactor suggestions in my head. I'm going to look for any area that is not quite consistent with the standard or the project's standards. My review is going to address what the code does, and what it *should* do, as well as considering if the change is a complete solution.
|
| 78/4 |
2026/05/20 22:42 |
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 74cd4e8a6..cb4450a89 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1217,34 +1217,34 @@ static vm_fault_t
sg_vma_fault(struct vm_fault *vmf)
{
struct vm_area_struct *vma = vmf->vma;
Sg_fd *sfp;
unsigned long offset, len, sa;
Sg_scatter_hold *rsv_schp;
int k, length;
if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
return VM_FAULT_SIGBUS;
rsv_schp = &sfp->reserve;
offset = vmf->pgoff << PAGE_SHIFT;
if (offset >= rsv_schp->bufflen)
return VM_FAULT_SIGBUS;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
"sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
if (offset < len) {
struct page *page = rsv_schp->pages[k] + (offset >> PAGE_SHIFT);
get_page(page); /* increment page count */
vmf->page = page;
return 0; /* success */
}
sa += len;
offset -= len;
}
return VM_FAULT_SIGBUS;
}
@@ -1257,39 +1257,39 @@ static int
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, length;
int ret = 0;
if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
return -ENXIO;
req_sz = vma->vm_end - vma->vm_start;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sfp->parentdp,
"sg_mmap starting, vm_start=%p, len=%d\n",
(void *) vma->vm_start, (int) req_sz));
if (vma->vm_pgoff)
return -EINVAL; /* want no offset */
rsv_schp = &sfp->reserve;
mutex_lock(&sfp->f_mutex);
if (req_sz > rsv_schp->bufflen) {
ret = -ENOMEM; /* cannot map more than reserved buffer */
goto out;
}
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
sa += len;
}
sfp->mmap_called = 1;
vm_flags_set(vma, VM_IO | VM_DONTEXPAND | VM_DONTDUMP);
vma->vm_private_data = sfp;
vma->vm_ops = &sg_mmap_vm_ops;
out:
mutex_unlock(&sfp->f_mutex);
return ret;
}
@@ -1855,76 +1855,77 @@ 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) {
+ 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);
+ ret_sz = PAGE_SIZE << 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;
}
@@ -1956,31 +1957,31 @@ static int
sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
{
Sg_scatter_hold *schp = &srp->data;
int k, num;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, srp->parentfp->parentdp,
"sg_read_oxfer: num_read_xfer=%d\n",
num_read_xfer));
if ((!outp) || (num_read_xfer <= 0))
return 0;
- num = 1 << (PAGE_SHIFT + schp->page_order);
+ num = PAGE_SIZE << 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(schp->pages[k]),
num_read_xfer))
return -EFAULT;
break;
} else {
if (copy_to_user(outp, page_address(schp->pages[k]),
num))
return -EFAULT;
num_read_xfer -= num;
if (num_read_xfer <= 0)
break;
outp += num;
}
}
return 0;
}
@@ -2007,29 +2008,29 @@ static void
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;
int k, num, rem;
srp->res_used = 1;
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp,
"sg_link_reserve: size=%d\n", size));
rem = size;
- num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ num = PAGE_SIZE << rsv_schp->page_order;
for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
req_schp->k_use_sg = k + 1;
req_schp->sglist_len = rsv_schp->sglist_len;
req_schp->pages = rsv_schp->pages;
req_schp->bufflen = size;
req_schp->page_order = rsv_schp->page_order;
break;
} else
rem -= num;
}
if (k >= rsv_schp->k_use_sg)
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp,
"sg_link_reserve: BAD size\n"));
}
]
|
| 79/4 |
2026/05/20 22:42 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 67743
output: 462
thoughts: 368
Thoughts: **My Analysis of the Patch and Final Response**
Okay, this diff is looking solid. Time to craft the final response. I'll make sure to clearly articulate the following points:
First, the key fix: I addressed the missing `num = PAGE_SIZE` update when clamping `scatter_elem_sz`. This was the crucial oversight. Without it, we were ending up in a situation where `get_order(0)` was being called, and that was the root cause of the shift-out-of-bounds error. `get_order(0)`, due to underflow, essentially returned a very large value, leading to the problem.
Second, regarding the proposed fix involving `1UL`, I've opted for a more robust approach. Initially, the suggestion was to replace `1` with `1UL`. However, I've opted to change the expression to `PAGE_SIZE << order`. The original proposed fix, `1UL << (PAGE_SHIFT + order)`, still presented a potential for undefined behavior if `PAGE_SHIFT + order` became greater than or equal to 64. Specifically, in this scenario, `12 + 52 = 64`. Shifting a 64-bit integer by 64 bits is undefined behavior in C. Using `PAGE_SIZE << order` resolves this. The shift operation is defined even when `order` is 52. More importantly, using `PAGE_SIZE << order` is the standard and idiomatic way within the kernel to calculate the size of an allocation given its order. This is consistent with kernel coding conventions.
Finally, for consistency and future-proofing, I've also updated four other locations within `drivers/scsi/sg.c` that employed the identical pattern, `1 << (PAGE_SHIFT + order)`. These locations include `sg_vma_fault`, `sg_mmap`, `sg_read_oxfer`, and `sg_link_reserve`. While these specific cases were currently safe because `page_order` is bounded by `MAX_PAGE_ORDER`, I made the change to `PAGE_SIZE << order` to ensure consistency and proactively prevent any possibility of undefined behavior in the future. This is a preventative measure to maintain code quality and safety.
|
| 80/3 |
2026/05/20 22:42 |
action |
test-patch |
34m
Results: map[PatchDiff:diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 74cd4e8a6..cb4450a89 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1232,7 +1232,7 @@ sg_vma_fault(struct vm_fault *vmf)
"sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1278,7 +1278,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
}
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1877,6 +1877,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1885,7 +1886,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = PAGE_SIZE << order;
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
@@ -1964,7 +1965,7 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- num = 1 << (PAGE_SHIFT + schp->page_order);
+ num = PAGE_SIZE << 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(schp->pages[k]),
@@ -2015,7 +2016,7 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
"sg_link_reserve: size=%d\n", size));
rem = size;
- num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ num = PAGE_SIZE << rsv_schp->page_order;
for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
req_schp->k_use_sg = k + 1;
TestError:]
|
| 81/1 |
2026/05/20 23:17 |
agent |
fixes-finder |
23m
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/d5a02ed91a4f019017141f71e695c75b27c3612e/drivers/scsi/sg.c:1888:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 0 UID: 0 PID: 6185 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+0x385/0x410 lib/ubsan.c:494
sg_build_indirect+0x549/0x850 drivers/scsi/sg.c:1888
sg_build_reserve drivers/scsi/sg.c:1998 [inline]
sg_add_sfp drivers/scsi/sg.c:2178 [inline]
sg_open+0x122a/0x1a40 drivers/scsi/sg.c:349
chrdev_open+0x4cd/0x5e0 fs/char_dev.c:411
do_dentry_open+0x785/0x14e0 fs/open.c:947
vfs_open+0x3b/0x340 fs/open.c:1079
do_open fs/namei.c:4699 [inline]
path_openat+0x2e08/0x3860 fs/namei.c:4858
do_file_open+0x23e/0x4a0 fs/namei.c:4887
do_sys_openat2+0x113/0x200 fs/open.c:1364
do_sys_open fs/open.c:1370 [inline]
__do_sys_openat fs/open.c:1386 [inline]
__se_sys_openat fs/open.c:1381 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1381
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f72e679ce59
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:00007f72e75e3028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007f72e6a15fa0 RCX: 00007f72e679ce59
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007f72e6832d6f R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f72e6a16038 R14: 00007f72e6a15fa0 R15: 00007ffe5f34f718
</TASK>
---[ end trace ]---
The explanation of the root cause is:
An excellent catch by syzkaller. The root cause of this crash is a missing local variable update after clamping a module parameter, combined with an unsafe bitwise shift on a signed 32-bit integer.
### Root Cause Analysis
The `sg` driver exposes the `scatter_elem_sz` module parameter, which can be modified at runtime by a privileged user via `/sys/module/sg/parameters/scatter_elem_sz`.
1. **The Sysfs Write:**
The syzkaller reproducer writes the string `"0"` to this sysfs file. The kernel parses this using `kstrtoint` and sets the global variable `scatter_elem_sz` to `0`. (Writing a negative value like `"-1"` would have the same effect).
2. **The Trigger:**
The reproducer then opens `/dev/sg0`. This invokes `sg_open()`, which calls `sg_add_sfp()`, and subsequently `sg_build_reserve()` and `sg_build_indirect()`.
3. **The Missing Variable Update:**
In `sg_build_indirect()`, the code reads `scatter_elem_sz` into a local variable `num` and attempts to clamp it to a minimum of `PAGE_SIZE`:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 scatter_elem_sz = PAGE_SIZE;
1901 scatter_elem_sz_prev = PAGE_SIZE;
1902 } else
1903 scatter_elem_sz_prev = num;
1904 }
1905
1906 order = get_order(num);
```
Notice that while the global `scatter_elem_sz` and `scatter_elem_sz_prev` are correctly clamped to `PAGE_SIZE`, **the local variable `num` is never updated**. Thus, `num` remains `0` (or negative).
4. **The `get_order()` Underflow:**
The code then calls `order = get_order(num);` where `num` is `0`.
Inside `get_order(unsigned long size)`, the size is decremented (`size--`), which underflows `0` to `0xffffffffffffffffUL`. It is then shifted right by `PAGE_SHIFT` (12), resulting in `0x000fffffffffffffUL`. The `fls64()` of this value is `52`. Thus, `get_order(0)` returns `52`.
5. **The UBSAN Shift-Out-Of-Bounds:**
Immediately after, the code calculates the return size:
```c
1907 retry:
1908 ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT` being `12` and `order` being `52`, the expression evaluates to `1 << 64`. Since the literal `1` is a signed 32-bit `int`, shifting it by 64 is undefined behavior and triggers the exact UBSAN warning seen in the crash: `shift exponent 64 is too large for 32-bit type 'int'`.
*(Note: There is also a secondary bug here. If a user intentionally writes a very large valid value like `0x7fffffff` to `scatter_elem_sz`, `order` becomes `19`. The expression `1 << (12 + 19)` evaluates to `1 << 31`, which shifts a bit into the sign bit of a signed 32-bit integerโalso undefined behavior in C).*
### Proposed Fix
To fix this, we need to update `num` to `PAGE_SIZE` when clamping, and change the literal `1` to `1UL` to prevent any undefined behavior when `order` is legitimately large.
```c
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1897,6 +1897,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1905,7 +1906,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = 1UL << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
```
The patch that fixes the bug is:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 74cd4e8a6..cb4450a89 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1232,7 +1232,7 @@ sg_vma_fault(struct vm_fault *vmf)
"sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1278,7 +1278,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
}
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1877,6 +1877,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1885,7 +1886,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = PAGE_SIZE << order;
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
@@ -1964,7 +1965,7 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- num = 1 << (PAGE_SHIFT + schp->page_order);
+ num = PAGE_SIZE << 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(schp->pages[k]),
@@ -2015,7 +2016,7 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
"sg_link_reserve: size=%d\n", size));
rem = size;
- num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ num = PAGE_SIZE << rsv_schp->page_order;
for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
req_schp->k_use_sg = k + 1;
Search for the commit(s) that introduced this bug.
|
| 82/2 |
2026/05/20 23:17 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 7348
output: 35
thoughts: 161
Thoughts: **Pinpointing the Bug's Genesis**
Okay, so we've got a patch that fixes a bug in `drivers/scsi/sg.c`, specifically within the `sg_build_indirect()` function. My immediate goal is to trace this bug back to its origin. The provided information tells me the core issue is related to how `num` isn't updated correctly when `num` is less than `PAGE_SIZE` and `scatter_elem_sz` is clamped. Then, there is the integer overflow concern with `1 << (PAGE_SHIFT + order)`. I need to figure out when this behavior was introduced.
Right, time to dive into the revision history of that function. I'll reach for `git log` to walk me through the changes to `sg_build_indirect()` in `drivers/scsi/sg.c`. Hopefully, the commit messages are clear enough to identify the change that led to the problem. I'll be looking for clues around how those calculations involving `num`, `PAGE_SIZE`, and any shifting operations were implemented. I'm expecting to be able to isolate the problematic commit pretty quickly.
|
| 83/2 |
2026/05/20 23:17 |
tool |
git-log |
0m
Args: map[SourcePath:drivers/scsi/sg.c SymbolName:sg_build_indirect]
Results: map[Output:1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 84/2 |
2026/05/20 23:18 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 7822
output: 26
thoughts: 61
Thoughts: **Initial Code Dive: Unearthing a Potential Bug**
Okay, so `sg_build_indirect`... that function's been around since the very beginning, huh? Right back to the `1da177e4c3f4` commit, which, as I recall, marks the genesis of this particular code base. Intriguing. It's a hunch, but I'm thinking we might be dealing with something fundamental, something that's been baked in since day one.
My next step is clear: let's jump into that initial commit of `drivers/scsi/sg.c`. I need to see the original implementation of `sg_build_indirect`. If the potential issue is present there, it validates the hypothesis that it's a longstanding flaw. It will give me a better understanding and a greater chance to correct the issue.
|
| 85/2 |
2026/05/20 23:18 |
tool |
git-show |
0m
Args:
Results: map[Output:
Full output is too long, showing 1000 out of 6822520 lines.
[commit 1da177e4c3f41524e886b7f1b8a0c1fc7321cac2
Author: Linus Torvalds <torvalds@ppc970.osdl.org>
Date: Sat Apr 16 15:20:36 2005 -0700
Linux-2.6.12-rc2
Initial git repository build. I'm not bothering with the full history,
even though we have it. We can create a separate "historical" git
archive of that later if we want to, and in the meantime it's about
3.2GB when imported into git - space that would just make the early
git days unnecessarily complicated, when we don't have a lot of good
infrastructure for it.
Let it rip!
diff --git a/COPYING b/COPYING
new file mode 100644
index 000000000000..2a7e338ec2fc
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,356 @@
+
+ NOTE! This copyright does *not* cover user programs that use kernel
+ services by normal system calls - this is merely considered normal use
+ of the kernel, and does *not* fall under the heading of "derived work".
+ Also note that the GPL below is copyrighted by the Free Software
+ Foundation, but the instance of code that it refers to (the Linux
+ kernel) is copyrighted by me and others who actually wrote it.
+
+ Also note that the only valid version of the GPL as far as the kernel
+ is concerned is _this_ particular version of the license (ie v2, not
+ v2.2 or v3.x or whatever), unless explicitly otherwise stated.
+
+ Linus Torvalds
+
+----------------------------------------
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/CREDITS b/CREDITS
new file mode 100644
index 000000000000..671e9c2d31fe
--- /dev/null
+++ b/CREDITS
@@ -0,0 +1,3743 @@
+ This is at least a partial credits-file of people that have
+ contributed to the Linux project. It is sorted by name and
+ formatted to allow easy grepping and beautification by
+ scripts. The fields are: name (N), email (E), web-address
+ (W), PGP key ID and fingerprint (P), description (D), and
+ snail-mail address (S).
+ Thanks,
+
+ Linus
+----------
+
+N: Matti Aarnio
+E: mea@nic.funet.fi
+D: Alpha systems hacking, IPv6 and other network related stuff
+D: One of assisting postmasters for vger.kernel.org's lists
+S: (ask for current address)
+S: Finland
+
+N: Dragos Acostachioaie
+E: dragos@iname.com
+W: http://www.arbornet.org/~dragos
+D: /proc/sysvipc
+S: C. Negri 6, bl. D3
+S: Iasi 6600
+S: Romania
+
+N: Monalisa Agrawal
+E: magrawal@nortelnetworks.com
+D: Basic Interphase 5575 driver with UBR and ABR support.
+S: 75 Donald St, Apt 42
+S: Weymouth, MA 02188
+
+N: Dave Airlie
+E: airlied@linux.ie
+W: http://www.csn.ul.ie/~airlied
+D: NFS over TCP patches
+D: in-kernel DRM Maintainer
+S: Longford, Ireland
+S: Sydney, Australia
+
+N: Tigran A. Aivazian
+E: tigran@veritas.com
+W: http://www.moses.uklinux.net/patches
+D: BFS filesystem
+D: Intel IA32 CPU microcode update support
+D: Various kernel patches
+S: United Kingdom
+
+N: Werner Almesberger
+E: werner@almesberger.net
+W: http://www.almesberger.net/
+D: dosfs, LILO, some fd features, ATM, various other hacks here and there
+S: Buenos Aires
+S: Argentina
+
+N: Tim Alpaerts
+E: tim_alpaerts@toyota-motor-europe.com
+D: 802.2 class II logical link control layer,
+D: the humble start of an opening towards the IBM SNA protocols
+S: Klaproosstraat 72 c 10
+S: B-2610 Wilrijk-Antwerpen
+S: Belgium
+
+N: Anton Altaparmakov
+E: aia21@cantab.net
+W: http://www-stu.christs.cam.ac.uk/~aia21/
+D: Author of new NTFS driver, various other kernel hacks.
+S: Christ's College
+S: Cambridge CB2 3BU
+S: United Kingdom
+
+N: C. Scott Ananian
+E: cananian@alumni.princeton.edu
+W: http://www.pdos.lcs.mit.edu/~cananian
+P: 1024/85AD9EED AD C0 49 08 91 67 DF D7 FA 04 1A EE 09 E8 44 B0
+D: Unix98 pty support.
+D: APM update to 1.2 spec.
+D: /devfs hacking.
+S: 7 Kiwi Loop
+S: Howell, NJ 07731
+S: USA
+
+N: Erik Andersen
+E: andersen@codepoet.org
+W: http://www.codepoet.org/
+P: 1024D/30D39057 1BC4 2742 E885 E4DE 9301 0C82 5F9B 643E 30D3 9057
+D: Maintainer of ide-cd and Uniform CD-ROM driver,
+D: ATAPI CD-Changer support, Major 2.1.x CD-ROM update.
+S: 352 North 525 East
+S: Springville, Utah 84663
+S: USA
+
+N: Michael Ang
+E: mang@subcarrier.org
+W: http://www.subcarrier.org/mang
+D: Linux/PA-RISC hacker
+S: 85 Frank St.
+S: Ottawa, Ontario
+S: Canada K2P 0X3
+
+N: H. Peter Anvin
+E: hpa@zytor.com
+W: http://www.zytor.com/~hpa/
+P: 2047/2A960705 BA 03 D3 2C 14 A8 A8 BD 1E DF FE 69 EE 35 BD 74
+D: Author of the SYSLINUX boot loader, maintainer of the linux.* news
+D: hierarchy and the Linux Device List; various kernel hacks
+S: 4390 Albany Drive #46
+S: San Jose, California 95129
+S: USA
+
+N: Andrea Arcangeli
+E: andrea@suse.de
+W: http://www.kernel.org/pub/linux/kernel/people/andrea/
+P: 1024D/68B9CB43 13D9 8355 295F 4823 7C49 C012 DFA1 686E 68B9 CB43
+P: 1024R/CB4660B9 CC A0 71 81 F4 A0 63 AC C0 4B 81 1D 8C 15 C8 E5
+D: Parport hacker
+D: Implemented a workaround for some interrupt buggy printers
+D: Author of pscan that helps to fix lp/parport bugs
+D: Author of lil (Linux Interrupt Latency benchmark)
+D: Fixed the shm swap deallocation at swapoff time (try_to_unuse message)
+D: VM hacker
+D: Various other kernel hacks
+S: Via Cicalini 26
+S: Imola 40026
+S: Italy
+
+N: Derek Atkins
+E: warlord@MIT.EDU
+D: Linux-AFS Port, random kernel hacker,
+D: VFS fixes (new notify_change in particular)
+D: Moving all VFS access checks into the file systems
+S: MIT Room E15-341
+S: 20 Ames Street
+S: Cambridge, Massachusetts 02139
+S: USA
+
+N: Michel Aubry
+E: giovanni <giovanni@sudfr.com>
+D: Aladdin 1533/1543(C) chipset IDE
+D: VIA MVP-3/TX Pro III chipset IDE
+
+N: Jens Axboe
+E: axboe@suse.de
+D: Linux CD-ROM maintainer, DVD support
+D: elevator + block layer rewrites
+D: highmem I/O support
+D: misc hacking on IDE, SCSI, block drivers, etc
+S: Peter Bangs Vej 258, 2TH
+S: 2500 Valby
+S: Denmark
+
+N: John Aycock
+E: aycock@cpsc.ucalgary.ca
+D: Adaptec 274x driver
+S: Department of Computer Science
+S: University of Calgary
+S: Calgary, Alberta
+S: Canada
+
+N: Miles Bader
+E: miles@gnu.org
+D: v850 port (uClinux)
+S: NEC Corporation
+S: 1753 Shimonumabe, Nakahara-ku
+S: Kawasaki 211-8666
+S: Japan
+
+N: Ralf Baechle
+E: ralf@gnu.org
+P: 1024/AF7B30C1 CF 97 C2 CC 6D AE A7 FE C8 BA 9C FC 88 DE 32 C3
+D: Linux/MIPS port
+D: Linux/68k hacker
+S: Hauptstrasse 19
+S: 79837 St. Blasien
+S: Germany
+
+N: Krishna Balasubramanian
+E: balasub@cis.ohio-state.edu
+D: Wrote SYS V IPC (part of standard kernel since 0.99.10)
+
+N: Dario Ballabio
+E: ballabio_dario@emc.com
+E: dario.ballabio@tiscalinet.it
+E: dario.ballabio@inwind.it
+D: Author and maintainer of the Ultrastor 14F/34F SCSI driver
+D: Author and maintainer of the EATA ISA/EISA/PCI SCSI driver
+S: EMC Corporation
+S: Milano
+S: Italy
+
+N: Paul Bame
+E: bame@debian.org
+E: bame@puffin.external.hp.com
+E: paul_bame@hp.com
+W: http://www.parisc-linux.org
+D: PA-RISC 32 and 64-bit early boot, firmware interface, interrupts, misc
+S: MS42
+S: Hewlett-Packard
+S: 3404 E Harmony Rd
+S: Fort Collins, CO 80525
+
+N: Arindam Banerji
+E: axb@cse.nd.edu
+D: Contributed ESDI driver routines needed to port LINUX to the PS/2 MCA.
+S: Department of Computer Science & Eng.
+S: University of Notre Dame
+S: Notre Dame, Indiana
+S: USA
+
+N: Greg Banks
+E: gnb@alphalink.com.au
+D: IDT77105 ATM network driver
+D: some SuperH port work
+D: some trivial futzing with kconfig
+
+N: James Banks
+E: james@sovereign.org
+D: TLAN network driver
+D: Logitech Busmouse driver
+
+N: Krzysztof G. Baranowski
+E: kgb@manjak.knm.org.pl
+P: 1024/FA6F16D1 96 D1 1A CF 5F CA 69 EC F9 4F 36 1F 6D 60 7B DA
+D: Maintainer of the System V file system.
+D: System V fs update for 2.1.x dcache.
+D: Forward ported a couple of SCSI drivers.
+D: Various bugfixes.
+S: ul. Koscielna 12a
+S: 62-300 Wrzesnia
+S: Poland
+
+N: Fred Barnes
+E: frmb2@ukc.ac.uk
+D: Various parport/ppdev hacks and fixes
+S: Computing Lab, The University
+S: Canterbury, KENT
+S: CT2 7NF
+S: England
+
+N: Paul Barton-Davis
+E: pbd@op.net
+D: Driver for WaveFront soundcards (Turtle Beach Maui, Tropez, Tropez+)
+D: Various bugfixes and changes to sound drivers
+S: USA
+
+N: Carlos Henrique Bauer
+E: chbauer@acm.org
+E: bauer@atlas.unisinos.br
+D: Some new sysctl entries for the parport driver.
+D: New sysctl function for handling unsigned longs
+S: Universidade do Vale do Rio dos Sinos - UNISINOS
+S: DSI/IDASI
+S: Av. Unisinos, 950
+S: 93022000 Sao Leopoldo RS
+S: Brazil
+
+N: Peter Bauer
+E: 100136.3530@compuserve.com
+D: Driver for depca-ethernet-board
+S: 69259 Wilhemsfeld
+S: Rainweg 15
+S: Germany
+
+N: Fred Baumgarten
+E: dc6iq@insl1.etec.uni-karlsruhe.de
+E: dc6iq@adacom.org
+E: dc6iq@db0ais.#hes.deu.eu (packet radio)
+D: NET-2 & netstat(8)
+S: Soevener Strasse 11
+S: 53773 Hennef
+S: Germany
+
+N: Donald Becker
+E: becker@cesdis.gsfc.nasa.gov
+D: General low-level networking hacker
+D: Most of the ethercard drivers
+D: Original author of the NFS server
+S: USRA Center of Excellence in Space Data and Information Sciences
+S: Code 930.5, Goddard Space Flight Center
+S: Greenbelt, Maryland 20771
+S: USA
+
+N: Adam Belay
+E: ambx1@neo.rr.com
+D: Linux Plug and Play Support
+S: USA
+
+N: Daniele Bellucci
+E: bellucda@tiscali.it
+D: Various Janitor work.
+W: http://web.tiscali.it/bellucda
+S: Via Delle Palme, 9
+S: Terni 05100
+S: Italy
+
+N: Krzysztof Benedyczak
+E: golbi@mat.uni.torun.pl
+W: http://www.mat.uni.torun.pl/~golbi
+D: POSIX message queues fs (with M. Wronski)
+S: ul. Podmiejska 52
+S: Radunica
+S: 83-000 Pruszcz Gdanski
+S: Poland
+
+N: Randolph Bentson
+E: bentson@grieg.seaslug.org
+W: http://www.aa.net/~bentson/
+P: 1024/39ED5729 5C A8 7A F4 B2 7A D1 3E B5 3B 81 CF 47 30 11 71
+D: Author of driver for Cyclom-Y and Cyclades-Z async mux
+S: 2322 37th Ave SW
+S: Seattle, Washington 98126-2010
+S: USA
+
+N: Stephen R. van den Berg (AKA BuGless)
+E: berg@pool.informatik.rwth-aachen.de
+D: General kernel, gcc, and libc hacker
+D: Specialisation: tweaking, ensuring portability, tweaking, cleaning,
+D: tweaking and occasionally debugging :-)
+S: Bouwensstraat 22
+S: 6369 BG Simpelveld
+S: The Netherlands
+
+N: Peter Berger
+E: pberger@brimson.com
+W: http://www.brimson.com
+D: Author/maintainer of Digi AccelePort USB driver
+S: 1549 Hiironen Rd.
+S: Brimson, MN 55602
+S: USA
+
+N: Hennus Bergman
+P: 1024/77D50909 76 99 FD 31 91 E1 96 1C 90 BB 22 80 62 F6 BD 63
+D: Author and maintainer of the QIC-02 tape driver
+S: The Netherlands
+
+N: Tomas Berndtsson
+E: tomas@nocrew.org
+W: http://tomas.nocrew.org/
+D: dsp56k device driver
+
+N: Ross Biro
+E: bir7@leland.Stanford.Edu
+D: Original author of the Linux networking code
+
+N: Anton Blanchard
+E: anton@samba.org
+W: http://samba.org/~anton/
+P: 1024/8462A731 4C 55 86 34 44 59 A7 99 2B 97 88 4A 88 9A 0D 97
+D: sun4 port, Sparc hacker
+
+N: Hugh Blemings
+E: hugh@misc.nu
+W: http://misc.nu/hugh/
+D: Author and maintainer of the Keyspan USB to Serial drivers
+S: Po Box 234
+S: Belconnen ACT 2616
+S: Australia
+
+N: Philip Blundell
+E: philb@gnu.org
+D: Linux/ARM hacker
+D: Device driver hacker (eexpress, 3c505, c-qcam, ...)
+D: m68k port to HP9000/300
+D: AUN network protocols
+D: Co-architect of the parallel port sharing system
+D: IPv6 netfilter
+S: FutureTV Labs Ltd
+S: Brunswick House, 61-69 Newmarket Rd, Cambridge CB5 8EG
+S: United Kingdom
+
+N: Thomas Bogend๏ฟฝrfer
+E: tsbogend@alpha.franken.de
+D: PCnet32 driver, SONIC driver, JAZZ_ESP driver
+D: newport abscon driver, g364 framebuffer driver
+D: strace for Linux/Alpha
+D: Linux/MIPS hacker
+S: Schafhofstr. 40
+S: 90556 Cadolzburg
+S: Germany
+
+N: Bill Bogstad
+E: bogstad@pobox.com
+D: wrote /proc/self hack, minor samba & dosemu patches
+
+N: Axel Boldt
+E: axel@uni-paderborn.de
+W: http://math-www.uni-paderborn.de/~axel/
+D: Configuration help text support
+D: Linux CD and Support Giveaway List
+
+N: Erik Inge Bols๏ฟฝ
+E: knan@mo.himolde.no
+D: Misc kernel hacks
+
+N: Andreas E. Bombe
+E: andreas.bombe@munich.netsurf.de
+W: http://home.pages.de/~andreas.bombe/
+P: 1024/04880A44 72E5 7031 4414 2EB6 F6B4 4CBD 1181 7032 0488 0A44
+D: IEEE 1394 subsystem rewrite and maintainer
+D: Texas Instruments PCILynx IEEE 1394 driver
+
+N: Al Borchers
+E: alborchers@steinerpoint.com
+D: Author/maintainer of Digi AccelePort USB driver
+D: work on usbserial and keyspan_pda drivers
+S: 4912 Zenith Ave. S.
+S: Minneapolis, MN 55410
+S: USA
+
+N: Marc Boucher
+E: marc@mbsi.ca
+P: CA 67 A5 1A 38 CE B6 F2 D5 83 51 03 D2 9C 30 9E CE D2 DD 65
+D: Netfilter core
+D: IP policy routing by mark
+D: Various fixes (mostly networking)
+S: Montreal, Quebec
+S: Canada
+
+N: Zolt๏ฟฝn B๏ฟฝsz๏ฟฝrm๏ฟฝnyi
+E: zboszor@mail.externet.hu
+D: MTRR emulation with Cyrix style ARR registers, Athlon MTRR support
+
+N: John Boyd
+E: boyd@cis.ohio-state.edu
+D: Co-author of wd7000 SCSI driver
+S: 101 Curl Drive #591
+S: Columbus, Ohio 43210
+S: USA
+
+N: Peter Braam
+E: braam@clusterfs.com
+W: http://www.clusterfs.com/
+D: Coda & InterMezzo filesystems
+S: 181 McNeil
+S: Canmore, AB
+S: Canada, T1W 2R9
+
+N: Ryan Bradetich
+E: rbradetich@uswest.net
+D: Linux/PA-RISC hacker
+S: 1200 Goldenrod Dr.
+S: Nampa, Idaho 83686
+
+N: Derrick J. Brashear
+E: shadow@dementia.org
+W: http://www.dementia.org/~shadow
+P: 512/71EC9367 C5 29 0F BC 83 51 B9 F0 BC 05 89 A0 4F 1F 30 05
+D: Author of Sparc CS4231 audio driver, random Sparc work
+S: 403 Gilmore Avenue
+S: Trafford, Pennsylvania 15085
+S: USA
+
+N: Dag Brattli
+E: dagb@cs.uit.no
+W: http://www.cs.uit.no/~dagb
+D: IrDA Subsystem
+S: 19. Wellington Road
+S: Lancaster, LA1 4DN
+S: UK, England
+
+N: Lars Brinkhoff
+E: lars@nocrew.org
+W: http://lars.nocrew.org/
+D: dsp56k device driver
+D: ptrace proxy in user mode kernel port
+S: Kopmansg 2
+S: 411 13 Goteborg
+S: Sweden
+
+N: Dominik Brodowski
+E: linux@brodo.de
+W: http://www.brodo.de/
+P: 1024D/725B37C6 190F 3E77 9C89 3B6D BECD 46EE 67C3 0308 725B 37C6
+D: parts of CPUFreq code, ACPI bugfixes
+S: Tuebingen, Germany
+
+N: Andries Brouwer
+E: aeb@cwi.nl
+D: random Linux hacker
+S: Bessemerstraat 21
+S: Amsterdam
+S: The Netherlands
+
+N: Zach Brown
+E: zab@zabbo.net
+D: maestro pci sound
+
+N: Gary Brubaker
+E: xavyer@ix.netcom.com
+D: USB Serial Empeg Empeg-car Mark I/II Driver
+
+N: Matthias Bruestle
+E: m@mbsks.franken.de
+D: REINER SCT cyberJack pinpad/e-com USB chipcard reader driver
+S: Germany
+
+N: Adrian Bunk
+E: bunk@stusta.de
+P: 1024D/4F12B400 B29C E71E FE19 6755 5C8A 84D4 99FC EA98 4F12 B400
+D: misc kernel hacking and testing
+S: Grasmeierstrasse 11
+S: 80805 Muenchen
+S: Germany
+
+N: Ray Burr
+E: ryb@nightmare.com
+D: Original author of Amiga FFS filesystem
+S: Orlando, Florida
+S: USA
+
+N: Lennert Buytenhek
+E: buytenh@gnu.org
+D: Rewrite of the ethernet bridging code
+S: Ravenhorst 58B
+S: 2317 AK Leiden
+S: The Netherlands
+
+N: Michael Callahan
+E: callahan@maths.ox.ac.uk
+D: PPP for Linux
+S: The Mathematical Institute
+S: 25-29 St Giles
+S: Oxford
+S: United Kingdom
+
+N: Luiz Fernando N. Capitulino
+E: lcapitulino@terra.com.br
+E: lcapitulino@prefeitura.sp.gov.br
+W: http://www.telecentros.sp.gov.br
+D: Little fixes and a lot of janitorial work
+S: E-GOV Telecentros SP
+S: Brazil
+
+N: Remy Card
+E: Remy.Card@masi.ibp.fr
+E: Remy.Card@linux.org
+D: Extended file system [defunct] designer and developer
+D: Second extended file system designer and developer
+S: Institut Blaise Pascal
+S: 4 Place Jussieu
+S: 75252 Paris Cedex 05
+S: France
+
+N: Ulf Carlsson
+D: SGI Indy audio (HAL2) drivers
+E: ulfc@bun.falkenberg.se
+
+N: Ed Carp
+E: ecarp@netcom.com
+D: uucp, elm, pine, pico port
+D: cron, at(1) developer
+S: 48287 Sawleaf
+S: Fremont, California 94539
+S: USA
+
+N: Florent Chabaud
+E: florent.chabaud@polytechnique.org
+D: software suspend
+S: SGDN/DCSSI/SDS/LTI
+S: 58, Bd Latour-Maubourg
+S: 75700 Paris 07 SP
+S: France
+
+N: Gordon Chaffee
+E: chaffee@cs.berkeley.edu
+W: http://bmrc.berkeley.edu/people/chaffee/
+D: vfat, fat32, joliet, native language support
+S: 3700 Warwick Road
+S: Fremont, California 94555
+S: USA
+
+N: Chih-Jen Chang
+E: chihjenc@scf.usc.edu
+E: chihjen@iis.sinica.edu.tw
+D: IGMP(Internet Group Management Protocol) version 2
+S: 3F, 65 Tajen street
+S: Tamsui town, Taipei county,
+S: Taiwan 251
+S: Republic of China
+
+N: Michael Elizabeth Chastain
+E: mec@shout.net
+D: Configure, Menuconfig, xconfig
+
+N: Raymond Chen
+E: raymondc@microsoft.com
+D: Author of Configure script
+S: 14509 NE 39th Street #1096
+S: Bellevue, Washington 98007
+S: USA
+
+N: Christopher L. Cheney
+E: ccheney@debian.org
+E: ccheney@cheney.cx
+W: http://www.cheney.cx
+P: 1024D/8E384AF2 2D31 1927 87D7 1F24 9FF9 1BC5 D106 5AB3 8E38 4AF2
+D: Vista Imaging usb webcam driver
+S: 314 Prince of Wales
+S: Conroe, TX 77304
+S: USA
+
+N: Stuart Cheshire
+E: cheshire@cs.stanford.edu
+D: Author of Starmode Radio IP (STRIP) driver
+D: Originator of design for new combined interrupt handlers
+S: William Gates Department
+S: Stanford University
+S: Stanford, California 94305
+S: USA
+
+N: Randolph Chung
+E: tausq@debian.org
+D: Linux/PA-RISC hacker
+S: Los Altos, CA 94022
+S: USA
+
+N: Juan Jose Ciarlante
]
]
|
| 86/2 |
2026/05/20 23:18 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 19958
output: 38
thoughts: 49
Thoughts: Okay, here's my take on those thoughts, framed as an expert's inner monologue:
**Investigating `sg_build_indirect`'s Lineage**
Right, `sg_build_indirect`. That function's been around for ages, hasn't it? Feels like it's seen every SCSI hardware generation. I'm getting a nagging feeling about potential legacy issues or perhaps the evolution of handling scatter-gather lists. Best to dig into its recent history. I need to understand how the allocation of scatter lists has changed over time.
Let's start by scrutinizing the usage and modification history of `scatter_elem_sz` and its previous incarnation, `scatter_elem_sz_prev`, specifically within `drivers/scsi/sg.c`. I need to figure out how these variables relate to the block size calculations and determine if there have been any significant performance optimizations in these calculations. I wonder if there are any subtle bugs lurking, introduced by changes in the scatter-gather implementation, or if there were any issues that required them to add a previous version of the code. That will give me some context on potential problems or areas to watch out for.
|
| 87/2 |
2026/05/20 23:18 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:scatter_elem_sz_prev SourcePath:drivers/scsi/sg.c]
Results:
|
| 88/2 |
2026/05/20 23:28 |
llm |
fixes-finder |
1m
Model:
Tokens:
input: 20326
output: 38
thoughts: 31
Thoughts: Okay, here's my interpretation of that thought process, as if it were my own:
**Investigating Scatter/Gather Element Size in the SCSI Subsystem**
Alright, I need to get a better handle on how the scatter/gather element size is handled within the SCSI subsystem, specifically within the `sg.c` driver. My initial thought is to zero in on where `scatter_elem_sz` is defined, used, or modified. Given the nature of this inquiry, I'm reaching for `git log` โ that's the tool for tracking down historical changes and understanding the evolution of this particular code snippet. I'm going to leverage `PathPrefix` to narrow the search down to the `drivers/scsi/` directory, and further refine it to the `sg.c` file itself. This should give me a focused history of changes related to that specific variable within the driver. Time to dig in and see what the revision history reveals. I'm hoping to quickly understand the context around this size and how it's being managed.
|
| 89/2 |
2026/05/20 23:29 |
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
]
|
| 90/2 |
2026/05/20 23:29 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 20678
output: 27
thoughts: 33
Thoughts: Okay, here's my interpretation of those thoughts, presented as a personal thought process, as requested:
**Assessing Recent Commits**
Right, time to dig into this. I'm seeing a need to analyze two specific commits, and I'm immediately focusing on the commit hashes: `6460e75a104d` and `10db10d144c0`. My gut feeling is that these are likely related to a recent bug report or perhaps a feature implementation I was involved with. Let's see whatโs going on in there. I need to understand the changes made in these commits, their context within the codebase, and their potential impact. Iโll start by reviewing the diffs and looking for any clues that jump out. It's likely that one of them is the direct solution and the other is a refactor or adjacent contribution. Either way, my immediate thought is to check them both, quickly.
|
| 91/2 |
2026/05/20 23:29 |
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
]
|
| 92/2 |
2026/05/20 23:29 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 25350
output: 40
thoughts: 283
Thoughts: **Analyzing a Recent Change and a Potential Bug**
Okay, so commit `6460e75a104d` introduced `scatter_elem_sz` and `scatter_elem_sz_prev`, interesting. Let's dig into the diff within `sg_build_indirect`. I see this snippet:
```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 is that `num` isn't updated if `num` is less than `PAGE_SIZE`. The variables `scatter_elem_sz` and `scatter_elem_sz_prev` are updated, but the local variable `num` stays as it was. It's clamping the global values, but not the local one used for the `get_order()` function call.
Ah, the bug report... "Notice that while the global scatter_elem_sz and scatter_elem_sz_prev are correctly clamped to PAGE_SIZE, the local variable num is never updated. Thus, num remains 0 (or negative)." That's what I suspected.
And then it points out that the code calls `order = get_order(num);` where `num` is 0, which makes perfect sense with what I have assessed. This is where things go south. However, `get_order(num)` wasn't in the initial commit. I need to track down *when* `get_order(num)` was introduced into the code to figure out how this issue came to life.
|
| 93/2 |
2026/05/20 23:29 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:order = get_order\(num\); SourcePath:drivers/scsi/sg.c]
Results:
|
| 94/2 |
2026/05/20 23:39 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 26109
output: 40
thoughts: 7
Thoughts: Okay, here's my attempt at summarizing the thought process, adopting the first-person perspective, and aiming for a concise explanation as if speaking to a peer:
**PathPrefix: A Thoughtful Choice**
Alright, I'm thinking we should definitely lean towards using `PathPrefix` here. When considering how to handle this routing situation, it just seems like the most elegant and, frankly, the most straightforward solution. It cleanly addresses the requirement we're dealing with, allowing us to organize the routing logically within the overall structure. Itโll make things much easier to manage, troubleshoot, and scale down the line. Plus, it fits like a glove with the framework's architecture, minimizing any potential for weird edge cases or complex configurations. Yeah, `PathPrefix` it is.
|
| 95/2 |
2026/05/20 23:39 |
tool |
git-log |
0m
Args: map[CodeRegexp:order = get_order\(num\); PathPrefix:drivers/scsi/sg.c]
Results: map[Output:10db10d144c0 sg: convert the indirect IO path to use the block layer
]
|
| 96/2 |
2026/05/20 23:39 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 26356
output: 26
thoughts: 18
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm deep in my domain:
**Diving into the Code History**
Alright, time to get my hands dirty. Let's see what changed around commit `10db10d144c0`. I remember that vicinity was a crucial point, likely where we introduced that performance bottleneck or maybe integrated that major refactor. I'm going to pull up the diff right away. Need to quickly assess the context, the exact lines modified, and understand the rationale behind the changes at that time. I'm hoping it's a relatively focused change set, not some sprawling monster, so I can grasp it quickly. Let's see if the commit message offers a useful clue... ready to dig in.
|
| 97/2 |
2026/05/20 23:39 |
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)
]
|
| 98/2 |
2026/05/20 23:39 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 36210
output: 53
thoughts: 3307
Thoughts: **Analysis of Commit 10db10d144c0 and Related Issues**
Okay, here's my breakdown of this commit and the problems it introduces, as I see it. I'm focusing on the logic flow and the potential for integer overflows and memory allocation errors, based on the diffs provided.
It appears that `10db10d144c0` introduced a significant change by moving the `order = get_order(num);` and `ret_sz = 1 << (PAGE_SHIFT + order);` logic *before* the main loop in the `sg_build_indirect` function. This is immediately concerning because the value of `num` is derived from an initial value, `scatter_elem_sz`, and is later updated *within* a conditional block (`if (num < PAGE_SIZE)`). The critical issue is the fact that if `scatter_elem_sz` is initialized to zero, and the code inside the conditional block does not update `num` (which indeed it doesn't!), then `num` remains at 0, which then triggers `order = get_order(0)` causing the size argument to underflow, resulting in a large order and thus an unsafe bitwise shift. This could lead to a severe integer overflow when calculating `ret_sz`.
The code relies on `get_order(num)` returning a valid order, but in this scenario, the initial `num` could be zero if `scatter_elem_sz` is zero at the beginning. Before this commit, this wasn't a problem because `num` was re-assigned inside the loop, using a variable that guaranteed it would not be zero.
The commit also modifies how `ret_sz` is used in other functions, such as `sg_vma_fault`, `sg_mmap`, `sg_read_oxfer`, and `sg_link_reserve`. In these functions, the code shifts `1` by `PAGE_SHIFT + page_order`. These sections, before this commit, had `length = 1 << (PAGE_SHIFT + rsv_schp->page_order);` and `length` was calculated correctly. All these sections are now affected by the same vulnerability: an unchecked `page_order`.
In summary, the crux of the issue boils down to the fact that the introduction of `get_order(num)` before the loop and the potential for a zero value for `num` due to an initialization issue, *combined* with the unchecked bitwise shift, creates a clear path to undefined behavior and potential memory corruption or integer overflow errors. The commit changes are definitely the root cause. This has the potential to cause significant problems.
|
| 99/2 |
2026/05/20 23:40 |
tool |
set-results |
0m
Args: map[FixesHash:10db10d144c0248f285242f79daf6b9de6b00a62]
Results: map[FixesHash:10db10d144c0248f285242f79daf6b9de6b00a62]
|
| 100/1 |
2026/05/20 23:40 |
action |
format-fixes |
0m
Results: map[Fixes:map[Hash:10db10d144c0248f285242f79daf6b9de6b00a62 Title:sg: convert the indirect IO path to use the block layer]]
|
| 101/1 |
2026/05/20 23:40 |
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:martin.petersen@oracle.com Name:Martin K. Petersen To:true]]]
|
| 102/1 |
2026/05/20 23:40 |
action |
get-recent-commits |
0m
Results: map[RecentCommits: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
scsi: sg: Fix checking return value of blk_get_queue()
]
|
| 103/1 |
2026/05/20 23:40 |
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.
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.
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/d5a02ed91a4f019017141f71e695c75b27c3612e/drivers/scsi/sg.c:1888:13
shift exponent 64 is too large for 32-bit type 'int'
CPU: 0 UID: 0 PID: 6185 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+0x385/0x410 lib/ubsan.c:494
sg_build_indirect+0x549/0x850 drivers/scsi/sg.c:1888
sg_build_reserve drivers/scsi/sg.c:1998 [inline]
sg_add_sfp drivers/scsi/sg.c:2178 [inline]
sg_open+0x122a/0x1a40 drivers/scsi/sg.c:349
chrdev_open+0x4cd/0x5e0 fs/char_dev.c:411
do_dentry_open+0x785/0x14e0 fs/open.c:947
vfs_open+0x3b/0x340 fs/open.c:1079
do_open fs/namei.c:4699 [inline]
path_openat+0x2e08/0x3860 fs/namei.c:4858
do_file_open+0x23e/0x4a0 fs/namei.c:4887
do_sys_openat2+0x113/0x200 fs/open.c:1364
do_sys_open fs/open.c:1370 [inline]
__do_sys_openat fs/open.c:1386 [inline]
__se_sys_openat fs/open.c:1381 [inline]
__x64_sys_openat+0x138/0x170 fs/open.c:1381
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0x15f/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f72e679ce59
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:00007f72e75e3028 EFLAGS: 00000246 ORIG_RAX: 0000000000000101
RAX: ffffffffffffffda RBX: 00007f72e6a15fa0 RCX: 00007f72e679ce59
RDX: 00000000000c0482 RSI: 0000200000000000 RDI: ffffffffffffff9c
RBP: 00007f72e6832d6f R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f72e6a16038 R14: 00007f72e6a15fa0 R15: 00007ffe5f34f718
</TASK>
---[ end trace ]---
The explanation of the root cause of the bug is:
An excellent catch by syzkaller. The root cause of this crash is a missing local variable update after clamping a module parameter, combined with an unsafe bitwise shift on a signed 32-bit integer.
### Root Cause Analysis
The `sg` driver exposes the `scatter_elem_sz` module parameter, which can be modified at runtime by a privileged user via `/sys/module/sg/parameters/scatter_elem_sz`.
1. **The Sysfs Write:**
The syzkaller reproducer writes the string `"0"` to this sysfs file. The kernel parses this using `kstrtoint` and sets the global variable `scatter_elem_sz` to `0`. (Writing a negative value like `"-1"` would have the same effect).
2. **The Trigger:**
The reproducer then opens `/dev/sg0`. This invokes `sg_open()`, which calls `sg_add_sfp()`, and subsequently `sg_build_reserve()` and `sg_build_indirect()`.
3. **The Missing Variable Update:**
In `sg_build_indirect()`, the code reads `scatter_elem_sz` into a local variable `num` and attempts to clamp it to a minimum of `PAGE_SIZE`:
```c
1897 num = scatter_elem_sz;
1898 if (unlikely(num != scatter_elem_sz_prev)) {
1899 if (num < PAGE_SIZE) {
1900 scatter_elem_sz = PAGE_SIZE;
1901 scatter_elem_sz_prev = PAGE_SIZE;
1902 } else
1903 scatter_elem_sz_prev = num;
1904 }
1905
1906 order = get_order(num);
```
Notice that while the global `scatter_elem_sz` and `scatter_elem_sz_prev` are correctly clamped to `PAGE_SIZE`, **the local variable `num` is never updated**. Thus, `num` remains `0` (or negative).
4. **The `get_order()` Underflow:**
The code then calls `order = get_order(num);` where `num` is `0`.
Inside `get_order(unsigned long size)`, the size is decremented (`size--`), which underflows `0` to `0xffffffffffffffffUL`. It is then shifted right by `PAGE_SHIFT` (12), resulting in `0x000fffffffffffffUL`. The `fls64()` of this value is `52`. Thus, `get_order(0)` returns `52`.
5. **The UBSAN Shift-Out-Of-Bounds:**
Immediately after, the code calculates the return size:
```c
1907 retry:
1908 ret_sz = 1 << (PAGE_SHIFT + order);
```
With `PAGE_SHIFT` being `12` and `order` being `52`, the expression evaluates to `1 << 64`. Since the literal `1` is a signed 32-bit `int`, shifting it by 64 is undefined behavior and triggers the exact UBSAN warning seen in the crash: `shift exponent 64 is too large for 32-bit type 'int'`.
*(Note: There is also a secondary bug here. If a user intentionally writes a very large valid value like `0x7fffffff` to `scatter_elem_sz`, `order` becomes `19`. The expression `1 << (12 + 19)` evaluates to `1 << 31`, which shifts a bit into the sign bit of a signed 32-bit integerโalso undefined behavior in C).*
### Proposed Fix
To fix this, we need to update `num` to `PAGE_SIZE` when clamping, and change the literal `1` to `1UL` to prevent any undefined behavior when `order` is legitimately large.
```c
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1897,6 +1897,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1905,7 +1906,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = 1UL << (PAGE_SHIFT + order);
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
```
The diff of the bug fix is:
diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 74cd4e8a6..cb4450a89 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -1232,7 +1232,7 @@ sg_vma_fault(struct vm_fault *vmf)
"sg_vma_fault: offset=%lu, scatg=%d\n",
offset, rsv_schp->k_use_sg));
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1278,7 +1278,7 @@ sg_mmap(struct file *filp, struct vm_area_struct *vma)
}
sa = vma->vm_start;
- length = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ length = PAGE_SIZE << 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 < length) ? len : length;
@@ -1877,6 +1877,7 @@ 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) {
+ num = PAGE_SIZE;
scatter_elem_sz = PAGE_SIZE;
scatter_elem_sz_prev = PAGE_SIZE;
} else
@@ -1885,7 +1886,7 @@ sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
order = get_order(num);
retry:
- ret_sz = 1 << (PAGE_SHIFT + order);
+ ret_sz = PAGE_SIZE << order;
for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems;
k++, rem_sz -= ret_sz) {
@@ -1964,7 +1965,7 @@ sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
if ((!outp) || (num_read_xfer <= 0))
return 0;
- num = 1 << (PAGE_SHIFT + schp->page_order);
+ num = PAGE_SIZE << 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(schp->pages[k]),
@@ -2015,7 +2016,7 @@ sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
"sg_link_reserve: size=%d\n", size));
rem = size;
- num = 1 << (PAGE_SHIFT + rsv_schp->page_order);
+ num = PAGE_SIZE << rsv_schp->page_order;
for (k = 0; k < rsv_schp->k_use_sg; k++) {
if (rem <= num) {
req_schp->k_use_sg = k + 1;
Additional description of the patch:
I have applied the fix and also improved upon the initially proposed solution.
### What I did in the patch:
1. **Fixed the missing variable update:** I added `num = PAGE_SIZE;` inside the clamping block in `sg_build_indirect()`. This ensures that `num` is never 0 or negative when passed to `get_order()`. Passing 0 to `get_order()` was the root cause of the bug, as it underflows and returns a very large order (e.g., 52), which then caused the shift-out-of-bounds.
2. **Used a safer and more idiomatic size calculation:** Instead of changing `1` to `1UL` as proposed in the initial explanation, I changed the expression to `PAGE_SIZE << order`.
- The initially proposed fix `1UL << (PAGE_SHIFT + order)` would **still trigger undefined behavior** if `PAGE_SHIFT + order >= 64` (which was exactly the case here: 12 + 52 = 64, and shifting a 64-bit integer by 64 or more is UB in C).
- `PAGE_SIZE << order` shifts by `order` (which is at most 52), so it is strictly well-defined even if `order` was somehow 52.
- More importantly, `PAGE_SIZE << order` is the standard, idiomatic way in the kernel to calculate the byte size of an allocation given its page order.
3. **Applied the pattern consistently across the file:** I searched for other occurrences of the unsafe `1 << (PAGE_SHIFT + order)` pattern in `drivers/scsi/sg.c` and found four other places (`sg_vma_fault`, `sg_mmap`, `sg_read_oxfer`, and `sg_link_reserve`). While those specific places were practically safe because their `page_order` is bounded by `MAX_PAGE_ORDER`, I updated them to use `PAGE_SIZE << order` as well for consistency, robustness, and to prevent any future undefined behavior if the code is refactored.
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: 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
scsi: sg: Fix checking return value of blk_get_queue()
Reply: scsi: sg: Fix shift-out-of-bounds in sg_build_indirect()
When the scatter_elem_sz module parameter is set to 0 (or a negative value), sg_build_indirect() attempts to clamp it to PAGE_SIZE. However, while the global variables are updated, the local variable num is not. This results in num remaining 0. Calling get_order(0) underflows and returns a very large order (e.g., 52). Subsequently, the expression 1 << (PAGE_SHIFT + order) evaluates to 1 << 64, which triggers a shift-out-of-bounds undefined behavior.
Fix this by updating the local variable num to PAGE_SIZE during the clamping process to ensure it is never 0 or negative when passed to get_order(). Additionally, replace the unsafe 1 << (PAGE_SHIFT + order) pattern with the safer and more idiomatic PAGE_SIZE << order throughout the file. This prevents any potential undefined behavior if PAGE_SHIFT + order equals or exceeds 31 (or 64 for 1UL), and ensures consistency across sg_build_indirect(), sg_vma_fault(), sg_mmap(), sg_read_oxfer(), and sg_link_reserve().
|
| 104/2 |
2026/05/20 23:40 |
llm |
description-generator |
0m
Model:
Tokens:
input: 7986
output: 269
thoughts: 1824
Thoughts: **Commit Description Thoughts**
Okay, so I need to craft a commit message for this SCSI SG driver bug fix. The user's provided context clearly points to a shift-out-of-bounds issue in `sg_build_indirect()`. The problem arises when `scatter_elem_sz` is set to zero, and the clamping logic doesn't update the local variable `num`. This leads to a `get_order(0)` call, which, due to integer underflow, returns an incorrect order value, causing `1 << (PAGE_SHIFT + order)` to shift beyond the representable bit width and triggering undefined behavior.
The patch itself is straightforward: fix the missing `num = PAGE_SIZE;` inside the clamp and then replace all instances of `1 << (PAGE_SHIFT + order)` with the safer, idiomatic `PAGE_SIZE << order`. This affects `sg_build_indirect()`, `sg_vma_fault()`, `sg_mmap()`, `sg_read_oxfer()`, and `sg_link_reserve()`, ensuring consistency.
Based on recent commits, the appropriate prefix appears to be `scsi: sg: `. The summary line, which can't be longer than 72 characters, should probably be something like "scsi: sg: Fix shift-out-of-bounds in sg_build_indirect()". Let me write the description and check the line length.
I should make sure that the lines are not wrapping.
Here's the result:
```text
scsi: sg: Fix shift-out-of-bounds in sg_build_indirect()
When the scatter_elem_sz module parameter is set to 0 (or a negative value), sg_build_indirect() attempts to clamp it to PAGE_SIZE. However, while the global variables are updated, the local variable num is not. This results in num remaining 0. Calling get_order(0) underflows and returns a very large order (e.g., 52). Subsequently, the expression 1 << (PAGE_SHIFT + order) evaluates to 1 << 64, which triggers a shift-out-of-bounds undefined behavior.
Fix this by updating the local variable num to PAGE_SIZE during the clamping process to ensure it is never 0 or negative when passed to get_order(). Additionally, replace the unsafe 1 << (PAGE_SHIFT + order) pattern with the safer and more idiomatic PAGE_SIZE << order throughout the file. This prevents any potential undefined behavior if PAGE_SHIFT + order equals or exceeds 31 (or 64 for 1UL), and ensures consistency across sg_build_indirect(), sg_vma_fault(), sg_mmap(), sg_read_oxfer(), and sg_link_reserve().
```
Looks good.
|
| 105/1 |
2026/05/20 23:41 |
action |
format-patch-description |
0m
Results: map[PatchDescription:scsi: sg: Fix shift-out-of-bounds in sg_build_indirect()
When the scatter_elem_sz module parameter is set to 0 (or a negative
value), sg_build_indirect() attempts to clamp it to PAGE_SIZE. However,
while the global variables are updated, the local variable num is not.
This results in num remaining 0. Calling get_order(0) underflows and
returns a very large order (e.g., 52). Subsequently, the expression 1 <<
(PAGE_SHIFT + order) evaluates to 1 << 64, which triggers a
shift-out-of-bounds undefined behavior.
Fix this by updating the local variable num to PAGE_SIZE during the
clamping process to ensure it is never 0 or negative when passed to
get_order(). Additionally, replace the unsafe 1 << (PAGE_SHIFT + order)
pattern with the safer and more idiomatic PAGE_SIZE << order throughout
the file. This prevents any potential undefined behavior if PAGE_SHIFT +
order equals or exceeds 31 (or 64 for 1UL), and ensures consistency
across sg_build_indirect(), sg_vma_fault(), sg_mmap(), sg_read_oxfer(),
and sg_link_reserve().]
|
| 106/1 |
2026/05/20 23:41 |
action |
empty-tags |
0m
Results: map[AckedBy:<nil> ReportedBy:<nil> ReviewedBy:<nil> TestedBy:<nil>]
|