| 0/0 |
2026/07/31 06:20 |
flow |
patching |
1h35m
Results: map[AckedBy:[] Fixes:map[AuthorEmail:torvalds@ppc970.osdl.org AuthorName:Linus Torvalds Hash:1da177e4c3f41524e886b7f1b8a0c1fc7321cac2 Title:Linux-2.6.12-rc2] KernelBranch:master KernelCommit:f5098b6bae761e346ebcd9da7f95622c04733cff KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git PatchDescription:usb: gadgetfs: fix unbalanced refcount in gadgetfs_bind() error path
A KASAN slab-use-after-free can occur in gadget_dev_open() due to an
unbalanced reference count in the error path of gadgetfs_bind().
When gadgetfs_bind() is called, it performs several initialization steps.
If it succeeds, it takes a reference to the dev object by calling
get_dev(dev) at the very end of the function. This reference is meant to be
balanced by a call to put_dev(dev) inside gadgetfs_unbind() when the driver
is eventually unbound.
However, if gadgetfs_bind() fails midway (e.g., due to a memory allocation
failure in usb_ep_alloc_request() or activate_ep_files()), it jumps to the
enomem label and calls gadgetfs_unbind(gadget). Because get_dev(dev) was
never called, gadgetfs_unbind() drops a reference that was never acquired.
This leads to the dev object being freed prematurely when the file
descriptor is closed, resulting in a use-after-free when the file is opened
again.
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq
include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70
kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
...
Call trace:
...
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
To fix this, replace the monolithic gadgetfs_unbind() call in the enomem
error path with manual, step-by-step cleanup of exactly the resources that
were allocated prior to the failure. If dev->req was allocated, it is freed
and set to NULL. The gadget data pointers (gadget->ep0->driver_data,
dev->gadget, and set_gadget_data) are cleared. Note that
activate_ep_files() already cleans up after itself if it fails, so we don't
need to manually undo its effects.
This ensures that only the resources actually allocated by gadgetfs_bind()
are cleaned up, preventing the unbalanced put_dev() and incorrect state
changes that caused the use-after-free. PatchDiff:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..365f9ab4d 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,13 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request(gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data(gadget, NULL);
return -ENOMEM;
}
Recipients:[map[Email:brauner@kernel.org Name:Christian Brauner To:false] map[Email:gregkh@linuxfoundation.org Name:Greg Kroah-Hartman To:true] map[Email:jack@suse.cz Name:Jan Kara To:false] map[Email:kees@kernel.org Name:Kees Cook To:false] map[Email:linux-kernel@vger.kernel.org Name: To:false] map[Email:linux-usb@vger.kernel.org Name: To:true] map[Email:mjguzik@gmail.com Name:Mateusz Guzik To:false] map[Email:viro@zeniv.linux.org.uk Name:Al Viro To:false] map[Email:torvalds@ppc970.osdl.org Name:Linus Torvalds To:true]] ReportedBy:[] ReviewedBy:[] TestedBy:[]]
|
| 1/1 |
2026/07/31 06:20 |
action |
base-commit-picker |
0m
Results: map[KernelBranch:master KernelCommit:f5098b6bae761e346ebcd9da7f95622c04733cff KernelRepo:git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git]
|
| 2/1 |
2026/07/31 06:20 |
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 <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef __NR_mkdirat
#define __NR_mkdirat 34
#endif
#ifndef __NR_mmap
#define __NR_mmap 222
#endif
#ifndef __NR_mount
#define __NR_mount 40
#endif
#ifndef __NR_openat
#define __NR_openat 56
#endif
#ifndef __NR_write
#define __NR_write 64
#endif
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
static int inject_fault(int nth)
{
int fd;
fd = open("/proc/thread-self/fail-nth", O_RDWR);
if (fd == -1)
exit(1);
char buf[16];
sprintf(buf, "%d", nth);
if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf))
exit(1);
return fd;
}
static const char* setup_fault()
{
int fd = open("/proc/self/make-it-fail", O_WRONLY);
if (fd == -1)
return "CONFIG_FAULT_INJECTION is not enabled";
close(fd);
fd = open("/proc/thread-self/fail-nth", O_WRONLY);
if (fd == -1)
return "kernel does not have systematic fault injection support";
close(fd);
static struct {
const char* file;
const char* val;
bool fatal;
} files[] = {
{"/sys/kernel/debug/failslab/ignore-gfp-wait", "N", true},
{"/sys/kernel/debug/fail_futex/ignore-private", "N", false},
{"/sys/kernel/debug/fail_page_alloc/ignore-gfp-highmem", "N", false},
{"/sys/kernel/debug/fail_page_alloc/ignore-gfp-wait", "N", false},
{"/sys/kernel/debug/fail_page_alloc/min-order", "0", false},
};
unsigned i;
for (i = 0; i < sizeof(files) / sizeof(files[0]); i++) {
if (!write_file(files[i].file, files[i].val)) {
if (files[i].fatal)
return "failed to write fault injection file";
}
}
return NULL;
}
uint64_t r[1] = {0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x20000000ul, /*len=*/0x1000000, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x21000000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
if ((reason = setup_fault())) {
fprintf(stderr, "reproducer setup failed: fault injection: %s\n", reason);
exit(1);
}
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// mkdirat arguments: [
// fd: fd_dir (resource)
// path: ptr[in, buffer] {
// buffer: {2e 2f 67 61 64 67 65 74 00} (length 0x9)
// }
// mode: open_mode = 0x1ff (8 bytes)
// ]
memcpy((void*)0x20000100, "./gadget\000", 9);
syscall(__NR_mkdirat, /*fd=*/0xffffff9c, /*path=*/0x20000100ul, /*mode=S_IXOTH|S_IWOTH|S_IROTH|S_IXGRP|S_IWGRP|S_IRGRP|S_IXUSR|S_IWUSR|0x100*/0x1fful);
// mount arguments: [
// src: nil
// dst: ptr[in, buffer] {
// buffer: {2e 2f 67 61 64 67 65 74 00} (length 0x9)
// }
// type: ptr[in, buffer] {
// buffer: {67 61 64 67 65 74 66 73 00} (length 0x9)
// }
// flags: mount_flags = 0x0 (8 bytes)
// data: nil
// ]
memcpy((void*)0x20000140, "./gadget\000", 9);
memcpy((void*)0x20000180, "gadgetfs\000", 9);
syscall(__NR_mount, /*src=*/0ul, /*dst=*/0x20000140ul, /*type=*/0x20000180ul, /*flags=*/0ul, /*data=*/0ul);
// openat arguments: [
// fd: fd_dir (resource)
// file: ptr[in, buffer] {
// buffer: {2e 2f 67 61 64 67 65 74 2f 64 75 6d 6d 79 5f 75 64 63 00} (length 0x13)
// }
// flags: open_flags = 0x2 (4 bytes)
// mode: open_mode = 0x0 (2 bytes)
// ]
// returns fd
memcpy((void*)0x200001c0, "./gadget/dummy_udc\000", 19);
res = syscall(__NR_openat, /*fd=*/0xffffff9c, /*file=*/0x200001c0ul, /*flags=O_RDWR*/2, /*mode=*/0);
if (res != -1)
r[0] = res;
// write arguments: [
// fd: fd (resource)
// buf: ptr[in, buffer] {
// buffer: {00 00 00 00 09 02 19 00 01 01 00 80 32 09 04 00 00 01 ff 00 00 00 07 05 81 02 40 00 00 09 02 19 00 01 01 00 80 32 09 04 00 00 01 ff 00 00 00 07 05 81 02 00 02 00 12 01 00 02 00 00 00 40 34 12 78 56 00 01 00 00 00 01} (length 0x48)
// }
// count: len = 0x48 (8 bytes)
// ]
memcpy((void*)0x20000200, "... [truncated large byte array] ...", 72);
inject_fault(13);
syscall(__NR_write, /*fd=*/r[0], /*buf=*/0x20000200ul, /*count=*/0x48ul);
return 0;
}
]
|
| 3/1 |
2026/07/31 06:20 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/app/workdir/cache/src/3735123449433f9e6f9fb5b55ddd9994cbcf15f0]
|
| 4/1 |
2026/07/31 06:20 |
action |
kernel-builder |
0m
Results: map[KernelObj:/app/workdir/cache/build/9489f6eebc7a3b82dc732d7cd595837dda1629c4]
|
| 5/1 |
2026/07/31 06:20 |
action |
crash-reproducer |
5m
Results: map[OtherCrashReports:<nil> ReproducedBugTitle:KASAN: slab-use-after-free Read in gadget_dev_open ReproducedCrashReport:==================================================================
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Not tainted syzkaller #1 PREEMPT
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
print_address_description+0xb0/0x238 mm/kasan/report.c:378
print_report+0x68/0x84 mm/kasan/report.c:482
kasan_report+0x8c/0xc4 mm/kasan/report.c:595
__kasan_check_byte+0x3c/0x54 mm/kasan/common.c:574
kasan_check_byte include/linux/kasan.h:402 [inline]
lock_acquire+0xa4/0x364 kernel/locking/lockdep.c:5842
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Allocated by task 5241:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_alloc_info+0x44/0x54 mm/kasan/generic.c:570
poison_kmalloc_redzone mm/kasan/common.c:398 [inline]
__kasan_kmalloc+0x9c/0xb4 mm/kasan/common.c:415
kasan_kmalloc include/linux/kasan.h:263 [inline]
__kmalloc_cache_noprof+0x2e8/0x5ec mm/slub.c:5489
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
dev_new drivers/usb/gadget/legacy/inode.c:176 [inline]
gadgetfs_fill_super+0x19c/0x370 drivers/usb/gadget/legacy/inode.c:2054
vfs_get_super+0xb8/0x148 fs/super.c:1273
get_tree_single+0x30/0x40 fs/super.c:1300
gadgetfs_get_tree+0x28/0x38 drivers/usb/gadget/legacy/inode.c:2085
vfs_get_tree+0x90/0x28c fs/super.c:1700
fc_mount+0x24/0xac fs/namespace.c:1198
do_new_mount_fc fs/namespace.c:3765 [inline]
do_new_mount+0x2a4/0x538 fs/namespace.c:3841
path_mount+0x5f0/0xa88 fs/namespace.c:4161
do_mount+0xe8/0x148 fs/namespace.c:4174
__do_sys_mount fs/namespace.c:4390 [inline]
__se_sys_mount fs/namespace.c:4367 [inline]
__arm64_sys_mount+0x334/0x380 fs/namespace.c:4367
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Freed by task 5331:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_free_info+0x58/0x70 mm/kasan/generic.c:584
poison_slab_object mm/kasan/common.c:253 [inline]
__kasan_slab_free+0x74/0xa4 mm/kasan/common.c:285
kasan_slab_free include/linux/kasan.h:235 [inline]
slab_free_hook mm/slub.c:2677 [inline]
slab_free mm/slub.c:6377 [inline]
kfree+0x188/0x690 mm/slub.c:6692
put_dev+0x8c/0xf8 drivers/usb/gadget/legacy/inode.c:169
dev_release+0x100/0x15c drivers/usb/gadget/legacy/inode.c:1215
__fput+0x338/0x74c fs/file_table.c:512
____fput+0x20/0x30 fs/file_table.c:540
task_work_run+0x1cc/0x25c kernel/task_work.c:233
resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]
__exit_to_user_mode_loop kernel/entry/common.c:70 [inline]
exit_to_user_mode_loop+0x10c/0x17c kernel/entry/common.c:101
__exit_to_user_mode_prepare include/linux/irq-entry-common.h:207 [inline]
syscall_exit_to_user_mode_prepare include/linux/irq-entry-common.h:230 [inline]
arm64_syscall_exit_to_user_mode arch/arm64/kernel/entry-common.c:88 [inline]
el0_svc+0x18c/0x260 arch/arm64/kernel/entry-common.c:737
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
The buggy address belongs to the object at ffff0000dbe16000
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 24 bytes inside of
freed 1024-byte region [ffff0000dbe16000, ffff0000dbe16400)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff0000dbe15000 pfn:0x11be10
head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
flags: 0x5ffc00000000240(workingset|head|node=0|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
raw: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
head: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000003 fffffdffc36f8401 00000000ffffffff 00000000ffffffff
head: ffffffffffffffff 0000000000000000 00000000ffffffff 0000000000000008
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff0000dbe15f00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff0000dbe15f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff0000dbe16000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff0000dbe16080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff0000dbe16100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
------------[ cut here ]------------
UBSAN: array-index-out-of-bounds in /app/workdir/cache/src/3735123449433f9e6f9fb5b55ddd9994cbcf15f0/kernel/locking/qspinlock.h:68:9
index 13031 is out of range for type 'unsigned long[8]'
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
ubsan_epilogue+0x14/0x48 lib/ubsan.c:233
__ubsan_handle_out_of_bounds+0xd0/0xf8 lib/ubsan.c:455
decode_tail kernel/locking/qspinlock.h:68 [inline]
queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
---[ end trace ]---
Unable to handle kernel paging request at virtual address ffff800088b48710
KASAN: probably user-memory-access in range [0x0000000445a43880-0x0000000445a43887]
Mem abort info:
ESR = 0x0000000096000047
EC = 0x25: DABT (current EL), IL = 32 bits
SET = 0, FnV = 0
EA = 0, S1PTW = 0
FSC = 0x07: level 3 translation fault
Data abort info:
ISV = 0, ISS = 0x00000047, ISS2 = 0x00000000
CM = 0, WnR = 1, TnD = 0, TagAccess = 0
GCS = 0, Overlay = 0, DirtyBit = 0
swapper pgtable: 4k pages, 48-bit VAs, pgdp=000000021aeb5000
[ffff800088b48710] pgd=0000000000000000, p4d=10000002211ac003, pud=10000002211ad003, pmd=10000002211b1003, pte=0000000000000000
Internal error: Oops: 0000000096000047 [#1] SMP
Modules linked in:
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
pstate: 834000c5 (Nzcv daIF +PAN -UAO +TCO +DIT -SSBS BTYPE=--)
pc : queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:288
lr : decode_tail kernel/locking/qspinlock.h:68 [inline]
lr : queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
sp : ffff800097c37560
x29: ffff800097c37600 x28: ffff800088b48710 x27: 1fffe00019980afa
x26: 1fffe0001b7c2c00 x25: ffff0001add9f708 x24: dfff800000000000
x23: ffff700012f86eb0 x22: ffff0001add9f700 x21: 1fffe00035bb3ee0
x20: ffff0000ccc057d0 x19: ffff0000dbe16000 x18: 0000000000000000
x17: 3d3d3d3d3d3d3d3d x16: 0000000000000001 x15: 0000000000000000
x14: 0000000000000000 x13: 0000000000000001 x12: 0000000000000004
x11: ffff700011474c6c x10: ffff800088b48700 x9 : ffff800088b48710
x8 : 0000000000000000 x7 : 0000000000000001 x6 : ffff80008048d694
x5 : 0000000000000000 x4 : 0000000000000000 x3 : ffff8000802f6c98
x2 : 0000000000000002 x1 : 0000000000000004 x0 : ffff0001add9f708
Call trace:
queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:291 (P)
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Code: aa1c03e0 968a785a 910022c0 52800081 (f9000396)
---[ end trace 0000000000000000 ]---
----------------
Code disassembly (best guess):
0: aa1c03e0 mov x0, x28
4: 968a785a bl 0xfffffffffa29e16c
8: 910022c0 add x0, x22, #0x8
c: 52800081 mov w1, #0x4 // #4
* 10: f9000396 str x22, [x28] <-- trapping instruction
ReproducedFaultInjection:FAULT_INJECTION: forcing a failure.
name failslab, interval 1, probability 0, space 0, times 1
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
fail_dump lib/fault-inject.c:73 [inline]
should_fail_ex+0x41c/0x590 lib/fault-inject.c:174
should_failslab+0xc4/0x120 mm/failslab.c:46
slab_pre_alloc_hook mm/slub.c:4539 [inline]
slab_alloc_node mm/slub.c:4897 [inline]
__kmalloc_cache_noprof+0x94/0x5ec mm/slub.c:5485
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
activate_ep_files drivers/usb/gadget/legacy/inode.c:1601 [inline]
gadgetfs_bind+0x204/0x75c drivers/usb/gadget/legacy/inode.c:1692
gadget_bind_driver+0x274/0x834 drivers/usb/gadget/udc/core.c:1662
call_driver_probe drivers/base/dd.c:-1 [inline]
really_probe+0x29c/0x800 drivers/base/dd.c:706
__driver_probe_device+0x1e0/0x350 drivers/base/dd.c:868
driver_probe_device+0x6c/0x19c drivers/base/dd.c:898
__driver_attach+0x168/0x384 drivers/base/dd.c:1292
bus_for_each_dev+0x128/0x1b4 drivers/base/bus.c:383
driver_attach+0x50/0x60 drivers/base/dd.c:1310
bus_add_driver+0x208/0x500 drivers/base/bus.c:763
driver_register+0x220/0x310 drivers/base/driver.c:174
usb_gadget_register_driver_owner+0xf0/0x25c drivers/usb/gadget/udc/core.c:1752
dev_config+0x91c/0xcc0 drivers/usb/gadget/legacy/inode.c:1883
vfs_write+0x2a4/0xa0c fs/read_write.c:685
ksys_write+0x12c/0x228 fs/read_write.c:739
__do_sys_write fs/read_write.c:750 [inline]
__se_sys_write fs/read_write.c:747 [inline]
__arm64_sys_write+0x7c/0x90 fs/read_write.c:747
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594]
|
| 6/1 |
2026/07/31 06:25 |
action |
codesearch-prepare |
0m
Results: map[Index:codesearch-index]
|
| 7/1 |
2026/07/31 06:25 |
agent |
debugger |
17m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with debugging a kernel crash root cause.
You need to provide a detailed explanation of the root cause for another developer to be
able to write a fix for the bug based on your explanation. Include all relevant details
into the response: function/struct/field/etc names, code snippets, line numbers,
macro/enum values, etc.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
==================================================================
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Not tainted syzkaller #1 PREEMPT
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
print_address_description+0xb0/0x238 mm/kasan/report.c:378
print_report+0x68/0x84 mm/kasan/report.c:482
kasan_report+0x8c/0xc4 mm/kasan/report.c:595
__kasan_check_byte+0x3c/0x54 mm/kasan/common.c:574
kasan_check_byte include/linux/kasan.h:402 [inline]
lock_acquire+0xa4/0x364 kernel/locking/lockdep.c:5842
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Allocated by task 5241:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_alloc_info+0x44/0x54 mm/kasan/generic.c:570
poison_kmalloc_redzone mm/kasan/common.c:398 [inline]
__kasan_kmalloc+0x9c/0xb4 mm/kasan/common.c:415
kasan_kmalloc include/linux/kasan.h:263 [inline]
__kmalloc_cache_noprof+0x2e8/0x5ec mm/slub.c:5489
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
dev_new drivers/usb/gadget/legacy/inode.c:176 [inline]
gadgetfs_fill_super+0x19c/0x370 drivers/usb/gadget/legacy/inode.c:2054
vfs_get_super+0xb8/0x148 fs/super.c:1273
get_tree_single+0x30/0x40 fs/super.c:1300
gadgetfs_get_tree+0x28/0x38 drivers/usb/gadget/legacy/inode.c:2085
vfs_get_tree+0x90/0x28c fs/super.c:1700
fc_mount+0x24/0xac fs/namespace.c:1198
do_new_mount_fc fs/namespace.c:3765 [inline]
do_new_mount+0x2a4/0x538 fs/namespace.c:3841
path_mount+0x5f0/0xa88 fs/namespace.c:4161
do_mount+0xe8/0x148 fs/namespace.c:4174
__do_sys_mount fs/namespace.c:4390 [inline]
__se_sys_mount fs/namespace.c:4367 [inline]
__arm64_sys_mount+0x334/0x380 fs/namespace.c:4367
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Freed by task 5331:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_free_info+0x58/0x70 mm/kasan/generic.c:584
poison_slab_object mm/kasan/common.c:253 [inline]
__kasan_slab_free+0x74/0xa4 mm/kasan/common.c:285
kasan_slab_free include/linux/kasan.h:235 [inline]
slab_free_hook mm/slub.c:2677 [inline]
slab_free mm/slub.c:6377 [inline]
kfree+0x188/0x690 mm/slub.c:6692
put_dev+0x8c/0xf8 drivers/usb/gadget/legacy/inode.c:169
dev_release+0x100/0x15c drivers/usb/gadget/legacy/inode.c:1215
__fput+0x338/0x74c fs/file_table.c:512
____fput+0x20/0x30 fs/file_table.c:540
task_work_run+0x1cc/0x25c kernel/task_work.c:233
resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]
__exit_to_user_mode_loop kernel/entry/common.c:70 [inline]
exit_to_user_mode_loop+0x10c/0x17c kernel/entry/common.c:101
__exit_to_user_mode_prepare include/linux/irq-entry-common.h:207 [inline]
syscall_exit_to_user_mode_prepare include/linux/irq-entry-common.h:230 [inline]
arm64_syscall_exit_to_user_mode arch/arm64/kernel/entry-common.c:88 [inline]
el0_svc+0x18c/0x260 arch/arm64/kernel/entry-common.c:737
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
The buggy address belongs to the object at ffff0000dbe16000
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 24 bytes inside of
freed 1024-byte region [ffff0000dbe16000, ffff0000dbe16400)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff0000dbe15000 pfn:0x11be10
head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
flags: 0x5ffc00000000240(workingset|head|node=0|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
raw: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
head: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000003 fffffdffc36f8401 00000000ffffffff 00000000ffffffff
head: ffffffffffffffff 0000000000000000 00000000ffffffff 0000000000000008
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff0000dbe15f00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff0000dbe15f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff0000dbe16000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff0000dbe16080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff0000dbe16100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
------------[ cut here ]------------
UBSAN: array-index-out-of-bounds in /app/workdir/cache/src/3735123449433f9e6f9fb5b55ddd9994cbcf15f0/kernel/locking/qspinlock.h:68:9
index 13031 is out of range for type 'unsigned long[8]'
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
ubsan_epilogue+0x14/0x48 lib/ubsan.c:233
__ubsan_handle_out_of_bounds+0xd0/0xf8 lib/ubsan.c:455
decode_tail kernel/locking/qspinlock.h:68 [inline]
queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
---[ end trace ]---
Unable to handle kernel paging request at virtual address ffff800088b48710
KASAN: probably user-memory-access in range [0x0000000445a43880-0x0000000445a43887]
Mem abort info:
ESR = 0x0000000096000047
EC = 0x25: DABT (current EL), IL = 32 bits
SET = 0, FnV = 0
EA = 0, S1PTW = 0
FSC = 0x07: level 3 translation fault
Data abort info:
ISV = 0, ISS = 0x00000047, ISS2 = 0x00000000
CM = 0, WnR = 1, TnD = 0, TagAccess = 0
GCS = 0, Overlay = 0, DirtyBit = 0
swapper pgtable: 4k pages, 48-bit VAs, pgdp=000000021aeb5000
[ffff800088b48710] pgd=0000000000000000, p4d=10000002211ac003, pud=10000002211ad003, pmd=10000002211b1003, pte=0000000000000000
Internal error: Oops: 0000000096000047 [#1] SMP
Modules linked in:
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
pstate: 834000c5 (Nzcv daIF +PAN -UAO +TCO +DIT -SSBS BTYPE=--)
pc : queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:288
lr : decode_tail kernel/locking/qspinlock.h:68 [inline]
lr : queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
sp : ffff800097c37560
x29: ffff800097c37600 x28: ffff800088b48710 x27: 1fffe00019980afa
x26: 1fffe0001b7c2c00 x25: ffff0001add9f708 x24: dfff800000000000
x23: ffff700012f86eb0 x22: ffff0001add9f700 x21: 1fffe00035bb3ee0
x20: ffff0000ccc057d0 x19: ffff0000dbe16000 x18: 0000000000000000
x17: 3d3d3d3d3d3d3d3d x16: 0000000000000001 x15: 0000000000000000
x14: 0000000000000000 x13: 0000000000000001 x12: 0000000000000004
x11: ffff700011474c6c x10: ffff800088b48700 x9 : ffff800088b48710
x8 : 0000000000000000 x7 : 0000000000000001 x6 : ffff80008048d694
x5 : 0000000000000000 x4 : 0000000000000000 x3 : ffff8000802f6c98
x2 : 0000000000000002 x1 : 0000000000000004 x0 : ffff0001add9f708
Call trace:
queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:291 (P)
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Code: aa1c03e0 968a785a 910022c0 52800081 (f9000396)
---[ end trace 0000000000000000 ]---
----------------
Code disassembly (best guess):
0: aa1c03e0 mov x0, x28
4: 968a785a bl 0xfffffffffa29e16c
8: 910022c0 add x0, x22, #0x8
c: 52800081 mov w1, #0x4 // #4
* 10: f9000396 str x22, [x28] <-- trapping instruction
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 <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef __NR_mkdirat
#define __NR_mkdirat 34
#endif
#ifndef __NR_mmap
#define __NR_mmap 222
#endif
#ifndef __NR_mount
#define __NR_mount 40
#endif
#ifndef __NR_openat
#define __NR_openat 56
#endif
#ifndef __NR_write
#define __NR_write 64
#endif
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
static int inject_fault(int nth)
{
int fd;
fd = open("/proc/thread-self/fail-nth", O_RDWR);
if (fd == -1)
exit(1);
char buf[16];
sprintf(buf, "%d", nth);
if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf))
exit(1);
return fd;
}
static const char* setup_fault()
{
int fd = open("/proc/self/make-it-fail", O_WRONLY);
if (fd == -1)
return "CONFIG_FAULT_INJECTION is not enabled";
close(fd);
fd = open("/proc/thread-self/fail-nth", O_WRONLY);
if (fd == -1)
return "kernel does not have systematic fault injection support";
close(fd);
static struct {
const char* file;
const char* val;
bool fatal;
} files[] = {
{"/sys/kernel/debug/failslab/ignore-gfp-wait", "N", true},
{"/sys/kernel/debug/fail_futex/ignore-private", "N", false},
{"/sys/kernel/debug/fail_page_alloc/ignore-gfp-highmem", "N", false},
{"/sys/kernel/debug/fail_page_alloc/ignore-gfp-wait", "N", false},
{"/sys/kernel/debug/fail_page_alloc/min-order", "0", false},
};
unsigned i;
for (i = 0; i < sizeof(files) / sizeof(files[0]); i++) {
if (!write_file(files[i].file, files[i].val)) {
if (files[i].fatal)
return "failed to write fault injection file";
}
}
return NULL;
}
uint64_t r[1] = {0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x20000000ul, /*len=*/0x1000000, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x21000000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
if ((reason = setup_fault())) {
fprintf(stderr, "reproducer setup failed: fault injection: %s\n", reason);
exit(1);
}
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// mkdirat arguments: [
// fd: fd_dir (resource)
// path: ptr[in, buffer] {
// buffer: {2e 2f 67 61 64 67 65 74 00} (length 0x9)
// }
// mode: open_mode = 0x1ff (8 bytes)
// ]
memcpy((void*)0x20000100, "./gadget\000", 9);
syscall(__NR_mkdirat, /*fd=*/0xffffff9c, /*path=*/0x20000100ul, /*mode=S_IXOTH|S_IWOTH|S_IROTH|S_IXGRP|S_IWGRP|S_IRGRP|S_IXUSR|S_IWUSR|0x100*/0x1fful);
// mount arguments: [
// src: nil
// dst: ptr[in, buffer] {
// buffer: {2e 2f 67 61 64 67 65 74 00} (length 0x9)
// }
// type: ptr[in, buffer] {
// buffer: {67 61 64 67 65 74 66 73 00} (length 0x9)
// }
// flags: mount_flags = 0x0 (8 bytes)
// data: nil
// ]
memcpy((void*)0x20000140, "./gadget\000", 9);
memcpy((void*)0x20000180, "gadgetfs\000", 9);
syscall(__NR_mount, /*src=*/0ul, /*dst=*/0x20000140ul, /*type=*/0x20000180ul, /*flags=*/0ul, /*data=*/0ul);
// openat arguments: [
// fd: fd_dir (resource)
// file: ptr[in, buffer] {
// buffer: {2e 2f 67 61 64 67 65 74 2f 64 75 6d 6d 79 5f 75 64 63 00} (length 0x13)
// }
// flags: open_flags = 0x2 (4 bytes)
// mode: open_mode = 0x0 (2 bytes)
// ]
// returns fd
memcpy((void*)0x200001c0, "./gadget/dummy_udc\000", 19);
res = syscall(__NR_openat, /*fd=*/0xffffff9c, /*file=*/0x200001c0ul, /*flags=O_RDWR*/2, /*mode=*/0);
if (res != -1)
r[0] = res;
// write arguments: [
// fd: fd (resource)
// buf: ptr[in, buffer] {
// buffer: {00 00 00 00 09 02 19 00 01 01 00 80 32 09 04 00 00 01 ff 00 00 00 07 05 81 02 40 00 00 09 02 19 00 01 01 00 80 32 09 04 00 00 01 ff 00 00 00 07 05 81 02 00 02 00 12 01 00 02 00 00 00 40 34 12 78 56 00 01 00 00 00 01} (length 0x48)
// }
// count: len = 0x48 (8 bytes)
// ]
memcpy((void*)0x20000200, "... [truncated large byte array] ...", 72);
inject_fault(13);
syscall(__NR_write, /*fd=*/r[0], /*buf=*/0x20000200ul, /*count=*/0x48ul);
return 0;
}
The reproducer uses fault injection to force allocation failure at a specific point.
These injected failures often exercise rarely used error-handling paths,
so the bug is frequently in that error handling.
The following fault injection report(s) show what was injected:
FAULT_INJECTION: forcing a failure.
name failslab, interval 1, probability 0, space 0, times 1
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
fail_dump lib/fault-inject.c:73 [inline]
should_fail_ex+0x41c/0x590 lib/fault-inject.c:174
should_failslab+0xc4/0x120 mm/failslab.c:46
slab_pre_alloc_hook mm/slub.c:4539 [inline]
slab_alloc_node mm/slub.c:4897 [inline]
__kmalloc_cache_noprof+0x94/0x5ec mm/slub.c:5485
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
activate_ep_files drivers/usb/gadget/legacy/inode.c:1601 [inline]
gadgetfs_bind+0x204/0x75c drivers/usb/gadget/legacy/inode.c:1692
gadget_bind_driver+0x274/0x834 drivers/usb/gadget/udc/core.c:1662
call_driver_probe drivers/base/dd.c:-1 [inline]
really_probe+0x29c/0x800 drivers/base/dd.c:706
__driver_probe_device+0x1e0/0x350 drivers/base/dd.c:868
driver_probe_device+0x6c/0x19c drivers/base/dd.c:898
__driver_attach+0x168/0x384 drivers/base/dd.c:1292
bus_for_each_dev+0x128/0x1b4 drivers/base/bus.c:383
driver_attach+0x50/0x60 drivers/base/dd.c:1310
bus_add_driver+0x208/0x500 drivers/base/bus.c:763
driver_register+0x220/0x310 drivers/base/driver.c:174
usb_gadget_register_driver_owner+0xf0/0x25c drivers/usb/gadget/udc/core.c:1752
dev_config+0x91c/0xcc0 drivers/usb/gadget/legacy/inode.c:1883
vfs_write+0x2a4/0xa0c fs/read_write.c:685
ksys_write+0x12c/0x228 fs/read_write.c:739
__do_sys_write fs/read_write.c:750 [inline]
__se_sys_write fs/read_write.c:747 [inline]
__arm64_sys_write+0x7c/0x90 fs/read_write.c:747
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Reply: The root cause of this KASAN slab-use-after-free is a reference counting bug in the error path of `gadgetfs_bind()` in `drivers/usb/gadget/legacy/inode.c`.
When the gadget driver is being bound, `gadgetfs_bind()` performs several initialization steps. If it succeeds, it takes a reference to the `dev` object by calling `get_dev(dev)` at the very end of the function. This reference is meant to be balanced by a call to `put_dev(dev)` inside `gadgetfs_unbind()` when the driver is eventually unbound.
However, if `gadgetfs_bind()` fails midway (e.g., due to the fault injection causing `activate_ep_files()` to fail), it jumps to the `enomem` label and calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**.
### Detailed Trace
1. **Initialization**: When the gadgetfs is mounted, `gadgetfs_fill_super()` calls `dev_new()`, which initializes the `dev` object with a refcount of `1`.
2. **First Open**: The reproducer opens the `ep0` file (`dummy_udc`). This calls `gadget_dev_open()`, which increments the refcount to `2` via `get_dev(dev)`.
3. **Configuration**: The reproducer writes to the `ep0` file descriptor, triggering `dev_config()`. This parses the descriptors and calls `usb_gadget_register_driver()`, which in turn calls `gadgetfs_bind()`.
4. **Fault Injection**: Inside `gadgetfs_bind()`, `activate_ep_files()` fails due to the injected memory allocation failure.
5. **The Bug**: `gadgetfs_bind()` jumps to the `enomem` label and calls `gadgetfs_unbind()`. `gadgetfs_unbind()` calls `put_dev(dev)`, dropping the refcount to `1`. (It should have remained `2` because `gadgetfs_bind()` never took its reference).
6. **File Close**: The `write()` syscall returns `-ENOMEM`. The reproducer process exits (or closes the file descriptor), triggering `dev_release()`. This calls `put_dev(dev)`, dropping the refcount to `0`. The `dev` object is freed.
7. **Use-After-Free**: The reproducer (or another thread) opens the `ep0` file again. `gadget_dev_open()` is called, which accesses the freed `dev` object via `inode->i_private` to acquire `dev->lock`, resulting in the KASAN slab-use-after-free crash.
### The Fix
Instead of calling `gadgetfs_unbind()` on failure, `gadgetfs_bind()` should manually undo the specific initialization steps it performed before the failure.
Note that `activate_ep_files()` already cleans up after itself if it fails (by calling `destroy_ep_files()`), so we only need to free `dev->req` (if it was allocated) and clear the gadget data pointers.
```c
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,12 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
```
By doing this manual cleanup, we avoid the unbalanced `put_dev(dev)`, prevent `dev->state` from being incorrectly set to `STATE_DEV_UNBOUND` (which would prevent the user from retrying the configuration write), and avoid redundant calls to `destroy_ep_files()`.
|
| 8/2 |
2026/07/31 06:25 |
llm |
debugger |
0m
Model:
Tokens:
input: 13730
output: 42
thoughts: 178
Thoughts: **KASAN Slab-Use-After-Free Analysis**
Okay, so I've got a KASAN use-after-free issue here, specifically within `__raw_spin_lock_irq`. It's being triggered from `gadget_dev_open`, and the trace points to `drivers/usb/gadget/legacy/inode.c:1919`. That's not ideal, but at least we have a starting point.
The object in question was initially allocated by `dev_new`, which we'll find in `drivers/usb/gadget/legacy/inode.c:176`. Good, so we know where it's created. Now, let's see when it gets freed. The report indicates `put_dev` at `drivers/usb/gadget/legacy/inode.c:169` is responsible for freeing the memory, and that function is called from `dev_release` (at line 1215), which in turn, looks to be called through `__fput`. That call chain gives us a likely path to follow.
So, the next logical step is to dive into `gadget_dev_open` in `drivers/usb/gadget/legacy/inode.c`. That's where the critical problem code is running. I need to understand how this object is being allocated, used, and then *potentially* accessed after it's been freed in `put_dev` and its call chain. Time to go hunting for the bug.
|
| 9/2 |
2026/07/31 06:25 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadget_dev_open]
Results: map[SourceCode:1913: static int
1914: gadget_dev_open (struct inode *inode, struct file *fd)
1915: {
1916: struct dev_data *dev = inode->i_private;
1917: int value = -EBUSY;
1918:
1919: spin_lock_irq(&dev->lock);
1920: if (dev->state == STATE_DEV_DISABLED) {
1921: dev->ev_next = 0;
1922: dev->state = STATE_DEV_OPENED;
1923: fd->private_data = dev;
1924: get_dev (dev);
1925: value = 0;
1926: }
1927: spin_unlock_irq(&dev->lock);
1928: return value;
1929: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 10/2 |
2026/07/31 06:25 |
llm |
debugger |
0m
Model:
Tokens:
input: 14554
output: 39
thoughts: 38
Thoughts: Okay, here's my interpretation of that thought process, from an expert's perspective:
**Diving into the Device Data Structure**
Right, so I'm focusing on how `dev` is being handled, and it seems like it's crucial here. My immediate thought is, "Ah, `dev` is actually pointing to `inode->i_private`." That's a classic way to associate custom, device-specific data with an inode, very common. Then, I'm reminding myself that this `dev` variable is of type `struct dev_data`. Excellent, now I know the data structure I'm dealing with.
Okay, let's see, now I need to refresh my memory on the lifecycle of this `dev_data` structure. Time to look at `dev_new` and `put_dev`. I expect these functions handle object allocation/deallocation or reference counting to manage the lifecycle of this structure. I need to understand when this `dev` is created, how it's initialized, and, critically, how its resources are managed. This gives me the clue to look at how we manage the objects and resources.
|
| 11/2 |
2026/07/31 06:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:dev_new]
Results: map[SourceCode: 172: static struct dev_data *dev_new (void)
173: {
174: struct dev_data *dev;
175:
176: dev = kzalloc_obj(*dev);
177: if (!dev)
178: return NULL;
179: dev->state = STATE_DEV_DISABLED;
180: refcount_set (&dev->count, 1);
181: spin_lock_init (&dev->lock);
182: INIT_LIST_HEAD (&dev->epfiles);
183: init_waitqueue_head (&dev->wait);
184: return dev;
185: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 12/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 15105
output: 39
thoughts: 6
Thoughts: Okay, I'm ready. Here's a summary as if I'm processing the "Thoughts:" provided, keeping in mind I'm an expert and presenting it in a fulsome manner:
**Internal Processing of the `put_dev` Concept**
Alright, let's break this down. When I see the term `put_dev`, my mind immediately starts assembling the components of what that implies, especially within a development context. My initial thought is to ascertain the scope: is this a general concept, a specific implementation detail, or something else entirely? The vagueness necessitates delving deeper.
My immediate assumptions are linked to some kind of 'placement' function for 'dev' - that makes sense, as a short for development. I wonder if this relates to deployment. This could be about a piece of code, a development resource, a configuration file, or an entire development environment. The core function is about getting something "in place" for the development process. "Put" implies an active action, a command, an intervention. Where is it being placed - locally, on a test server, in a staging environment? The destination is critical.
I'm thinking about the implications. Is this about provisioning a new development environment, updating an existing one, or just setting up a single development resource? It might be related to testing, such as deploying a development version to a testing area, but that may be a function that comes after.
The context is important. Is this part of a larger automation script, an interactive tool, or a part of a configuration management system? The specific method of putting something might range from a basic file copy to sophisticated orchestration through APIs or infrastructure-as-code tools. It could trigger a build process or a deployment pipeline.
Essentially, `put_dev` immediately prompts me to consider the "what, where, how, and why" of development resource placement. I'm already anticipating questions about permissions, versioning, dependencies, and potential conflicts. My expert eye is scanning for potential vulnerabilities, efficiencies, and areas that could be streamlined. I'm essentially starting to outline the potential for automation, error handling, and overall optimization related to this function. This function feels like it is a starting point, and that more is required to understand its use and how it will be properly used.
|
| 13/2 |
2026/07/31 06:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:put_dev]
Results: map[SourceCode: 163: static void put_dev (struct dev_data *data)
164: {
165: if (likely (!refcount_dec_and_test (&data->count)))
166: return;
167: /* needs no more cleanup */
168: BUG_ON (waitqueue_active (&data->wait));
169: kfree (data);
170: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 14/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 15777
output: 39
thoughts: 6
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Analyzing the `dev_release` Process**
Alright, let's break this down. The term `dev_release`... instantly, my mind goes to the various connotations. Is this a specific pipeline? A branching strategy? A general process for pushing code from development environments into a release candidate state? The ambiguity is actually a good starting point because it forces me to think generically, and also to make some assumptions which I can then later check against.
My initial line of thought involves considering how this `dev_release` cycle interacts with established software development best practices. We need to look at what the existing release cadence looks like, the degree of automation, and the level of testing performed throughout the release lifecycle.
If this is a mature project, then this implies a well defined version control strategy. How are feature branches merged? Is there continuous integration (CI) automatically testing commits, pull requests, and the final merge? That is crucial, because CI should identify most defects. Also, is continuous deployment (CD) present and how much of it is automated? And are there any manual steps still in this process?
If we're talking about a more rapid or less mature development cycle, then `dev_release` might be more ad-hoc. I will need to consider whether that is sustainable long-term. Is the current team size adequate? What kind of documentation exists for this process? Is there automated logging and monitoring, which enables fast detection and mitigation of issues? How are rollback procedures handled?
I'm also immediately wondering about potential risks. Security vulnerabilities, breaking changes, data integrity issues... I need to consider all the failure modes. What are the key performance indicators (KPIs) we're tracking related to this `dev_release`? Are they sufficient?
Ultimately, the goal is a smooth, reliable transition of code from development into a state suitable for a more formal release. To analyze this, I will need some more data on the exact context.
|
| 15/2 |
2026/07/31 06:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:dev_release]
Results: map[SourceCode:1190: static int
1191: dev_release (struct inode *inode, struct file *fd)
1192: {
1193: struct dev_data *dev = fd->private_data;
1194:
1195: /* closing ep0 === shutdown all */
1196:
1197: if (dev->gadget_registered) {
1198: usb_gadget_unregister_driver (&gadgetfs_driver);
1199: dev->gadget_registered = false;
1200: }
1201:
1202: /* at this point "good" hardware has disconnected the
1203: * device from USB; the host won't see it any more.
1204: * alternatively, all host requests will time out.
1205: */
1206:
1207: kfree (dev->buf);
1208: dev->buf = NULL;
1209:
1210: /* other endpoints were all decoupled from this device */
1211: spin_lock_irq(&dev->lock);
1212: dev->state = STATE_DEV_DISABLED;
1213: spin_unlock_irq(&dev->lock);
1214:
1215: put_dev (dev);
1216: return 0;
1217: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 16/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 16663
output: 61
thoughts: 169
Thoughts: **Analyzing the File Descriptor Lifecycle**
Okay, let's break this down. My initial understanding is that `dev_release` is the function responsible for releasing the resources associated with a file descriptor. I remember that the file descriptor itself was opened using `gadget_dev_open`. The crux of the matter is that `dev_release` gets called when a file is closed, right? That's what `__fput` handles, triggering the cleanup. But hold on, `gadget_dev_open` is executed when the file is opened.
So if `dev_release` is supposed to free the `dev` structure... then how can `gadget_dev_open` possibly work with a device that has already been deallocated? This is where my confusion lies. It simply doesn't make sense. If I'm understanding this correctly, then there's a serious potential for a use-after-free vulnerability here.
Aha! The `dev` structure isn't just floating around. I seem to recall it's stored within `inode->i_private`. That's the crucial piece I was missing. Now I need to refresh my memory... When and how is `inode->i_private` actually set? That's the critical piece of this puzzle I need to find to figure out what's going on here.
|
| 17/2 |
2026/07/31 06:26 |
tool |
codesearch-find-references |
0m
Error:
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c IncludeSnippetLines:2 Name:i_private SourceTreePrefix:drivers/usb/gadget/legacy/]
Results: map[References:<nil> TruncatedOutput:false]
|
| 18/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 17199
output: 35
thoughts: 39
Thoughts: Okay, here's my take on those thoughts, framed for an expert:
**Navigating the Linux USB Gadget Codebase**
Right, so `i_private`... that's a classic `struct inode` field, isn't it? I need to figure out what's going on with it in the USB gadget subsystem. Given the context, `drivers/usb/gadget/legacy/inode.c` sounds like the most logical place to start digging. Time to see what that particular implementation is doing with `i_private`. I'll probably be looking for its usage to understand the data it's associated with within the USB gadget context, and how it is used to interact with the underlying hardware or the broader USB stack. Let's see what that file reveals.
|
| 19/2 |
2026/07/31 06:26 |
tool |
grepper |
0m
Args: map[Expression:i_private PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:drivers/usb/gadget/legacy/inode.c=818=ep_open (struct inode *inode, struct file *fd)
drivers/usb/gadget/legacy/inode.c-819-{
drivers/usb/gadget/legacy/inode.c:820: struct ep_data *data = inode->i_private;
drivers/usb/gadget/legacy/inode.c-821- int value = -EBUSY;
--
drivers/usb/gadget/legacy/inode.c=1914=gadget_dev_open (struct inode *inode, struct file *fd)
drivers/usb/gadget/legacy/inode.c-1915-{
drivers/usb/gadget/legacy/inode.c:1916: struct dev_data *dev = inode->i_private;
drivers/usb/gadget/legacy/inode.c-1917- int value = -EBUSY;
--
drivers/usb/gadget/legacy/inode.c=1965=gadgetfs_make_inode (struct super_block *sb,
--
drivers/usb/gadget/legacy/inode.c-1976- simple_inode_init_ts(inode);
drivers/usb/gadget/legacy/inode.c:1977: inode->i_private = data;
drivers/usb/gadget/legacy/inode.c-1978- inode->i_fop = fops;
]
|
| 20/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 17808
output: 43
thoughts: 13
Thoughts: Okay, let's dive into this `gadgetfs_make_inode` function. As an expert in this, I'm expecting to see the core logic for inode creation within the gadgetfs filesystem. I want to understand how it's setting up the inode structure itself, and what data it's extracting or referencing to populate those fields. Specifically, I'm looking for how it handles the inode's permissions, ownership, and size – is it defaulting to some system-wide values, or reading them from an associated data structure? I need to analyze its interaction with the underlying data store, whether it's allocating a physical block on disk or simply managing an in-memory representation. I need to note how it handles concurrency and locking to ensure data integrity during multiple operations and what are the steps taken to handle any error conditions. Furthermore, I will look to see what kind of debugging information it provides. Let's see how it handles different file types and attributes. Finally, I'm hoping to see well-commented and logically structured code, as I can quickly follow the flow.
|
| 21/2 |
2026/07/31 06:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_make_inode]
Results: map[SourceCode:1964: static struct inode *
1965: gadgetfs_make_inode (struct super_block *sb,
1966: void *data, const struct file_operations *fops,
1967: int mode)
1968: {
1969: struct inode *inode = new_inode (sb);
1970:
1971: if (inode) {
1972: inode->i_ino = get_next_ino();
1973: inode->i_mode = mode;
1974: inode->i_uid = make_kuid(&init_user_ns, default_uid);
1975: inode->i_gid = make_kgid(&init_user_ns, default_gid);
1976: simple_inode_init_ts(inode);
1977: inode->i_private = data;
1978: inode->i_fop = fops;
1979: }
1980: return inode;
1981: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 22/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 18398
output: 65
thoughts: 13
Thoughts: Okay, here's my attempt at summarizing my thought process on finding the calls to `gadgetfs_make_inode`, as if I were thinking it:
**Tracing the Inode Creation**
Alright, so I need to figure out where `gadgetfs_make_inode` gets called. This is fundamental to understanding how inodes are created within the gadgetfs filesystem. I need to trace its call stack. This should tell me where the filesystem is actually deciding it needs a new inode and which higher-level functions are responsible for the filesystem's behavior. Are we dealing with file creation, directory traversal, device handling, or something else entirely? I bet that examining the calls to `gadgetfs_make_inode` will shine light onto this. This is the starting point for exploring that module, and the call sites would be critical to understand. I'll need to go through the code, ideally use a cross-referencing tool or debugger, and track down all the instances of where this function is invoked. That will be the key to reverse-engineering how the inode structure and therefore the filesystem function, is built.
|
| 23/2 |
2026/07/31 06:26 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c IncludeSnippetLines:2 Name:gadgetfs_make_inode SourceTreePrefix:drivers/usb/gadget/legacy/]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:gadgetfs_create_file SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1992 SourceSnippet:1990: struct inode *inode;
1991:
1992: inode = gadgetfs_make_inode (sb, data, fops,
1993: S_IFREG | (default_perm & S_IRWXUGO));
1994: if (!inode)
] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:gadgetfs_fill_super SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:2042 SourceSnippet:2040:
2041: /* root inode */
2042: inode = gadgetfs_make_inode (sb,
2043: NULL, &simple_dir_operations,
2044: S_IFDIR | S_IRUGO | S_IXUGO);
]] TruncatedOutput:false]
|
| 24/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 19009
output: 43
thoughts: 13
Thoughts: Okay, let's dive into this. Here's my take on `gadgetfs_fill_super`:
**Initial Assessment: gadgetfs_fill_super**
Alright, so we're looking at `gadgetfs_fill_super`. This function's name tells me immediately that we're dealing with the core of how the `gadgetfs` filesystem gets initialized and mounted. I'm already thinking this is the bridge between the kernel's virtual filesystem (VFS) layer and the specific data structures and operations unique to `gadgetfs`. It's likely responsible for populating the superblock with all the metadata the VFS needs. My initial thoughts are around these key questions:
* **Superblock Data:** What kind of information is `gadgetfs_fill_super` populating within the superblock? Is it device-specific data, file system version information, or perhaps pointers to the root directory's inode? I'll need to look for calls that set things like `s_op`, `s_fs_info`, and potentially file system size information.
* **Inode Operations:** I'll be looking to see if `gadgetfs_fill_super` sets up any of the essential inode operations, like `inode_ops`, `file_ops`, or maybe even specific methods for creating, reading, and writing files/directories within the gadgetfs context. This is the crux of the file system's functionality.
* **Device Interaction:** Given that `gadgetfs` is often associated with USB Gadget functionality, I'm expecting some interaction with the USB subsystem. There's a high probability this function is handling any device-specific information and possibly creating a connection to the USB device. I'm going to look for references to USB device structures or any relevant driver calls.
* **Error Handling:** It's absolutely crucial for this initialization routine to handle potential errors gracefully. I'll need to understand how it addresses failure cases like memory allocation problems, device errors, or issues during the initialization of the underlying USB gadget connection. I'll search for `goto fail` or similar error-handling constructs.
* **Mount Options:** Is this function taking any mount options into account? I'd expect it to handle options like read-only mounting, or perhaps parameters to tune the filesystem's behavior. I will need to understand where these are parsed.
In essence, I'm ready to examine the function and see how it builds the necessary infrastructure to integrate `gadgetfs` into the kernel's file system landscape and make it work with the USB gadget. I'm expecting to see a structured approach, setting up data structures, assigning function pointers, and handling potential failures along the way.
|
| 25/2 |
2026/07/31 06:26 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_fill_super]
Results: map[SourceCode:2014: static int
2015: gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc)
2016: {
2017: struct inode *inode;
2018: struct dev_data *dev;
2019: int rc;
2020:
2021: mutex_lock(&sb_mutex);
2022:
2023: if (the_device) {
2024: rc = -ESRCH;
2025: goto Done;
2026: }
2027:
2028: CHIP = usb_get_gadget_udc_name();
2029: if (!CHIP) {
2030: rc = -ENODEV;
2031: goto Done;
2032: }
2033:
2034: /* superblock */
2035: sb->s_blocksize = PAGE_SIZE;
2036: sb->s_blocksize_bits = PAGE_SHIFT;
2037: sb->s_magic = GADGETFS_MAGIC;
2038: sb->s_op = &gadget_fs_operations;
2039: sb->s_time_gran = 1;
2040:
2041: /* root inode */
2042: inode = gadgetfs_make_inode (sb,
2043: NULL, &simple_dir_operations,
2044: S_IFDIR | S_IRUGO | S_IXUGO);
2045: if (!inode)
2046: goto Enomem;
2047: inode->i_op = &simple_dir_inode_operations;
2048: if (!(sb->s_root = d_make_root (inode)))
2049: goto Enomem;
2050:
2051: /* the ep0 file is named after the controller we expect;
2052: * user mode code can use it for sanity checks, like we do.
2053: */
2054: dev = dev_new ();
2055: if (!dev)
2056: goto Enomem;
2057:
2058: dev->sb = sb;
2059: rc = gadgetfs_create_file(sb, CHIP, dev, &ep0_operations);
2060: if (rc) {
2061: put_dev(dev);
2062: goto Enomem;
2063: }
2064:
2065: /* other endpoint files are available after hardware setup,
2066: * from binding to a controller.
2067: */
2068: the_device = dev;
2069: rc = 0;
2070: goto Done;
2071:
2072: Enomem:
2073: kfree(CHIP);
2074: CHIP = NULL;
2075: rc = -ENOMEM;
2076:
2077: Done:
2078: mutex_unlock(&sb_mutex);
2079: return rc;
2080: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 26/2 |
2026/07/31 06:26 |
llm |
debugger |
0m
Model:
Tokens:
input: 20554
output: 43
thoughts: 77
Thoughts: Okay, here's my take on those thoughts, framed as my own mental processing, as a fellow expert:
**Understanding the `gadgetfs` Filesystem Initialization**
Alright, let's break this down from a filesystem perspective. So, the `gadgetfs_fill_super` function – that's the core of our superblock filling process, and it's starting with the creation of the foundational root inode. Standard stuff. Then it's immediately following that up by creating this `CHIP` file, and that `CHIP` file is basically the same thing as the UDC name for this particular gadget. Nice and clean. The architecture is following convention.
Now, here's where it gets interesting, with the `dev` allocation using `dev_new()`, which is then passed to `gadgetfs_create_file`. This is how we're tying the device object to the filesystem object. Wait a second, `gadgetfs_create_file` actually handles the critical task of creating both the dentry and the inode for this new file. That's a good separation of concerns, `dev` is a pointer to the generic data, the filesystem is the filesystem. Got it. This makes the initialization process seem simple, organized, and straightforward. It's a sensible approach to building a virtual filesystem, I can see what is happening, and where.
|
| 27/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_create_file]
Results: map[SourceCode:1983: /* creates in fs root directory, so non-renamable and non-linkable.
1984: * so inode and dentry are paired, until device reconfig.
1985: */
1986: static int gadgetfs_create_file (struct super_block *sb, char const *name,
1987: void *data, const struct file_operations *fops)
1988: {
1989: struct dentry *dentry;
1990: struct inode *inode;
1991:
1992: inode = gadgetfs_make_inode (sb, data, fops,
1993: S_IFREG | (default_perm & S_IRWXUGO));
1994: if (!inode)
1995: return -ENOMEM;
1996:
1997: dentry = simple_start_creating(sb->s_root, name);
1998: if (IS_ERR(dentry)) {
1999: iput(inode);
2000: return PTR_ERR(dentry);
2001: }
2002:
2003: d_make_persistent(dentry, inode);
2004:
2005: simple_done_creating(dentry);
2006: return 0;
2007: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 28/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 21367
output: 40
thoughts: 113
Thoughts: **My Understanding of the GadgetFS File Creation and Lifecycle**
Okay, so let's break this down. `gadgetfs_create_file`, right, that's the starting point. It's the function that's responsible for creating the inode. And crucially, it sets `i_private` on that inode to `data`, which I recognize is effectively the `dev` pointer we're dealing with. Then, naturally, it creates the corresponding dentry, linking the file in the filesystem.
Now, the interesting part is the file lifecycle. When a user actually *opens* this gadgetfs file, `gadget_dev_open` gets invoked. That's where we retrieve the real device context, this `dev` pointer, by grabbing it from `inode->i_private`. Makes perfect sense; the inode holds the handle to what we're ultimately interacting with.
The final piece: when the file is closed, `dev_release` gets called. Ah, and that's the *release* function of the `ep0_operations` structure. The purpose of `dev_release` is to call `put_dev(dev)`. So, that's where the device gets released.
|
| 29/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:ep0_operations]
Results: map[SourceCode:1931: static const struct file_operations ep0_operations = {
1932:
1933: .open = gadget_dev_open,
1934: .read = ep0_read,
1935: .write = dev_config,
1936: .fasync = ep0_fasync,
1937: .poll = ep0_poll,
1938: .unlocked_ioctl = gadget_dev_ioctl,
1939: .release = dev_release,
1940: };
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 30/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 21965
output: 43
thoughts: 426
Thoughts: **Analyzing the Device Reference Counting in the Gadget Driver**
Okay, let's break down this gadget driver's device management. My initial thought is about how `gadget_dev_open` and `dev_release` interact, particularly concerning multiple opens. I see `gadget_dev_open` calls `get_dev(dev)` and `dev_release` calls `put_dev(dev)`. That's standard refcounting, but the devil's in the details.
Looking at `gadget_dev_open`, I see a spinlock protecting a state check. If the device is disabled, it transitions to `STATE_DEV_OPENED`, sets up the `private_data`, and importantly, calls `get_dev(dev)`. If it *is* already open, it returns `-EBUSY`. So far, so good – preventing double opens on the same file descriptor, I'd say.
But then, consider `dev_release`. It also uses a spinlock. It sets the state to `STATE_DEV_DISABLED` and immediately calls `put_dev(dev)`. This is where it starts to get interesting. If it's opened, closed, and re-opened, `dev_release` effectively disables the device *and* decrements the reference count.
Aha! This refcounting has to be handled correctly. `dev_new` initializes the device refcount using `refcount_set(&dev->count, 1)`. Then, inside `gadget_dev_open`, `get_dev(dev)` increments it, so the count is 2. The critical question here is, who's holding the initial reference? I'm missing something here. In `dev_release` the count would go to 1, as that is the last ref.
Alright, the initial reference is likely set from `gadgetfs_fill_super`. This is where `dev_new()` gets called and the ref count is set to 1. Then the global `the_device = dev` is set. When is *that* initial reference dropped? This is important. Let's look at `gadgetfs_kill_sb` to find out. I'll bet it's there.
|
| 31/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_kill_sb]
Results: map[SourceCode:2098: static void
2099: gadgetfs_kill_sb (struct super_block *sb)
2100: {
2101: mutex_lock(&sb_mutex);
2102: kill_anon_super (sb);
2103: if (the_device) {
2104: put_dev (the_device);
2105: the_device = NULL;
2106: }
2107: kfree(CHIP);
2108: CHIP = NULL;
2109: mutex_unlock(&sb_mutex);
2110: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 32/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 23114
output: 39
thoughts: 253
Thoughts: **My Line of Reasoning Regarding the GadgetFS Driver**
Okay, so `gadgetfs_kill_sb` ultimately calls `put_dev(the_device)`. Seems straightforward, right? But hold on a second. What happens if `gadgetfs_fill_super` hits an error? Let's trace it back. I see the allocation: `dev = dev_new()`. That's fine. But then there's this `gadgetfs_create_file` call.
If that fails, it correctly calls `put_dev(dev)` before bailing out with `Enomem`, which is what you'd expect. However, if `gadgetfs_create_file` succeeds, we get to this critical bit: `the_device = dev; rc = 0;`. This means the `dev` is assigned to `the_device`, and the function proceeds, as planned.
But, and this is where it gets interesting... what if `gadgetfs_fill_super` does *succeed*? It successfully sets up `the_device`! And then, later, `dev_config` is called? According to the reproducer, `dev_config` is triggered via a `write` call. I need to refresh my memory on the interactions of those functions, as this seems like where the potential issue might lie. Let's dig into that `dev_config` function now... I need to understand the state it's working with to see if there's a race, or a use-after-free, or something similar lurking in there.
|
| 33/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:dev_config]
Results: map[SourceCode:1800: static ssize_t
1801: dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1802: {
1803: struct dev_data *dev = fd->private_data;
1804: ssize_t value, length = len;
1805: unsigned total;
1806: u32 tag;
1807: char *kbuf;
1808:
1809: spin_lock_irq(&dev->lock);
1810: if (dev->state > STATE_DEV_OPENED) {
1811: value = ep0_write(fd, buf, len, ptr);
1812: spin_unlock_irq(&dev->lock);
1813: return value;
1814: }
1815: spin_unlock_irq(&dev->lock);
1816:
1817: if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||
1818: (len > PAGE_SIZE * 4))
1819: return -EINVAL;
1820:
1821: /* we might need to change message format someday */
1822: if (copy_from_user (&tag, buf, 4))
1823: return -EFAULT;
1824: if (tag != 0)
1825: return -EINVAL;
1826: buf += 4;
1827: length -= 4;
1828:
1829: kbuf = memdup_user(buf, length);
1830: if (IS_ERR(kbuf))
1831: return PTR_ERR(kbuf);
1832:
1833: spin_lock_irq (&dev->lock);
1834: value = -EINVAL;
1835: if (dev->buf) {
1836: spin_unlock_irq(&dev->lock);
1837: kfree(kbuf);
1838: return value;
1839: }
1840: dev->buf = kbuf;
1841:
1842: /* full or low speed config */
1843: dev->config = (void *) kbuf;
1844: total = le16_to_cpu(dev->config->wTotalLength);
1845: if (!is_valid_config(dev->config, total) ||
1846: total > length - USB_DT_DEVICE_SIZE)
1847: goto fail;
1848: kbuf += total;
1849: length -= total;
1850:
1851: /* optional high speed config */
1852: if (kbuf [1] == USB_DT_CONFIG) {
1853: dev->hs_config = (void *) kbuf;
1854: total = le16_to_cpu(dev->hs_config->wTotalLength);
1855: if (!is_valid_config(dev->hs_config, total) ||
1856: total > length - USB_DT_DEVICE_SIZE)
1857: goto fail;
1858: kbuf += total;
1859: length -= total;
1860: } else {
1861: dev->hs_config = NULL;
1862: }
1863:
1864: /* could support multiple configs, using another encoding! */
1865:
1866: /* device descriptor (tweaked for paranoia) */
1867: if (length != USB_DT_DEVICE_SIZE)
1868: goto fail;
1869: dev->dev = (void *)kbuf;
1870: if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1871: || dev->dev->bDescriptorType != USB_DT_DEVICE
1872: || dev->dev->bNumConfigurations != 1)
1873: goto fail;
1874: dev->dev->bcdUSB = cpu_to_le16 (0x0200);
1875:
1876: /* triggers gadgetfs_bind(); then we can enumerate. */
1877: spin_unlock_irq (&dev->lock);
1878: if (dev->hs_config)
1879: gadgetfs_driver.max_speed = USB_SPEED_HIGH;
1880: else
1881: gadgetfs_driver.max_speed = USB_SPEED_FULL;
1882:
1883: value = usb_gadget_register_driver(&gadgetfs_driver);
1884: if (value != 0) {
1885: spin_lock_irq(&dev->lock);
1886: goto fail;
1887: } else {
1888: /* at this point "good" hardware has for the first time
1889: * let the USB the host see us. alternatively, if users
1890: * unplug/replug that will clear all the error state.
1891: *
1892: * note: everything running before here was guaranteed
1893: * to choke driver model style diagnostics. from here
1894: * on, they can work ... except in cleanup paths that
1895: * kick in after the ep0 descriptor is closed.
1896: */
1897: value = len;
1898: dev->gadget_registered = true;
1899: }
1900: return value;
1901:
1902: fail:
1903: dev->config = NULL;
1904: dev->hs_config = NULL;
1905: dev->dev = NULL;
1906: spin_unlock_irq (&dev->lock);
1907: pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev);
1908: kfree (dev->buf);
1909: dev->buf = NULL;
1910: return value;
1911: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 34/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 25462
output: 41
thoughts: 651
Thoughts: **Analyzing the `usb_gadget_register_driver` Failure**
Okay, so I'm looking at this trace, and it's pretty clear where the problem lies. The `dev_config` function in `dev_config` calls `usb_gadget_register_driver(&gadgetfs_driver)`. The trace shows it failing and going to `fail`, which frees `dev->buf` and returns `value`. That's standard error handling. But the stack trace is the key. The fault injection trace shows the failure happens within the bowels of the memory allocation system, specifically at `should_failslab` through `__kmalloc_cache_noprof` ultimately within `gadgetfs_bind`.
So, it's not a direct `usb_gadget_register_driver` issue, but a failure *during* its execution, originating in `gadgetfs_bind`. This points directly to the `gadgetfs_bind` function as the root cause of the memory allocation failure. I need to understand what's happening within `gadgetfs_bind` to cause `__kmalloc_cache_noprof` to fail. I'll need to dig into its code to determine what resources it's trying to allocate.
|
| 35/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_bind]
Results: map[SourceCode:1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 36/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 27008
output: 41
thoughts: 52
Thoughts: Here's my analysis of what's happening:
**Dissecting a Potential Memory Allocation Failure in `activate_ep_files`**
Okay, so if `activate_ep_files` throws a wrench into the works and fails, my immediate concern is how the system handles the fallout. It looks like the error handling is pretty straightforward, thankfully. It jumps directly to the `enomem` label. Now, *that* tells me the failure is likely related to memory – hence the "ENOMEM" error code that's ultimately returned.
The interesting part, and what I need to fully understand, is the role of `gadgetfs_unbind(gadget)`. Before returning the dreaded -ENOMEM, the system attempts to unbind the gadget. This suggests a potential cleanup or rollback operation related to gadgetfs. It's almost a guarantee that if activation fails, any previously bound resources should be safely unbound prior to the return, but I need to understand the function call better to be sure. I will begin by examining the workings of `gadgetfs_unbind`.
|
| 37/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_unbind]
Results: map[SourceCode:1639: static void
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
1643:
1644: DBG (dev, "%s\n", __func__);
1645:
1646: spin_lock_irq (&dev->lock);
1647: dev->state = STATE_DEV_UNBOUND;
1648: while (dev->udc_usage > 0) {
1649: spin_unlock_irq(&dev->lock);
1650: usleep_range(1000, 2000);
1651: spin_lock_irq(&dev->lock);
1652: }
1653: spin_unlock_irq (&dev->lock);
1654:
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 38/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 27770
output: 43
thoughts: 640
Thoughts: **Analyzing a Potential Reference Count Leak in `gadgetfs` Driver Binding/Unbinding**
Okay, so I'm digging into this `gadgetfs` code and something feels off. I'm seeing that `gadgetfs_unbind` calls `put_dev(dev)`. That's normal, part of the cleanup process. The thing that's making me pause is how `gadgetfs_bind` interacts with this. I'm seeing that `get_dev(dev)` is *only* called within `gadgetfs_bind` if `activate_ep_files` succeeds.
The sequence looks like this: `gadgetfs_bind` -> `activate_ep_files` -> *IF SUCCESS* `get_dev(dev)` and then it's all good. However, *if `activate_ep_files` fails*, it jumps to `enomem`, and *then* calls `gadgetfs_unbind`. The crucial point is that in this failure path, `get_dev(dev)` *isn't* called *before* `activate_ep_files`, but `put_dev(dev)` is called during `gadgetfs_unbind`
This immediately raises a red flag. I need to know if `get_dev` is called anywhere before `gadgetfs_bind` is invoked! Looking at `dev_config`, I see that `usb_gadget_register_driver` calls `gadgetfs_bind`. If `gadgetfs_bind` fails, then `gadgetfs_unbind` is called. Critically, `dev_config` does *not* call `get_dev(dev)` before calling `usb_gadget_register_driver`. This means `gadgetfs_unbind` could be dropping a reference that was never acquired in the first place, leading to a possible memory leak/double free.
Now, let's step back and consider *when* `gadgetfs_unbind` is called. I need to make sure I am not missing anything else. Aha! When `usb_gadget_unregister_driver` is called, it triggers `gadgetfs_unbind` as well. This actually makes sense in the *success* scenario. If `gadgetfs_bind` succeeds, `get_dev(dev)` is called. Then, when the driver is unregistered, `gadgetfs_unbind` is called, which calls `put_dev(dev)`. This balances the `get_dev(dev)` in the success case.
But, back to the failure case. If `gadgetfs_bind` *fails*, then it calls `gadgetfs_unbind` directly, *without* a corresponding `get_dev(dev)` call. This is the potential problem. So, I need to know if the UDC core has any interaction with this. I must look at `gadget_bind_driver` in `drivers/usb/gadget/udc/core.c`.
|
| 39/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/udc/core.c Name:gadget_bind_driver]
Results: map[SourceCode:1641: static int gadget_bind_driver(struct device *dev)
1642: {
1643: struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1644: struct usb_udc *udc = gadget->udc;
1645: struct usb_gadget_driver *driver = container_of(dev->driver,
1646: struct usb_gadget_driver, driver);
1647: int ret = 0;
1648:
1649: mutex_lock(&udc_lock);
1650: if (driver->is_bound) {
1651: mutex_unlock(&udc_lock);
1652: return -ENXIO; /* Driver binds to only one gadget */
1653: }
1654: driver->is_bound = true;
1655: udc->driver = driver;
1656: mutex_unlock(&udc_lock);
1657:
1658: dev_dbg(&udc->dev, "binding gadget driver [%s]\n", driver->function);
1659:
1660: usb_gadget_udc_set_speed(udc, driver->max_speed);
1661:
1662: ret = driver->bind(udc->gadget, driver);
1663: if (ret)
1664: goto err_bind;
1665:
1666: mutex_lock(&udc->connect_lock);
1667: ret = usb_gadget_udc_start_locked(udc);
1668: if (ret) {
1669: mutex_unlock(&udc->connect_lock);
1670: goto err_start;
1671: }
1672: usb_gadget_enable_async_callbacks(udc);
1673: udc->allow_connect = true;
1674: ret = usb_udc_connect_control_locked(udc);
1675: if (ret)
1676: goto err_connect_control;
1677:
1678: mutex_unlock(&udc->connect_lock);
1679:
1680: kobject_uevent(&udc->dev.kobj, KOBJ_CHANGE);
1681: return 0;
1682:
1683: err_connect_control:
1684: udc->allow_connect = false;
1685: usb_gadget_disable_async_callbacks(udc);
1686: if (gadget->irq)
1687: synchronize_irq(gadget->irq);
1688: usb_gadget_udc_stop_locked(udc);
1689: mutex_unlock(&udc->connect_lock);
1690:
1691: err_start:
1692: driver->unbind(udc->gadget);
1693:
1694: err_bind:
1695: if (ret != -EISNAM)
1696: dev_err(&udc->dev, "failed to start %s: %d\n",
1697: driver->function, ret);
1698:
1699: mutex_lock(&udc_lock);
1700: udc->driver = NULL;
1701: driver->is_bound = false;
1702: mutex_unlock(&udc_lock);
1703:
1704: return ret;
1705: }
SourceFile:drivers/usb/gadget/udc/core.c]
|
| 40/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 30093
output: 41
thoughts: 161
Thoughts: **Analyzing the Gadget Driver Binding Process**
Okay, here's what I'm thinking. In the `gadget_bind_driver` function, the critical line is `driver->bind(udc->gadget, driver)`. If that `bind` call returns an error, the code jumps to `err_bind`. And here's the kicker: it *doesn't* automatically call `driver->unbind(udc->gadget)`! That's important. It means the UDC core itself isn't going to clean up after a failed `bind`.
So, in the context of `gadgetfs_bind` calling `gadgetfs_unbind` on failure, that's actually *correct* from the UDC core's point of view; the UDC core won't expect an unbind if the bind itself fails. But now I have a question about reference counting. `gadgetfs_unbind` *does* call `put_dev(dev)`. That's where I need to be careful; is `gadgetfs_bind` taking a reference to the `dev` before it calls `gadgetfs_unbind` if things go wrong? I'm going to have to dig back into `gadgetfs_bind` to see how it handles references.
|
| 41/2 |
2026/07/31 06:27 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_bind]
Results: map[SourceCode:1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 42/2 |
2026/07/31 06:27 |
llm |
debugger |
0m
Model:
Tokens:
input: 31158
output: 42
thoughts: 1428
Thoughts: **Analysis of a USB Gadget Driver Unbind/Freeing Bug**
Okay, so here's what I've got. I'm looking at a potential use-after-free vulnerability in the `gadgetfs` driver. It seems like `gadgetfs_bind` has a subtle flaw. It doesn't call `get_dev(dev)` before potentially bailing out to `enomem`. If `usb_ep_alloc_request` or `activate_ep_files` fails, we hit the `enomem` label. This then calls `gadgetfs_unbind(gadget)`, which, importantly, *does* call `put_dev(dev)`. This is where the problem lies.
Let's trace this step by step. `gadgetfs_fill_super` calls `dev_new()`, initializing the refcount to 1. Then, `the_device = dev`. Later, a `write` call to ep0 triggers `dev_config`, which in turn calls `usb_gadget_register_driver(&gadgetfs_driver)`. This leads to `gadget_bind_driver` calling `gadgetfs_bind`. Inside `gadgetfs_bind`, we get `dev = the_device`. But, and this is key, there's no corresponding `get_dev(dev)`.
Now, if `activate_ep_files` fails (and we know it can due to injected faults), we jump to `enomem`. `gadgetfs_unbind` is then called and it calls `put_dev(dev)`. Since the refcount started at 1 and there was no corresponding `get_dev`, the refcount drops to 0, and *poof*, `dev` is freed! The subsequent `gadgetfs_bind` returns `-ENOMEM`, which cascades up through `gadget_bind_driver` and `usb_gadget_register_driver`.
Within `dev_config` at the `fail` label, the code clears the `dev`'s configuration, nulls several pointers, and then calls `kfree(dev->buf)`. My initial thought was that there was a race with `dev_config`'s lock. However, `dev_config` *acquires* the spinlock *after* `usb_gadget_register_driver` returns. So, the potential use-after-free isn't there.
So, where's the crash? The crash report points to `gadget_dev_open`, not `dev_config`. This is strange. Why would it be `gadget_dev_open`, and not within the `fail` block? The use-after-free might not immediately crash if the memory isn't reallocated, or maybe some compiler optimization avoids the crash inside `dev_config`.
The KASAN report then shows a "slab-use-after-free" error in `__raw_spin_lock_irq`. The backtrace points to `gadget_dev_open` which is called by `do_dentry_open`.
The reproducer calls `mount`, opens a device (likely `dummy_udc` which represents ep0), injects a fault, and then calls `write`. It seems the opening of `dummy_udc` triggers a call to `gadget_dev_open`. Wait, `gadget_dev_open` is called when `dummy_udc` is opened, but it's already been opened before, right? Let's check this again: `gadgetfs_fill_super` creates `dummy_udc` in the first place, and then `openat` opens it which leads to the call of `gadget_dev_open`. `openat` returns a file descriptor, and a `write` is called using this file descriptor, which triggers `dev_config`. `dev_config` calls `usb_gadget_register_driver`. This fails, so `gadgetfs_unbind` calls `put_dev(dev)`. If `openat` has already opened the device, then `gadget_dev_open` has already been called! Aha, here it is: the call to `spin_lock_irq(&dev->lock)` inside `gadget_dev_open` is being performed on the freed `dev` when ep0 is being opened.
The bug is in `gadgetfs_unbind` not calling `get_dev`, combined with a failure during the driver registration process leading to a `put_dev`, and then further access on the released object in the open path. I need to look at `gadget_dev_open` now to verify what's happening.
|
| 43/2 |
2026/07/31 06:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadget_dev_open]
Results: map[SourceCode:1913: static int
1914: gadget_dev_open (struct inode *inode, struct file *fd)
1915: {
1916: struct dev_data *dev = inode->i_private;
1917: int value = -EBUSY;
1918:
1919: spin_lock_irq(&dev->lock);
1920: if (dev->state == STATE_DEV_DISABLED) {
1921: dev->ev_next = 0;
1922: dev->state = STATE_DEV_OPENED;
1923: fd->private_data = dev;
1924: get_dev (dev);
1925: value = 0;
1926: }
1927: spin_unlock_irq(&dev->lock);
1928: return value;
1929: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 44/2 |
2026/07/31 06:28 |
llm |
debugger |
0m
Model:
Tokens:
input: 33915
output: 41
thoughts: 1008
Thoughts: **Analyzing a Use-After-Free in the USB Gadget Driver**
Okay, so I'm diving into this KASAN report and I think I've got a handle on the use-after-free issue. It looks like the core problem revolves around reference counting of a device structure, let's call it `dev`, within the USB gadget driver's legacy code.
First, `gadget_dev_open` uses `get_dev(dev)` and the refcount becomes 2. Then a `write` operation gets called, which in turn calls `dev_config`, which then calls `usb_gadget_register_driver`. This, however, fails and calls `gadgetfs_unbind`, which then calls `put_dev(dev)`. Refcount is now back to 1. The `write` function then returns an error, and the process eventually exits or closes the file descriptor. The file descriptor is closed and `dev_release` gets called. `dev_release` calls `put_dev(dev)` again. At this point, the refcount drops to 0, and `dev` is freed!
So far, so good – seemingly proper resource management. But then, the KASAN report reveals the crash, specifically a use-after-free in `__raw_spin_lock_irq`, originating from a subsequent call to `gadget_dev_open`. This means `gadget_dev_open` is trying to access `dev` *after* it has been freed. This seems problematic, how can `gadget_dev_open` be called again?
A closer look at the KASAN report confirms `dev` is freed in `dev_release`. It's freed by `put_dev(dev)`. The critical thing is the inode still exists, and its `i_private` points to this now-freed `dev`! This is how the call to `gadget_dev_open` accesses the freed memory. The filesystem is still mounted, so the inodes are still available.
Okay, so why is `dev` freed prematurely? Tracing the refcount is key here. It starts at 1, increased to 2 on open, then reduced to 1 due to `gadgetfs_unbind` during the failed configuration, and then to 0 during the `close` sequence, which calls `dev_release`. The bug then is exposed when calling `gadget_dev_open` when `dev` is freed!
The root cause then seems to be that `gadgetfs_unbind` calls `put_dev(dev)` without a corresponding `get_dev(dev)` in `gadgetfs_bind`, in the case where the driver registration fails! That's the vulnerability right there. It's a classic imbalance in the reference count.
|
| 45/2 |
2026/07/31 06:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_bind]
Results: map[SourceCode:1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 46/2 |
2026/07/31 06:28 |
llm |
debugger |
0m
Model:
Tokens:
input: 36150
output: 47
thoughts: 119
Thoughts: **Analyzing Potential USB Gadget Driver Resource Leaks**
Okay, so I'm looking closely at this `gadgetfs` driver code, and I think I've spotted a potential resource leak. My train of thought is this: if `usb_ep_alloc_request` fails, or if `activate_ep_files` fails, we hit `enomem`. That's important because it leads to `gadgetfs_unbind(gadget)`. And `gadgetfs_unbind` calls `put_dev(dev)`. This seems correct, in that if allocation fails, it cleans up resources.
But here’s where my concern lies: `get_dev(dev)` is only called on *success*! That suggests a pattern: on success, the device is acquired, and on failure, the device is released.
The crux of the issue is: I'm not seeing anywhere else that a `get_dev(dev)` would be called *before* the `gadgetfs_bind` function is called. If that's the case, then in a failure scenario, the device count could remain unbalanced.
Alright, before I dive deeper, let's step back and be thorough. Let me quickly check the call flow for `usb_gadget_register_driver` to make absolutely certain that there isn't some implicit `get_dev` happening there beforehand. Gotta cover all the bases!
|
| 47/2 |
2026/07/31 06:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/udc/core.c Name:usb_gadget_register_driver_owner]
Results: map[SourceCode:1740: int usb_gadget_register_driver_owner(struct usb_gadget_driver *driver,
1741: struct module *owner, const char *mod_name)
1742: {
1743: int ret;
1744:
1745: if (!driver || !driver->bind || !driver->setup)
1746: return -EINVAL;
1747:
1748: driver->driver.bus = &gadget_bus_type;
1749: driver->driver.owner = owner;
1750: driver->driver.mod_name = mod_name;
1751: driver->driver.probe_type = PROBE_FORCE_SYNCHRONOUS;
1752: ret = driver_register(&driver->driver);
1753: if (ret) {
1754: pr_warn("%s: driver registration failed: %d\n",
1755: driver->function, ret);
1756: return ret;
1757: }
1758:
1759: mutex_lock(&udc_lock);
1760: if (!driver->is_bound) {
1761: if (driver->match_existing_only) {
1762: pr_warn("%s: couldn't find an available UDC or it's busy\n",
1763: driver->function);
1764: ret = -EBUSY;
1765: } else {
1766: pr_info("%s: couldn't find an available UDC\n",
1767: driver->function);
1768: ret = 0;
1769: }
1770: }
1771: mutex_unlock(&udc_lock);
1772:
1773: if (ret)
1774: driver_unregister(&driver->driver);
1775: return ret;
1776: }
SourceFile:drivers/usb/gadget/udc/core.c]
|
| 48/2 |
2026/07/31 06:28 |
llm |
debugger |
0m
Model:
Tokens:
input: 37180
output: 41
thoughts: 134
Thoughts: **Analyzing the USB Gadget Driver Registration Process**
Okay, so let me break this down in my head. `usb_gadget_register_driver_owner` - that's just the registration part, right? It's not where the core magic happens. The driver core kicks things off, calling `gadget_bind_driver` through the `probe` function. Now, `gadget_bind_driver` is where it gets interesting, because that's what calls the `driver->bind` function, and in this specific case, that's `gadgetfs_bind`. Aha! So `gadgetfs_bind` is the first function that actually *knows* about the `dev` structure within the gadget context.
Right, so what I'm thinking is, if `gadgetfs_bind` fails, then `gadgetfs_unbind` shouldn't be called if `gadgetfs_unbind` is going to drop a reference it never took. I want to make sure the code doesn't try to free something it never allocated in the first place. That seems like it could create some really hard-to-debug memory errors.
Okay, let's step back a moment and just double-check that this is accurate, and then let me also think through, what exactly does `gadgetfs_unbind` *do*? I should refresh my memory on the whole unbind process, to make sure I am accounting for everything.
|
| 49/2 |
2026/07/31 06:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_unbind]
Results: map[SourceCode:1639: static void
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
1643:
1644: DBG (dev, "%s\n", __func__);
1645:
1646: spin_lock_irq (&dev->lock);
1647: dev->state = STATE_DEV_UNBOUND;
1648: while (dev->udc_usage > 0) {
1649: spin_unlock_irq(&dev->lock);
1650: usleep_range(1000, 2000);
1651: spin_lock_irq(&dev->lock);
1652: }
1653: spin_unlock_irq (&dev->lock);
1654:
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 50/2 |
2026/07/31 06:28 |
llm |
debugger |
0m
Model:
Tokens:
input: 38106
output: 40
thoughts: 1619
Thoughts: **Analyzing the GadgetFS Unbind/Bind Sequence**
Okay, so I'm looking at the `gadgetfs_unbind` function, and my initial thought is that it does a pretty standard cleanup: it sets the device state to `STATE_DEV_UNBOUND`, waits for usage to drop to zero, calls `destroy_ep_files`, clears gadget data and the driver data, frees the request, and then calls `put_dev(dev)`. That makes sense.
However, I need to understand the failure cases, specifically what happens when `gadgetfs_bind` fails. I need to make sure that the system correctly undoes everything it started to do. What does `gadgetfs_bind` set up before it calls `goto enomem`? It sets up `gadget_data`, assigns the gadget, allocates the USB request, and activates the endpoint files. I see that if either `usb_ep_alloc_request` or `activate_ep_files` fails, `gadgetfs_unbind` *will* be called, and it cleans up the allocated request, clears the gadget data, and calls `destroy_ep_files`. This seems correct, but...
Why is `put_dev(dev)` being called in `gadgetfs_unbind`? It's called when the driver is normally unbound, such as on module unload. In that situation, `gadgetfs_bind` would have succeeded, and called `get_dev(dev)`. So, the `gadgetfs_unbind` drops the reference taken by a successful bind. But, if `gadgetfs_bind` fails, it calls `gadgetfs_unbind` directly, and it drops a reference that was *never* taken! This is where the bug potentially resides.
I'm thinking, could I fix this by having `gadgetfs_bind` call `get_dev(dev)` at the very beginning of the function? Then, regardless of whether it succeeds or fails, `gadgetfs_unbind` will properly drop the reference in the failure case.
Let's see: I'll add the `get_dev(dev)` call, and proceed with the remaining setup. If it fails and goes to `enomem`, it should be okay. Oh, wait. What if it fails right at the beginning? I need to account for the preliminary checks: does the device exist, and is it the correct gadget? Those checks *return* if there's a problem. So, if the initial checks fail, there's no reference to drop. That's good!
Alright, so I'll add `get_dev(dev)` right *after* those initial checks. Then, in the `enomem` path, `gadgetfs_unbind` will drop the reference. Is this correct?
I need to make sure this doesn't break anything. I'm going to check if `gadgetfs_unbind` assumes any specific state for the device. `gadgetfs_unbind` *does* set `dev->state = STATE_DEV_UNBOUND`. Wait... if `gadgetfs_bind` fails, the `dev->state` is `STATE_DEV_OPENED`!
If `gadgetfs_unbind` sets the state to `STATE_DEV_UNBOUND`, is that correct? What happens if the file is still open and the user tries to write again? The `dev_config` function will be called from the `write` function on the open file, and checks the device state. If `dev->state` is greater than `STATE_DEV_OPENED`, it will call `ep0_write` instead of `dev_config`.
Okay, so I check the enum to be sure... `STATE_DEV_UNBOUND` is actually 5. If `gadgetfs_unbind` sets `dev->state = STATE_DEV_UNBOUND`, then `dev->state > STATE_DEV_OPENED` *will* be true, which means, the next write call will result in `ep0_write` getting called, even though the device is NOT bound! This would be disastrous. I need to examine `ep0_write` now.
|
| 51/2 |
2026/07/31 06:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:ep0_write]
Results: map[SourceCode:1124: static ssize_t
1125: ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1126: {
1127: struct dev_data *dev = fd->private_data;
1128: ssize_t retval = -ESRCH;
1129:
1130: /* report fd mode change before acting on it */
1131: if (dev->setup_abort) {
1132: dev->setup_abort = 0;
1133: retval = -EIDRM;
1134:
1135: /* data and/or status stage for control request */
1136: } else if (dev->state == STATE_DEV_SETUP) {
1137:
1138: len = min_t(size_t, len, dev->setup_wLength);
1139: if (dev->setup_in) {
1140: retval = setup_req (dev->gadget->ep0, dev->req, len);
1141: if (retval == 0) {
1142: dev->state = STATE_DEV_CONNECTED;
1143: ++dev->udc_usage;
1144: spin_unlock_irq (&dev->lock);
1145: if (copy_from_user (dev->req->buf, buf, len))
1146: retval = -EFAULT;
1147: else {
1148: if (len < dev->setup_wLength)
1149: dev->req->zero = 1;
1150: retval = usb_ep_queue (
1151: dev->gadget->ep0, dev->req,
1152: GFP_KERNEL);
1153: }
1154: spin_lock_irq(&dev->lock);
1155: --dev->udc_usage;
1156: if (retval < 0) {
1157: clean_req (dev->gadget->ep0, dev->req);
1158: } else
1159: retval = len;
1160:
1161: return retval;
1162: }
1163:
1164: /* can stall some OUT transfers */
1165: } else if (dev->setup_can_stall) {
1166: VDEBUG(dev, "ep0out stall\n");
1167: (void) usb_ep_set_halt (dev->gadget->ep0);
1168: retval = -EL2HLT;
1169: dev->state = STATE_DEV_CONNECTED;
1170: } else {
1171: DBG(dev, "bogus ep0out stall!\n");
1172: }
1173: } else
1174: DBG (dev, "fail %s, state %d\n", __func__, dev->state);
1175:
1176: return retval;
1177: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 52/2 |
2026/07/31 06:29 |
llm |
debugger |
0m
Model:
Tokens:
input: 41523
output: 41
thoughts: 774
Thoughts: **Analyzing the USB Gadget State Transitions**
Okay, let's break this down. My initial thought was that if `dev->state` is `STATE_DEV_UNBOUND`, then a call to `ep0_write` will just return `-ESRCH`, which is safe enough. But hold on, the real question is about the state transitions, particularly around `gadgetfs_bind` and `gadgetfs_unbind`.
If `gadgetfs_bind` fails, should the state really move to `STATE_DEV_UNBOUND`? Logically, no. If the bind *failed*, then the device was never actually bound. The state should have stayed at `STATE_DEV_OPENED`. If it goes to `STATE_DEV_UNBOUND`, then the user can't retry `dev_config`! This is because `dev_config` checks if `dev->state` is greater than `STATE_DEV_OPENED` before calling `ep0_write`. So, if `dev_config` fails, the device is effectively stuck until it's closed and reopened. Is that intentional? This seems like a bug.
Let's consider another scenario: what if `usb_gadget_register_driver` fails, perhaps because no UDC is available? If it fails *before* calling `gadgetfs_bind` (e.g., `driver_register` fails, or no UDC is found), then `gadgetfs_bind` is *never* called! In this case, `dev->state` remains at `STATE_DEV_OPENED`. And importantly, `dev_config` goes to a `fail` label that releases the `dev` struct members, `dev->config`, `dev->hs_config`, `dev->dev`, `dev->buf`, unlocks the spinlock, and frees `dev->buf`. This is good! The user *can* retry `dev_config` in this situation.
But, if `gadgetfs_bind` *is* called and fails, `gadgetfs_unbind` *is* called, which sets `dev->state = STATE_DEV_UNBOUND`. Now, the user *can't* retry `dev_config`. This is the problem. This looks like a bug. It seems that `gadgetfs_bind` shouldn't call `gadgetfs_unbind` if it fails. Let's see what `gadgetfs_bind` actually does when it fails.
Okay, let's step through `gadgetfs_bind` failure:
1. `set_gadget_data(gadget, dev);`
2. `dev->gadget = gadget;`
3. `gadget->ep0->driver_data = dev;`
4. `dev->req = usb_ep_alloc_request(...)`
5. `activate_ep_files(dev)`
If it fails, it needs to undo those steps. What does that cleanup look like? If `activate_ep_files` fails, should it call `destroy_ep_files(dev)`? Let's check `activate_ep_files` to verify it cleans up after itself if it fails...
...*pauses to review `activate_ep_files` code*...
Okay, yes, looks like if `activate_ep_files` fails, it does clean up.
So, in summary: if the gadget's *setup* fails, but before anything has been bound, the state remains `OPENED` and the user can retry. However, if the bind *process* itself starts and fails, the gadget is set to `UNBOUND` and the user gets stuck. This looks like a definite bug. `gadgetfs_bind` should not transition to `UNBOUND` state if bind fails, and ideally should roll back those 5 steps.
|
| 53/2 |
2026/07/31 06:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:activate_ep_files]
Results: map[SourceCode:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
1610: data->dev = dev;
1611: get_dev (dev);
1612:
1613: data->ep = ep;
1614: ep->driver_data = data;
1615:
1616: data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1617: if (!data->req)
1618: goto enomem1;
1619:
1620: err = gadgetfs_create_file (dev->sb, data->name,
1621: data, &ep_io_operations);
1622: if (err)
1623: goto enomem2;
1624: list_add_tail (&data->epfiles, &dev->epfiles);
1625: }
1626: return 0;
1627:
1628: enomem2:
1629: usb_ep_free_request (ep, data->req);
1630: enomem1:
1631: put_dev (dev);
1632: kfree (data);
1633: enomem0:
1634: DBG (dev, "%s enomem\n", __func__);
1635: destroy_ep_files (dev);
1636: return -ENOMEM;
1637: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 54/2 |
2026/07/31 06:29 |
llm |
debugger |
0m
Model:
Tokens:
input: 43828
output: 41
thoughts: 99
Thoughts: **Double Destruction? A Potential Problem**
Okay, so I'm looking at this `activate_ep_files` function, and it seems like if that fails, it immediately calls `destroy_ep_files(dev)`. That's good, cleans up after itself. But, hang on... if `activate_ep_files` *does* fail, those endpoint files are already destroyed, right? Now, later on, the code goes into `gadgetfs_bind`. If *that* hits an `ENOMEM` error, it calls `gadgetfs_unbind`. And guess what `gadgetfs_unbind` does? Yep, calls `destroy_ep_files(dev)` *again*! That's a red flag. We might be attempting to destroy files that are already gone, or have unpredictable behavior. I better check `destroy_ep_files` to see how this double call is handled, or if it's even safe. This could lead to all sorts of issues.
|
| 55/2 |
2026/07/31 06:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:destroy_ep_files]
Results: map[SourceCode:1554: static void destroy_ep_files (struct dev_data *dev)
1555: {
1556: DBG (dev, "%s %d\n", __func__, dev->state);
1557:
1558: /* dev->state must prevent interference */
1559: spin_lock_irq (&dev->lock);
1560: while (!list_empty(&dev->epfiles)) {
1561: struct ep_data *ep;
1562:
1563: /* break link to FS */
1564: ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles);
1565: list_del_init (&ep->epfiles);
1566: spin_unlock_irq (&dev->lock);
1567:
1568: /* break link to controller */
1569: mutex_lock(&ep->lock);
1570: if (ep->state == STATE_EP_ENABLED)
1571: (void) usb_ep_disable (ep->ep);
1572: ep->state = STATE_EP_UNBOUND;
1573: usb_ep_free_request (ep->ep, ep->req);
1574: ep->ep = NULL;
1575: mutex_unlock(&ep->lock);
1576:
1577: wake_up (&ep->wait);
1578:
1579: /* break link to dcache */
1580: simple_remove_by_name(dev->sb->s_root, ep->name, NULL);
1581:
1582: put_ep (ep);
1583:
1584: spin_lock_irq (&dev->lock);
1585: }
1586: spin_unlock_irq (&dev->lock);
1587: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 56/2 |
2026/07/31 06:29 |
llm |
debugger |
0m
Model:
Tokens:
input: 44722
output: 63
thoughts: 732
Thoughts: **Refining the GadgetFS Bind/Unbind Logic**
Okay, let's break this down. My initial thought was that calling `destroy_ep_files` multiple times wouldn't be an issue because of the `list_empty` check. But the core concern is in the interaction between `gadgetfs_bind` and `gadgetfs_unbind`. `gadgetfs_unbind` calls `put_dev(dev)` and sets `dev->state` to `STATE_DEV_UNBOUND`. This is where it gets tricky.
If `gadgetfs_bind` fails, it should only undo what it *did*. That means freeing the request, clearing the endpoint's driver data, setting gadget to null, and setting gadget data to null. It *should not* call `put_dev(dev)` because no `get_dev` has happened yet, and it *should not* set `dev->state` to `STATE_DEV_UNBOUND` since the device was never actually bound.
Therefore, the updated `gadgetfs_bind` should look like this:
```c
enomem:
if (dev->req) {
usb_ep_free_request (gadget->ep0, dev->req);
dev->req = NULL;
}
gadget->ep0->driver_data = NULL;
dev->gadget = NULL;
set_gadget_data (gadget, NULL);
return -ENOMEM;
```
This leaves `dev->state` as `STATE_DEV_OPENED`, which means `dev_config` can be retried in a future iteration.
Now, considering the other actions in `gadgetfs_unbind`:
```c
spin_lock_irq (&dev->lock);
dev->state = STATE_DEV_UNBOUND;
while (dev->udc_usage > 0) {
spin_unlock_irq(&dev->lock);
usleep_range(1000, 2000);
spin_lock_irq(&dev->lock);
}
spin_unlock_irq (&dev->lock);
```
Since `gadgetfs_bind` hasn't finished, `dev->udc_usage` must be zero because it's only incremented during setup requests. These can't happen before `gadgetfs_bind` completes and the UDC is enabled. So, we don't need to worry about waiting for `udc_usage`.
What about `destroy_ep_files(dev)`? `activate_ep_files` calls it if it fails. However, if `usb_ep_alloc_request` fails, `activate_ep_files` is not called, and so no cleanup happens. However, in this scenario, `dev->epfiles` will be empty regardless. Therefore, no additional calls to `destroy_ep_files(dev)` are needed.
To be thorough, let's verify where `gadgetfs_unbind` is called. It's only called from `gadgetfs_bind` on error and by `usb_gadget_unregister_driver` via `gadgetfs_driver.unbind`. This makes the logic cleaner, eliminating redundant actions and ensuring correct state management.
|
| 57/2 |
2026/07/31 06:29 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c IncludeSnippetLines:2 Name:gadgetfs_unbind SourceTreePrefix:drivers/usb/gadget/legacy/]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:gadgetfs_bind SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1703 SourceSnippet:1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:gadgetfs_driver SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1749 SourceSnippet:1747: .function = (char *) driver_desc,
1748: .bind = gadgetfs_bind,
1749: .unbind = gadgetfs_unbind,
1750: .setup = gadgetfs_setup,
1751: .reset = gadgetfs_disconnect,
]] TruncatedOutput:false]
|
| 58/2 |
2026/07/31 06:29 |
llm |
debugger |
0m
Model:
Tokens:
input: 46523
output: 41
thoughts: 304
Thoughts: **Fixing the `gadgetfs` Bind Issue**
Okay, here's what I'm thinking. The problem looks like it's contained within `gadgetfs_bind` and `gadgetfs_driver.unbind`. If we modify `gadgetfs_bind` so that it doesn't call `gadgetfs_unbind` to handle the clean-up, but instead handles the clean-up directly, this should fix the issue.
Let me jot down exactly what clean-up needs to happen within `gadgetfs_bind` if there's an `enomem` failure:
```c
enomem:
if (dev->req) {
usb_ep_free_request (gadget->ep0, dev->req);
dev->req = NULL;
}
gadget->ep0->driver_data = NULL;
dev->gadget = NULL;
set_gadget_data (gadget, NULL);
return -ENOMEM;
```
Hang on a second. If `activate_ep_files` fails, it returns a negative error code. So, should `gadgetfs_bind` return that error code instead of just `-ENOMEM`? Let's check the current code:
```c
if (activate_ep_files (dev) < 0)
goto enomem;
```
Ah, right. And `enomem` returns `-ENOMEM`. But `activate_ep_files` *also* returns `-ENOMEM` on failure. So, we're already returning the expected error code.
Okay, let me just double-check `activate_ep_files` again to make sure I haven't missed anything.
|
| 59/2 |
2026/07/31 06:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:activate_ep_files]
Results: map[SourceCode:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
1610: data->dev = dev;
1611: get_dev (dev);
1612:
1613: data->ep = ep;
1614: ep->driver_data = data;
1615:
1616: data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1617: if (!data->req)
1618: goto enomem1;
1619:
1620: err = gadgetfs_create_file (dev->sb, data->name,
1621: data, &ep_io_operations);
1622: if (err)
1623: goto enomem2;
1624: list_add_tail (&data->epfiles, &dev->epfiles);
1625: }
1626: return 0;
1627:
1628: enomem2:
1629: usb_ep_free_request (ep, data->req);
1630: enomem1:
1631: put_dev (dev);
1632: kfree (data);
1633: enomem0:
1634: DBG (dev, "%s enomem\n", __func__);
1635: destroy_ep_files (dev);
1636: return -ENOMEM;
1637: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 60/2 |
2026/07/31 06:29 |
llm |
debugger |
0m
Model:
Tokens:
input: 47909
output: 40
thoughts: 685
Thoughts: **Dangling Pointers in Endpoint File Activation**
Okay, so I'm looking at this `activate_ep_files` function, and it's got a potential problem. If it fails, it calls `destroy_ep_files` to clean up. Standard procedure. But wait a minute... let's walk through this. `destroy_ep_files` iterates through `dev->epfiles` and frees the endpoints that *were* successfully added. It makes sense, right? But what about the current endpoint where the failure occurred?
The error path, if `gadgetfs_create_file` fails, jumps down to `enomem2`, which then frees `data->req`. `enomem1` frees the `data` itself. Finally, `enomem0` calls `destroy_ep_files`. Now, here's where it gets interesting... The current endpoint, the one that's failing, hasn't actually been added to `dev->epfiles` *yet* because that's done *after* the `gadgetfs_create_file` succeeds. So, `destroy_ep_files` correctly frees the *previous* endpoints that were successfully created and added to `dev->epfiles`. Fine.
But I'm worried about the `ep->driver_data` pointer. The code sets `data->ep = ep;` and then `ep->driver_data = data;`. If `gadgetfs_create_file` fails, `data` gets freed. But `ep->driver_data` is *not* cleared! This is a dangling pointer.
If the UDC core sees that `gadgetfs_bind` is failing, then the gadget driver isn't used. So the UDC core won't use the gadget driver. But this leaves `ep->driver_data` pointing to freed memory. That's bad. Later, the UDC driver could be bound to another gadget driver and overwrite this, or it might not care about it. Still, the dangling pointer is there.
And wait, there's more. The `destroy_ep_files` function also has this:
```c
mutex_lock(&ep->lock);
if (ep->state == STATE_EP_ENABLED)
(void) usb_ep_disable (ep->ep);
ep->state = STATE_EP_UNBOUND;
usb_ep_free_request (ep->ep, ep->req);
ep->ep = NULL;
mutex_unlock(&ep->lock);
```
It disables and frees the requests on each endpoint. Okay. But it doesn't clear `ep->ep->driver_data` either! That's a dangling pointer as well. Now I see that `ep->ep` is a `struct usb_ep *`. Does this even matter? No.
Where else is this `ep->driver_data` used? I've got to check. Looking at `ep_io_operations`, it's used there (like in `ep_read`, `ep_write`), where `data` is retrieved from `fd->private_data`. Also, it's used in completion handlers. I've got to check `epio_complete`. Dangling pointers in those operations could cause serious problems... Okay, that's definitely a point to raise.
|
| 61/2 |
2026/07/31 06:30 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:epio_complete]
Results: map[SourceCode: 279: static void epio_complete (struct usb_ep *ep, struct usb_request *req)
280: {
281: struct ep_data *epdata = ep->driver_data;
282:
283: if (!req->context)
284: return;
285: if (req->status)
286: epdata->status = req->status;
287: else
288: epdata->status = req->actual;
289: complete ((struct completion *)req->context);
290: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 62/2 |
2026/07/31 06:30 |
llm |
debugger |
0m
Model:
Tokens:
input: 49562
output: 39
thoughts: 3783
Thoughts: **Root Cause Analysis and Proposed Fix for Use-After-Free in GadgetFS**
Okay, here's my breakdown of this use-after-free bug in the GadgetFS driver. We're looking at a classic scenario where an unbalanced `get_dev()` and `put_dev()` operation leads to a premature free of a `dev` structure.
1. **The Bug**: The core of the problem lies in how `gadgetfs_bind` handles errors. If `gadgetfs_bind` fails *after* allocating resources but *before* taking the device's reference (via `get_dev()`), an unnecessary call to `gadgetfs_unbind()` happens in error paths. This call effectively *drops* a reference *that was never taken* and messes with the refcount of the `dev` structure. This leaves the device in `STATE_DEV_OPENED`, allowing the user to attempt to configure the device again.
The critical failure scenarios involve errors during allocation in `gadgetfs_bind`. In this scenario, an error return does not correctly balance the `get_dev` and `put_dev` calls which leads to the crash.
2. **Detailed Trace**:
Let's walk through the steps, focusing on the refcount of `dev`:
* `gadgetfs_fill_super()`: Creates the `dev` struct using `dev_new()`. The initial refcount is 1.
* `openat()` & `gadget_dev_open()`: A user process opens the device. `gadget_dev_open()` is called. `get_dev()` is called. The refcount is incremented to 2.
* `write()` & `dev_config()`: The user writes to the device to configure it. `dev_config()` handles this. It subsequently calls `usb_gadget_register_driver()`, which in turn, calls `gadget_bind_driver()` and finally calls `gadgetfs_bind()`.
* `gadgetfs_bind()` Success Case: If `gadgetfs_bind()` is successful, it calls `set_gadget_data(gadget, dev)`, and `get_dev(dev)` is called which increments the refcount. The refcount is now 3. Later, when the driver is unregistered, `gadgetfs_unbind` calls `put_dev`, dropping the refcount to 2, balancing the previous `get_dev`. The problem is that in the failure case, `get_dev(dev)` is not called.
* `gadgetfs_bind()` Failure Case: A fault in `activate_ep_files` causes `gadgetfs_bind` to return an error. In this scenario `gadgetfs_bind()` jumps to `enomem` and calls `gadgetfs_unbind()`. This function drops a reference (via `put_dev()`) *that was never taken* because `get_dev()` was never called. Because of this, it can also set `dev->state` to `STATE_DEV_UNBOUND`, preventing the user from reconfiguring the device. The refcount is decremented to 1.
* `write()` returns `-ENOMEM`.
* `close()` & `dev_release()`: When the user closes the device, `dev_release()` is called, and `put_dev()` is called. The refcount is decremented to 0, which frees the `dev` struct.
* `openat()` & `gadget_dev_open()`: The user opens the device again. But now the `dev` struct has been freed. The code tries to access `inode->i_private` which is `dev`. This use-after-free error.
3. **Proposed Fix**: We need to ensure that `gadgetfs_bind` *only* calls code to balance the call to `get_dev()` if it was actually called. This is done by removing the call to `gadgetfs_unbind()` in the failure path of `gadgetfs_bind`. Also, we need to balance any resources which were allocated by the failed code.
Here's the corrected `gadgetfs_bind()` function:
```c
static int gadgetfs_bind(struct usb_gadget *gadget,
struct usb_gadget_driver *driver)
{
struct dev_data *dev = the_device;
if (!dev)
return -ESRCH;
if (0 != strcmp (CHIP, gadget->name)) {
pr_err("%s expected %
|
| 63/2 |
2026/07/31 06:30 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:put_ep]
Results: map[SourceCode: 217: static void put_ep (struct ep_data *data)
218: {
219: if (likely (!refcount_dec_and_test (&data->count)))
220: return;
221: put_dev (data->dev);
222: /* needs no more cleanup */
223: BUG_ON (!list_empty (&data->epfiles));
224: BUG_ON (waitqueue_active (&data->wait));
225: kfree (data);
226: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 64/2 |
2026/07/31 06:30 |
llm |
debugger |
0m
Model:
Tokens:
input: 54593
output: 102
thoughts: 241
Thoughts: **Refcount Management and the `gadgetfs_bind` Imbalance**
Okay, so I've finally traced through this, and it all clicks. `put_ep` calls `put_dev(data->dev)`. Right, that's the key. That balances the `get_dev(dev)` calls within `activate_ep_files`:
```c
refcount_set (&data->count, 1);
data->dev = dev;
get_dev (dev);
```
So, essentially, `activate_ep_files` takes a reference to the `dev` object for *each* endpoint file it creates. Then, when that endpoint file is destroyed, `put_ep` properly releases that `dev` reference. That's all clean and balanced; it all makes sense. The refcounting scheme itself is solid.
The problem, as I suspected, is in `gadgetfs_bind`. It's calling `gadgetfs_unbind` on failure. And *that's* the imbalance! The `gadgetfs_bind` function isn't consistently pairing with any `get_dev`. The fault injection makes this obvious. `gadgetfs_bind` can fail and call `gadgetfs_unbind`, which releases a reference to the device that was never acquired.
Now I've got a complete picture of the problem. Time to put together the final response. I can clearly explain how `dev`'s refcount is handled, how the fault injection exposes the error in `gadgetfs_bind`, and how `gadgetfs_unbind` is the culprit by dropping a reference it didn't take. I can also confidently explain that the best fix is to replace that `gadgetfs_unbind` call with manual cleanup within `gadgetfs_bind`. That's where it all needs to be handled properly.
|
| 65/2 |
2026/07/31 06:30 |
tool |
codeexpert |
12m
Args: map[Question:Is there any reason why `gadgetfs_bind` in `drivers/usb/gadget/legacy/inode.c` should call `gadgetfs_unbind` on failure instead of just doing manual cleanup? If it calls `gadgetfs_unbind`, it drops a `dev` reference via `put_dev` that it hasn't acquired yet (since `get_dev` is only called on success).]
Results: map[Answer:No, there is no valid reason why `gadgetfs_bind` should call `gadgetfs_unbind` on failure. In fact, doing so is a bug that introduces several critical issues, most notably a reference counting imbalance that leads to a Use-After-Free (UAF) or double free.
### 1. Reference Counting Bug (UAF / Double Free)
The reference count of the `dev_data` structure (`dev->count`) is managed as follows:
- **Initialization**: Set to `1` in `dev_new()` when the filesystem is mounted (via `gadgetfs_fill_super`).
- **File Open**: Incremented to `2` in `gadget_dev_open()` when the user opens `/dev/gadget/$CHIP`.
- **Successful Bind**: Incremented to `3` via `get_dev(dev)` at the very end of `gadgetfs_bind()` (line 1699).
- **Failed Bind**: If `gadgetfs_bind()` fails (e.g., due to memory allocation failure in `usb_ep_alloc_request` or `activate_ep_files`), it jumps to `enomem` and calls `gadgetfs_unbind(gadget)`.
- Inside `gadgetfs_unbind()`, `put_dev(dev)` is called, which decrements the reference count of `dev` to `1`.
- However, `get_dev(dev)` was **never called** because the bind failed before reaching line 1699.
- When the user subsequently closes the open file descriptor, `dev_release()` is called and invokes `put_dev(dev)`, decrementing the reference count to `0` and freeing `dev`.
- Finally, when the filesystem is unmounted, `gadgetfs_kill_sb()` is called and invokes `put_dev(the_device)`. Since `the_device` points to the already-freed `dev`, this results in a **Use-After-Free (UAF) or double free**.
### 2. Other Issues Caused by Calling `gadgetfs_unbind` on Failure
- **Dangling Pointer**: `gadgetfs_unbind()` does not clear `dev->gadget`, leaving a dangling pointer to the `gadget` structure in `dev->gadget`.
- **Irrecoverable State**: `gadgetfs_unbind()` sets `dev->state = STATE_DEV_UNBOUND`. This prevents the user from retrying the configuration write on the open file descriptor. If manual cleanup was done instead, `dev->state` would remain `STATE_DEV_OPENED`, allowing the user to potentially retry the configuration write.
- **Redundant Cleanup**: If `activate_ep_files()` fails, it already calls `destroy_ep_files(dev)` internally to clean up any endpoint files it created. Calling `gadgetfs_unbind()` subsequently results in a redundant call to `destroy_ep_files(dev)`.
### 3. How Manual Cleanup Should Look
Instead of calling `gadgetfs_unbind()`, `gadgetfs_bind()` should perform manual cleanup on failure:
- **If `usb_ep_alloc_request` fails**:
```c
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
- **If `activate_ep_files` fails**:
```c
usb_ep_free_request(gadget->ep0, dev->req);
dev->req = NULL;
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
This manual cleanup is perfectly balanced, avoids the reference count drop, clears the dangling pointer, leaves the state as `STATE_DEV_OPENED` for retries, and avoids redundant cleanup.]
|
| 66/3 |
2026/07/31 06:30 |
agent |
codeexpert |
12m
Model:
Results: map[Answer:No, there is no valid reason why `gadgetfs_bind` should call `gadgetfs_unbind` on failure. In fact, doing so is a bug that introduces several critical issues, most notably a reference counting imbalance that leads to a Use-After-Free (UAF) or double free.
### 1. Reference Counting Bug (UAF / Double Free)
The reference count of the `dev_data` structure (`dev->count`) is managed as follows:
- **Initialization**: Set to `1` in `dev_new()` when the filesystem is mounted (via `gadgetfs_fill_super`).
- **File Open**: Incremented to `2` in `gadget_dev_open()` when the user opens `/dev/gadget/$CHIP`.
- **Successful Bind**: Incremented to `3` via `get_dev(dev)` at the very end of `gadgetfs_bind()` (line 1699).
- **Failed Bind**: If `gadgetfs_bind()` fails (e.g., due to memory allocation failure in `usb_ep_alloc_request` or `activate_ep_files`), it jumps to `enomem` and calls `gadgetfs_unbind(gadget)`.
- Inside `gadgetfs_unbind()`, `put_dev(dev)` is called, which decrements the reference count of `dev` to `1`.
- However, `get_dev(dev)` was **never called** because the bind failed before reaching line 1699.
- When the user subsequently closes the open file descriptor, `dev_release()` is called and invokes `put_dev(dev)`, decrementing the reference count to `0` and freeing `dev`.
- Finally, when the filesystem is unmounted, `gadgetfs_kill_sb()` is called and invokes `put_dev(the_device)`. Since `the_device` points to the already-freed `dev`, this results in a **Use-After-Free (UAF) or double free**.
### 2. Other Issues Caused by Calling `gadgetfs_unbind` on Failure
- **Dangling Pointer**: `gadgetfs_unbind()` does not clear `dev->gadget`, leaving a dangling pointer to the `gadget` structure in `dev->gadget`.
- **Irrecoverable State**: `gadgetfs_unbind()` sets `dev->state = STATE_DEV_UNBOUND`. This prevents the user from retrying the configuration write on the open file descriptor. If manual cleanup was done instead, `dev->state` would remain `STATE_DEV_OPENED`, allowing the user to potentially retry the configuration write.
- **Redundant Cleanup**: If `activate_ep_files()` fails, it already calls `destroy_ep_files(dev)` internally to clean up any endpoint files it created. Calling `gadgetfs_unbind()` subsequently results in a redundant call to `destroy_ep_files(dev)`.
### 3. How Manual Cleanup Should Look
Instead of calling `gadgetfs_unbind()`, `gadgetfs_bind()` should perform manual cleanup on failure:
- **If `usb_ep_alloc_request` fails**:
```c
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
- **If `activate_ep_files` fails**:
```c
usb_ep_free_request(gadget->ep0, dev->req);
dev->req = NULL;
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
This manual cleanup is perfectly balanced, avoids the reference count drop, clears the dangling pointer, leaves the state as `STATE_DEV_OPENED` for retries, and avoids redundant cleanup.]
Instruction:
You are a capable Linux kernel developer tasked with researching complex questions
about kernel source code. You will be given a concrete question, and need to provide
a concrete answer.
Use tools extensively while researching the question. Don't make assumptions,
or rely on your previous knowledge about the kernel source code, use available tools
to access the actual source code.
Use all available sources of information:
- kernel source code
- documentation in the Documentation dir in the source tree
- git commits descriptions, git blame
Do not guess file names or file paths and attempt to read them without
verifying their existence first using content search or directory listing tools.
If a file, symbol, or directory is not found via content search (grepper) or
directory listing (codesearch-dir-index), treat it as completely absent.
Do not attempt to guess alternative names, extensions, or directories.
Tool Selection Guidelines:
1. For C functions, structs, and variables: Prefer codesearch-definition-source
or codesearch-struct-layout FIRST to retrieve clean, exact definitions
without line-number guessing.
2. If symbol lookup fails (e.g., preprocessor macros, macro-generated code, or
disabled #ifdef branches), fall back to read-file or grepper.
3. For file headers, #include directives, preprocessor macro definitions, and
non-C files (Kconfig, Makefiles, docs): Use read-file or grepper directly.
Do NOT use git-log to search for the presence or existence of files in the
repository. git-log is only for tracing commit history of files that are
already present in the current checkout. If a file does not exist in the
current checkout, it cannot be used for reproduction.
Avoid running broad git-log queries (such as searches on the entire repo)
without a specific 'PathPrefix' to restrict the scope, as these are very
expensive and will time out.
If a git-log tool call times out, do not retry the query with the same broad
scope. You must specify a tighter, narrower 'PathPrefix' for subsequent queries.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Is there any reason why `gadgetfs_bind` in `drivers/usb/gadget/legacy/inode.c` should call `gadgetfs_unbind` on failure instead of just doing manual cleanup? If it calls `gadgetfs_unbind`, it drops a `dev` reference via `put_dev` that it hasn't acquired yet (since `get_dev` is only called on success).
|
| 67/4 |
2026/07/31 06:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 3949
output: 41
thoughts: 84
Thoughts: **Investigating `gadgetfs_bind` in the USB Gadget Legacy Driver**
Okay, so we have a precise question about `gadgetfs_bind`. My first thought is to get my bearings. Let's start by pinpointing the file location. It seems like it's in `drivers/usb/gadget/legacy/inode.c`, so I'll quickly navigate there. Now that I have the source code open, I'll need to understand the context of `gadgetfs_bind`. To truly grasp its role, I'll use the `codesearch-definition-source` function; this will give me the most direct and reliable insight into its definition and how it's used within the codebase. This method will help me quickly see where it is defined and how it is employed. This is the optimal approach to understand the relevant function.
|
| 68/4 |
2026/07/31 06:30 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_bind]
Results: map[SourceCode:1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 69/4 |
2026/07/31 06:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 4842
output: 41
thoughts: 18
Thoughts: Okay, here's my take on those thoughts, framed as my own:
**Analyzing `gadgetfs_unbind`**
Right, let's circle back and examine `gadgetfs_unbind` within this same file. I want to see how this function handles the unbinding process. Specifically, I'm thinking about the implications for resource management and potential race conditions in the context of our existing device driver implementation. Understanding how it cleans up after a device is unbound is critical, especially when we consider the asynchronous nature of some of these operations and the concurrent access patterns. We need to confirm it's robust and prevents any lingering data structures or handles from causing problems down the line. We must cross-reference this with the existing unbinding mechanisms and look for any overlapping considerations. It's time to dig into the details.
|
| 70/4 |
2026/07/31 06:30 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_unbind]
Results: map[SourceCode:1639: static void
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
1643:
1644: DBG (dev, "%s\n", __func__);
1645:
1646: spin_lock_irq (&dev->lock);
1647: dev->state = STATE_DEV_UNBOUND;
1648: while (dev->udc_usage > 0) {
1649: spin_unlock_irq(&dev->lock);
1650: usleep_range(1000, 2000);
1651: spin_lock_irq(&dev->lock);
1652: }
1653: spin_unlock_irq (&dev->lock);
1654:
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 71/4 |
2026/07/31 06:30 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 5514
output: 35
thoughts: 1334
Thoughts: **Analyzing the Bind/Unbind Logic in `gadgetfs`**
Okay, let's break down this `gadgetfs_bind` and `gadgetfs_unbind` interaction. First, in `gadgetfs_bind`, I see we're attempting to bind to a USB gadget. It retrieves the `dev_data` structure and performs a couple of checks: verifying the gadget name and, if those are passed, proceeds to configure it. Crucially, it pre-allocates a control request via `usb_ep_alloc_request` and sets up some associated files with `activate_ep_files`.
Here's where it gets interesting: If either `usb_ep_alloc_request` *or* `activate_ep_files` fails, the code jumps to the `enomem` label, and **then** calls `gadgetfs_unbind`. My immediate thought is, why call a separate unbind function? Why not just handle the cleanup directly within `gadgetfs_bind`? This seems like unnecessary overhead if it is all that is going on.
Now, let's step through what `gadgetfs_unbind` does. It's pulling the `dev_data` structure using `get_gadget_data`, sets the device state to `STATE_DEV_UNBOUND`, and includes a spinlock and loop that checks `dev->udc_usage`. It then proceeds to clean up by calling `destroy_ep_files`, nullifying `gadget->ep0->driver_data` and the gadget data, and finally, it frees the allocated request if it exists using `usb_ep_free_request`. Lastly, it calls `put_dev`.
Okay, the question is, why this indirect call and not a local cleanup at `enomem`? This is a bit unusual. One possibility is the need to synchronize access, so the spinlocks are understandable but it could be cleaner. Another possibility is a historical reason, perhaps refactoring, or to deal with concurrency. I need to understand the intent of the author/original design. To get a better sense of the rationale behind this design, I should go back and examine the commit history. Looking for changes made to `gadgetfs_bind` or the associated `inode.c` files should reveal the evolution of this code. It's likely the refactoring may have originally occurred in the `legacy/inode.c` file before being moved to the more generic name. Let's start with `git log` and see what we can find.
|
| 72/4 |
2026/07/31 06:31 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_bind PathPrefix:drivers/usb/gadget/]
Results: map[Output:ffe0b3350625 usb: gadget: remove global variable composite in composite.c
93952956c707 usb: gadget: move bind() callback back to struct usb_gadget_driver
b0fca50f5a94 usb gadget: don't save bind callback in struct usb_gadget_driver
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 73/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 7540
output: 42
thoughts: 73
Thoughts: **Analyzing the GadgetFS Bind Function**
Okay, let's dive into this `gadgetfs_bind` function. I need to understand its evolution and the rationale behind its current state. I'll start by examining the commit history and the blame information for this function within the `drivers/usb/gadget/legacy/inode.c` file. Specifically, I'm interested in the lines around 1668 to 1705, as that seems to be where the core logic of the bind operation resides. I'll use `git-blame` on those lines to pinpoint the authors and their associated commits, to trace the lineage and see if any relevant context is provided in the commit messages. Understanding the evolution of these lines will likely be key to understanding the bind function.
|
| 74/4 |
2026/07/31 06:31 |
tool |
git-blame |
0m
Args: map[End:1705 File:drivers/usb/gadget/legacy/inode.c Start:1668]
Results: map[Output:ffe0b33506250 drivers/usb/gadget/inode.c 1668) static int gadgetfs_bind(struct usb_gadget *gadget,
ffe0b33506250 drivers/usb/gadget/inode.c 1669) struct usb_gadget_driver *driver)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1670) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1671) struct dev_data *dev = the_device;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1672)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1673) if (!dev)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1674) return -ESRCH;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1675) if (0 != strcmp (CHIP, gadget->name)) {
00274921a052d drivers/usb/gadget/inode.c 1676) pr_err("%s expected %s controller not %s\n",
^1da177e4c3f4 drivers/usb/gadget/inode.c 1677) shortname, CHIP, gadget->name);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1678) return -ENODEV;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1679) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1680)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1681) set_gadget_data (gadget, dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1682) dev->gadget = gadget;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1683) gadget->ep0->driver_data = dev;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1684)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1685) /* preallocate control response and buffer */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1686) dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1687) if (!dev->req)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1688) goto enomem;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1689) dev->req->context = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1690) dev->req->complete = epio_complete;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1691)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1692) if (activate_ep_files (dev) < 0)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1693) goto enomem;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1694)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1695) INFO (dev, "bound to %s driver\n", gadget->name);
7489d14943181 drivers/usb/gadget/inode.c 1696) spin_lock_irq(&dev->lock);
7489d14943181 drivers/usb/gadget/inode.c 1697) dev->state = STATE_DEV_UNCONNECTED;
7489d14943181 drivers/usb/gadget/inode.c 1698) spin_unlock_irq(&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1699) get_dev (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1700) return 0;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1701)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1702) enomem:
^1da177e4c3f4 drivers/usb/gadget/inode.c 1703) gadgetfs_unbind (gadget);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1704) return -ENOMEM;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1705) }
]
|
| 75/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 9288
output: 39
thoughts: 140
Thoughts: **Deep Dive into Ancient Code**
Okay, here we go. This snippet is ancient history – practically fossilized! This code has been around since the very genesis of Git, all the way back to the initial import of Linux 2.6.12-rc2 with commit `1da177e4c3f4`. Before I start tearing into it, I need to get a lay of the land.
My initial thought was to hunt for any reported issues, discussions, or subsequent commits that touch upon `gadgetfs_bind`, `gadgetfs_unbind`, or even `put_dev` within the `inode.c` file. However, that's not quite the right approach. It seems more relevant to focus on `put_dev` and `get_dev` but in the `drivers/usb/gadget/legacy/inode.c` file. I need to refresh my memory and pinpoint their definitions. That's the core focus right now. Knowing their definitions would be a good start.
|
| 76/4 |
2026/07/31 06:31 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:put_dev]
Results: map[SourceCode: 163: static void put_dev (struct dev_data *data)
164: {
165: if (likely (!refcount_dec_and_test (&data->count)))
166: return;
167: /* needs no more cleanup */
168: BUG_ON (waitqueue_active (&data->wait));
169: kfree (data);
170: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 77/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 9832
output: 39
thoughts: 37
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience:
**Examining Device Number Retrieval**
Right, so I've realized that the `put_dev` and `get_dev` functions are *actually* defined within `inode.c`. That's a bit of a detail I missed initially, which explains why I wasn't finding them declared elsewhere. Okay, let's zoom in on `get_dev` specifically, and see how it is implemented. We need to check both for completeness, and correctness.
|
| 78/4 |
2026/07/31 06:31 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:get_dev]
Results: map[SourceCode: 158: static inline void get_dev (struct dev_data *data)
159: {
160: refcount_inc (&data->count);
161: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 79/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10112
output: 46
thoughts: 39
Thoughts: Okay, let's break this down.
**Investigating a Device Driver's Memory Management**
Hold on a second! Before I proceed any further with this debugging or analysis, I need to get a clear picture of how this device, let's call it `dev`, is being managed. My immediate concern is its memory allocation. Where exactly is this `dev` variable allocated in the system? More importantly, I need to understand its initial reference count, or how many parts of the system are pointing to this device. This is crucial for understanding the potential for resource contention, leaks, or premature deallocation issues.
To find that allocation, I'll start by searching the code base for any explicit references to device allocation, specifically keywords like `the_device` or `dev_data`. These are common naming conventions I've encountered for structures containing device-specific information, and often they're near where memory for the device is allocated. I'll need to locate where `the_device` or `dev_data` is initialized.
|
| 80/4 |
2026/07/31 06:31 |
tool |
codesearch-find-references |
0m
Error:
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c IncludeSnippetLines:10 Name:the_device]
Results: map[References:<nil> TruncatedOutput:false]
|
| 81/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 10435
output: 35
thoughts: 47
Thoughts: Okay, here's my interpretation of that thought process, from an expert's perspective:
**Debugging a Global Variable in a USB Gadget Driver**
Alright, a global variable, `the_device`, is causing me some grief. The fact that it's global immediately raises a red flag; those things can be a nightmare to track down, especially in a kernel module. I need to understand its scope and usage within the `drivers/usb/gadget/legacy/inode.c` file, since that's where the problem seems to be originating. To find its definition or any code that references it, I'll leverage `grepper`. Using grep effectively is key to navigating the codebase. This is a common and quick way for me to find the root of the issue.
|
| 82/4 |
2026/07/31 06:31 |
tool |
grepper |
0m
Args: map[Expression:the_device PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:drivers/usb/gadget/legacy/inode.c=1640=gadgetfs_unbind (struct usb_gadget *gadget)
--
drivers/usb/gadget/legacy/inode.c-1665-
drivers/usb/gadget/legacy/inode.c:1666:static struct dev_data *the_device;
drivers/usb/gadget/legacy/inode.c-1667-
drivers/usb/gadget/legacy/inode.c=1668=static int gadgetfs_bind(struct usb_gadget *gadget,
--
drivers/usb/gadget/legacy/inode.c-1670-{
drivers/usb/gadget/legacy/inode.c:1671: struct dev_data *dev = the_device;
drivers/usb/gadget/legacy/inode.c-1672-
--
drivers/usb/gadget/legacy/inode.c=2015=gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc)
--
drivers/usb/gadget/legacy/inode.c-2022-
drivers/usb/gadget/legacy/inode.c:2023: if (the_device) {
drivers/usb/gadget/legacy/inode.c-2024- rc = -ESRCH;
--
drivers/usb/gadget/legacy/inode.c-2067- */
drivers/usb/gadget/legacy/inode.c:2068: the_device = dev;
drivers/usb/gadget/legacy/inode.c-2069- rc = 0;
--
drivers/usb/gadget/legacy/inode.c=2099=gadgetfs_kill_sb (struct super_block *sb)
--
drivers/usb/gadget/legacy/inode.c-2102- kill_anon_super (sb);
drivers/usb/gadget/legacy/inode.c:2103: if (the_device) {
drivers/usb/gadget/legacy/inode.c:2104: put_dev (the_device);
drivers/usb/gadget/legacy/inode.c:2105: the_device = NULL;
drivers/usb/gadget/legacy/inode.c-2106- }
]
|
| 83/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 11264
output: 41
thoughts: 55
Thoughts: Okay, let's dive in.
**Analyzing `gadgetfs_fill_super` and Device Data Allocation**
Right, let's get down to brass tacks. I'm going to focus my attention on the `gadgetfs_fill_super` function and the crucial process of allocating `dev_data`. Specifically, I'm pulling up lines 2015 through 2075 within `drivers/usb/gadget/legacy/inode.c`. That section should give me the core logic for how the filesystem's superblock gets initialized and, importantly, how device-specific data is handled during the mount. I need to understand this to determine if the device is being correctly represented. Understanding this process will give me a better understanding of the overall filesystem structure.
|
| 84/4 |
2026/07/31 06:31 |
tool |
read-file |
0m
Args: map[File:drivers/usb/gadget/legacy/inode.c FirstLine:2015 LineCount:60]
Results: map[Contents:2015: gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc)
2016: {
2017: struct inode *inode;
2018: struct dev_data *dev;
2019: int rc;
2020:
2021: mutex_lock(&sb_mutex);
2022:
2023: if (the_device) {
2024: rc = -ESRCH;
2025: goto Done;
2026: }
2027:
2028: CHIP = usb_get_gadget_udc_name();
2029: if (!CHIP) {
2030: rc = -ENODEV;
2031: goto Done;
2032: }
2033:
2034: /* superblock */
2035: sb->s_blocksize = PAGE_SIZE;
2036: sb->s_blocksize_bits = PAGE_SHIFT;
2037: sb->s_magic = GADGETFS_MAGIC;
2038: sb->s_op = &gadget_fs_operations;
2039: sb->s_time_gran = 1;
2040:
2041: /* root inode */
2042: inode = gadgetfs_make_inode (sb,
2043: NULL, &simple_dir_operations,
2044: S_IFDIR | S_IRUGO | S_IXUGO);
2045: if (!inode)
2046: goto Enomem;
2047: inode->i_op = &simple_dir_inode_operations;
2048: if (!(sb->s_root = d_make_root (inode)))
2049: goto Enomem;
2050:
2051: /* the ep0 file is named after the controller we expect;
2052: * user mode code can use it for sanity checks, like we do.
2053: */
2054: dev = dev_new ();
2055: if (!dev)
2056: goto Enomem;
2057:
2058: dev->sb = sb;
2059: rc = gadgetfs_create_file(sb, CHIP, dev, &ep0_operations);
2060: if (rc) {
2061: put_dev(dev);
2062: goto Enomem;
2063: }
2064:
2065: /* other endpoint files are available after hardware setup,
2066: * from binding to a controller.
2067: */
2068: the_device = dev;
2069: rc = 0;
2070: goto Done;
2071:
2072: Enomem:
2073: kfree(CHIP);
2074: CHIP = NULL;
]
|
| 85/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 12345
output: 39
thoughts: 19
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing `dev_new()` Refcount Initialization**
Okay, let's dive into `dev_new()`. I want to understand precisely how the reference count is being initialized within that function. This is critical for thread-safety and resource management, especially in a concurrent environment, which I know all too well. I'm looking for the exact code path, not a general overview. Are they using atomic operations? Is it a simple assignment? Are there any potential race conditions I need to identify? The devil's in the details, as always, and the refcount initialization can make or break the design. Knowing this informs how I would handle deallocation later. I'm mentally parsing the code, looking for any subtle nuances that might be relevant to my own work.
|
| 86/4 |
2026/07/31 06:31 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:dev_new]
Results: map[SourceCode: 172: static struct dev_data *dev_new (void)
173: {
174: struct dev_data *dev;
175:
176: dev = kzalloc_obj(*dev);
177: if (!dev)
178: return NULL;
179: dev->state = STATE_DEV_DISABLED;
180: refcount_set (&dev->count, 1);
181: spin_lock_init (&dev->lock);
182: INIT_LIST_HEAD (&dev->epfiles);
183: init_waitqueue_head (&dev->wait);
184: return dev;
185: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 87/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 12809
output: 48
thoughts: 214
Thoughts: **Analyzing the USB Gadget File System Initialization**
Okay, so I'm looking at how the USB gadget file system is initialized. First, `dev_new` is called. Ah, right, that's what initializes the `dev` struct and crucially sets its reference count to 1. This makes sense. Then, diving into `gadgetfs_fill_super`, I see that `dev` is initialized and immediately assigned a superblock. Now, the critical part: `gadgetfs_create_file` is called, which presumably creates the initial files within the filesystem, associated with the CHIP. If something goes wrong during file creation, `put_dev(dev)` is called to free the memory. If it is successful then the device is assigned to `the_device` and the refcount of `the_device` is 1.
So far, so good. Everything seems to be building up the core device structure. However, I need to understand when the hardware gets associated with this structure. I need to know how the Gadget driver binds to the underlying hardware. Specifically, I'm trying to determine when and how `gadgetfs_bind` is called. That's the key: it's what hooks it all up. I need to trace the driver registration and any calls to this function, so I'm going to search for all references to `gadgetfs_bind` in the code.
|
| 88/4 |
2026/07/31 06:31 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c IncludeSnippetLines:10 Name:gadgetfs_bind]
Results: map[References:[map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:gadgetfs_driver SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1748 SourceSnippet:1746: static struct usb_gadget_driver gadgetfs_driver = {
1747: .function = (char *) driver_desc,
1748: .bind = gadgetfs_bind,
1749: .unbind = gadgetfs_unbind,
1750: .setup = gadgetfs_setup,
1751: .reset = gadgetfs_disconnect,
1752: .disconnect = gadgetfs_disconnect,
1753: .suspend = gadgetfs_suspend,
1754:
1755: .driver = {
1756: .name = shortname,
1757: },
1758: };
]] TruncatedOutput:false]
|
| 89/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 13643
output: 48
thoughts: 74
Thoughts: Okay, let's see. My mental gears are turning...
**Analyzing the gadgetfs Driver Structure**
Right, so `gadgetfs_driver`. It's a `struct usb_gadget_driver`, as expected. That makes sense. Let's see... its `.bind` function is `gadgetfs_bind`, and `.unbind` is `gadgetfs_unbind`. Standard stuff so far. Now, a key question pops up: How exactly *is* this `gadgetfs_driver` actually registered with the USB subsystem? I need to find the registration point. Time to dig into the code and search for where `gadgetfs_driver` is referenced to understand the overall picture. Let's see what that search turns up.
|
| 90/4 |
2026/07/31 06:31 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c IncludeSnippetLines:10 Name:gadgetfs_driver]
Results: map[References:<nil> TruncatedOutput:false]
|
| 91/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 13942
output: 37
thoughts: 49
Thoughts: Okay, let me think this through.
**Investigating Potential Code References**
Hang on a second… it seems like `codesearch-find-references` isn't giving me the full picture. It's missing references, and the reason might be that those other locations are in the *same* file or maybe I need a more general search tool to use a different search method.
Right, I'll go with `grepper` for this. Let's start with `gadgetfs_driver` and see what that turns up. I'm curious what kind of results this will give me.
|
| 92/4 |
2026/07/31 06:31 |
tool |
grepper |
0m
Args: map[Expression:gadgetfs_driver PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:drivers/usb/gadget/legacy/inode.c=1180=ep0_fasync (int f, struct file *fd, int on)
--
drivers/usb/gadget/legacy/inode.c-1187-
drivers/usb/gadget/legacy/inode.c:1188:static struct usb_gadget_driver gadgetfs_driver;
drivers/usb/gadget/legacy/inode.c-1189-
--
drivers/usb/gadget/legacy/inode.c=1191=dev_release (struct inode *inode, struct file *fd)
--
drivers/usb/gadget/legacy/inode.c-1197- if (dev->gadget_registered) {
drivers/usb/gadget/legacy/inode.c:1198: usb_gadget_unregister_driver (&gadgetfs_driver);
drivers/usb/gadget/legacy/inode.c-1199- dev->gadget_registered = false;
--
drivers/usb/gadget/legacy/inode.c=1726=gadgetfs_suspend (struct usb_gadget *gadget)
--
drivers/usb/gadget/legacy/inode.c-1745-
drivers/usb/gadget/legacy/inode.c:1746:static struct usb_gadget_driver gadgetfs_driver = {
drivers/usb/gadget/legacy/inode.c-1747- .function = (char *) driver_desc,
--
drivers/usb/gadget/legacy/inode.c=1801=dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
--
drivers/usb/gadget/legacy/inode.c-1878- if (dev->hs_config)
drivers/usb/gadget/legacy/inode.c:1879: gadgetfs_driver.max_speed = USB_SPEED_HIGH;
drivers/usb/gadget/legacy/inode.c-1880- else
drivers/usb/gadget/legacy/inode.c:1881: gadgetfs_driver.max_speed = USB_SPEED_FULL;
drivers/usb/gadget/legacy/inode.c-1882-
drivers/usb/gadget/legacy/inode.c:1883: value = usb_gadget_register_driver(&gadgetfs_driver);
drivers/usb/gadget/legacy/inode.c-1884- if (value != 0) {
]
|
| 93/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 14785
output: 41
thoughts: 76
Thoughts: Here's my analysis of what's going on:
**Deep Dive into USB Gadget Driver Registration**
Okay, so I'm seeing that `usb_gadget_register_driver(&gadgetfs_driver)` is being called. That's the key registration function. My instinct is to trace back the call chain and understand where this is initiated, and therefore how the gadget driver is brought into operation. The immediate place to check is `dev_config`, as that's where the initial observation was made.
Alright, let me focus on lines 1801 to 1890 of `drivers/usb/gadget/legacy/inode.c`. That chunk should give me the context I need. I'm looking for the function call, any conditional logic, and relevant data structures passed around. This should allow me to understand the calling circumstances and better grasp the overall flow of the gadgetfs driver's initialization and incorporation into the system. Knowing the conditions and triggering mechanisms is paramount here to fully grok the intent of the code.
|
| 94/4 |
2026/07/31 06:31 |
tool |
read-file |
0m
Args: map[File:drivers/usb/gadget/legacy/inode.c FirstLine:1801 LineCount:90]
Results: map[Contents:1801: dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1802: {
1803: struct dev_data *dev = fd->private_data;
1804: ssize_t value, length = len;
1805: unsigned total;
1806: u32 tag;
1807: char *kbuf;
1808:
1809: spin_lock_irq(&dev->lock);
1810: if (dev->state > STATE_DEV_OPENED) {
1811: value = ep0_write(fd, buf, len, ptr);
1812: spin_unlock_irq(&dev->lock);
1813: return value;
1814: }
1815: spin_unlock_irq(&dev->lock);
1816:
1817: if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||
1818: (len > PAGE_SIZE * 4))
1819: return -EINVAL;
1820:
1821: /* we might need to change message format someday */
1822: if (copy_from_user (&tag, buf, 4))
1823: return -EFAULT;
1824: if (tag != 0)
1825: return -EINVAL;
1826: buf += 4;
1827: length -= 4;
1828:
1829: kbuf = memdup_user(buf, length);
1830: if (IS_ERR(kbuf))
1831: return PTR_ERR(kbuf);
1832:
1833: spin_lock_irq (&dev->lock);
1834: value = -EINVAL;
1835: if (dev->buf) {
1836: spin_unlock_irq(&dev->lock);
1837: kfree(kbuf);
1838: return value;
1839: }
1840: dev->buf = kbuf;
1841:
1842: /* full or low speed config */
1843: dev->config = (void *) kbuf;
1844: total = le16_to_cpu(dev->config->wTotalLength);
1845: if (!is_valid_config(dev->config, total) ||
1846: total > length - USB_DT_DEVICE_SIZE)
1847: goto fail;
1848: kbuf += total;
1849: length -= total;
1850:
1851: /* optional high speed config */
1852: if (kbuf [1] == USB_DT_CONFIG) {
1853: dev->hs_config = (void *) kbuf;
1854: total = le16_to_cpu(dev->hs_config->wTotalLength);
1855: if (!is_valid_config(dev->hs_config, total) ||
1856: total > length - USB_DT_DEVICE_SIZE)
1857: goto fail;
1858: kbuf += total;
1859: length -= total;
1860: } else {
1861: dev->hs_config = NULL;
1862: }
1863:
1864: /* could support multiple configs, using another encoding! */
1865:
1866: /* device descriptor (tweaked for paranoia) */
1867: if (length != USB_DT_DEVICE_SIZE)
1868: goto fail;
1869: dev->dev = (void *)kbuf;
1870: if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1871: || dev->dev->bDescriptorType != USB_DT_DEVICE
1872: || dev->dev->bNumConfigurations != 1)
1873: goto fail;
1874: dev->dev->bcdUSB = cpu_to_le16 (0x0200);
1875:
1876: /* triggers gadgetfs_bind(); then we can enumerate. */
1877: spin_unlock_irq (&dev->lock);
1878: if (dev->hs_config)
1879: gadgetfs_driver.max_speed = USB_SPEED_HIGH;
1880: else
1881: gadgetfs_driver.max_speed = USB_SPEED_FULL;
1882:
1883: value = usb_gadget_register_driver(&gadgetfs_driver);
1884: if (value != 0) {
1885: spin_lock_irq(&dev->lock);
1886: goto fail;
1887: } else {
1888: /* at this point "good" hardware has for the first time
1889: * let the USB the host see us. alternatively, if users
1890: * unplug/replug that will clear all the error state.
]
|
| 95/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 16518
output: 41
thoughts: 41
Thoughts: Here's my summary, as the thought process of a seasoned developer digging into USB gadget driver internals:
**Diving into `dev_config` in `inode.c`**
Okay, I need to get the full picture of `dev_config` now. My understanding is that it's crucial for how the USB gadget device is configured, and I've traced it to this point. I'm going to jump into the `drivers/usb/gadget/legacy/inode.c` file and specifically hone in on lines 1891 through 1910. That's usually where the meat of the matter lies in this kind of driver code. I'm expecting this section to illuminate the setup and potentially the subsequent handling of the `dev_config` structure, and it will hopefully show me how it interplays with other essential device configurations. Hopefully, I'll see some obvious call chains that relate to the various USB requests. This should give me the context I need to understand its relationship to the broader device enumeration process. Let's see what we've got!
|
| 96/4 |
2026/07/31 06:31 |
tool |
read-file |
0m
Args: map[File:drivers/usb/gadget/legacy/inode.c FirstLine:1891 LineCount:20]
Results: map[Contents:1891: *
1892: * note: everything running before here was guaranteed
1893: * to choke driver model style diagnostics. from here
1894: * on, they can work ... except in cleanup paths that
1895: * kick in after the ep0 descriptor is closed.
1896: */
1897: value = len;
1898: dev->gadget_registered = true;
1899: }
1900: return value;
1901:
1902: fail:
1903: dev->config = NULL;
1904: dev->hs_config = NULL;
1905: dev->dev = NULL;
1906: spin_unlock_irq (&dev->lock);
1907: pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev);
1908: kfree (dev->buf);
1909: dev->buf = NULL;
1910: return value;
]
|
| 97/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 17123
output: 38
thoughts: 766
Thoughts: **Analyzing a Potential Use-After-Free Vulnerability in `gadgetfs`**
Okay, let's break this down. I'm tracing the execution path of `usb_gadget_register_driver(&gadgetfs_driver)`. It seems like we're binding a driver to a gadget, which is pretty standard. The core calls `gadgetfs_bind(gadget, driver)`. If that succeeds, the refcount of `dev` gets incremented to 2 with `get_dev(dev)`. But, *crucially*, if `gadgetfs_bind` *fails*, it calls `gadgetfs_unbind(gadget)`.
Now, the issue arises in `gadgetfs_unbind`. It retrieves `dev` using `get_gadget_data(gadget)`. Recall that `set_gadget_data(gadget, dev)` was called at the start of `gadgetfs_bind`. In this failure scenario, since `gadgetfs_bind` failed, `get_dev(dev)` was *not* called, and the initial refcount of `dev` is still 1.
`gadgetfs_unbind` then proceeds to lock the spinlock, set the device state, destroy endpoint files, nullify the driver data for EP0, and finally, potentially free the request and, importantly, call `put_dev(dev)`. The critical point here is that `put_dev` *decrements* the refcount. And if the refcount is 1 before the `put_dev` call, then `put_dev` decrements to 0 and, yes, `kfree(data)` is called. `put_dev` frees the memory for `dev`!
But wait a minute! `the_device` still points to `dev` and, even more concerningly, `dev` is still referenced by the open file descriptor for `/dev/gadget/$CHIP`! We're talking about a classic Use-After-Free! If the gadget driver fails to bind, we're freeing the memory *while* it's potentially still in use. Any subsequent access to the `/dev/gadget/$CHIP` file, closing it, or even reading/writing, after this failure could trigger a crash or allow arbitrary code execution.
This is a red flag. I need to understand if this is intentional or a bug. I need to search for any commits or discussions related to `gadgetfs_bind` and `gadgetfs_unbind` in the kernel mailing list and git logs. Let's see if there are any `MessageRegexps` for "gadgetfs" or even things around "inode.c" that could explain this. The goal now is to determine if this is a known issue, a deliberate design choice with some other safeguard, or a genuine vulnerability that needs fixing.
|
| 98/4 |
2026/07/31 06:31 |
tool |
git-log |
0m
Args: map[MessageRegexps:[gadgetfs] PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:57db9d428ba5 convert gadgetfs
b65e3b11e923 gadgetfs: switch to simple_remove_by_name()
bad356bb50e6 functionfs, gadgetfs: use simple_recursive_removal()
fc85c59b85d1 usb: gadgetfs: return USB_GADGET_DELAYED_STATUS from setup()
e07fec475cc8 usb: gadgetfs: Fix ep_read_iter to handle ITER_UBUF
d18dcfe9860e USB: gadgetfs: Fix race between mounting and unmounting
04cb742d4d8f gadgetfs: ep_io - wait until IRQ finishes
87bed3d7d26c usb: gadget: Fix memleak in gadgetfs_fill_super
e5d82a7360d1 vfs: Convert gadgetfs to use the new mount API
520b72fc64de USB: gadgetfs: Fix crash caused by inadequate synchronization
]
|
| 99/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 18792
output: 25
thoughts: 36
Thoughts: Here's my summary, as the thought process you described:
**Analyzing Commit 520b72fc64de: USB Gadgetfs Synchronization Issue**
Okay, let's pull up commit `520b72fc64de`. I remember seeing that one...it was related to the gadgetfs implementation and a crash, right? Yes, that's it - "USB: gadgetfs: Fix crash caused by inadequate synchronization". I need to refresh my memory on the specifics, so let's display the diff. I bet it addresses a race condition. I'm curious to see where the locking was lacking, and what mechanism they used to correct it. My initial guess would be a missing spinlock protection in either the device's control path or the transaction handling. Should be interesting to see if I'm right.
|
| 100/4 |
2026/07/31 06:31 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 520b72fc64debf8a86c3853b8e486aa5982188f0
Author: Alan Stern <stern@rowland.harvard.edu>
Date: Thu Sep 21 13:23:58 2017 -0400
USB: gadgetfs: Fix crash caused by inadequate synchronization
The gadgetfs driver (drivers/usb/gadget/legacy/inode.c) was written
before the UDC and composite frameworks were adopted; it is a legacy
driver. As such, it expects that once bound to a UDC controller, it
will not be unbound until it unregisters itself.
However, the UDC framework does unbind function drivers while they are
still registered. When this happens, it can cause the gadgetfs driver
to misbehave or crash. For example, userspace can cause a crash by
opening the device file and doing an ioctl call before setting up a
configuration (found by Andrey Konovalov using the syzkaller fuzzer).
This patch adds checks and synchronization to prevent these bad
behaviors. It adds a udc_usage counter that the driver increments at
times when it is using a gadget interface without holding the private
spinlock. The unbind routine waits for this counter to go to 0 before
returning, thereby ensuring that the UDC is no longer in use.
The patch also adds a check in the dev_ioctl() routine to make sure
the driver is bound to a UDC before dereferencing the gadget pointer,
and it makes destroy_ep_files() synchronize with the endpoint I/O
routines, to prevent the user from accessing an endpoint data
structure after it has been removed.
Signed-off-by: Alan Stern <stern@rowland.harvard.edu>
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Tested-by: Andrey Konovalov <andreyknvl@google.com>
CC: <stable@vger.kernel.org>
Acked-by: Felipe Balbi <felipe.balbi@linux.intel.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 956b3dc7c3a4..5c28bee327e1 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -28,7 +28,7 @@
#include <linux/aio.h>
#include <linux/uio.h>
#include <linux/refcount.h>
-
+#include <linux/delay.h>
#include <linux/device.h>
#include <linux/moduleparam.h>
@@ -116,6 +116,7 @@ enum ep0_state {
struct dev_data {
spinlock_t lock;
refcount_t count;
+ int udc_usage;
enum ep0_state state; /* P: lock */
struct usb_gadgetfs_event event [N_EVENT];
unsigned ev_next;
@@ -513,9 +514,9 @@ static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
INIT_WORK(&priv->work, ep_user_copy_worker);
schedule_work(&priv->work);
}
- spin_unlock(&epdata->dev->lock);
usb_ep_free_request(ep, req);
+ spin_unlock(&epdata->dev->lock);
put_ep(epdata);
}
@@ -939,9 +940,11 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
struct usb_request *req = dev->req;
if ((retval = setup_req (ep, req, 0)) == 0) {
+ ++dev->udc_usage;
spin_unlock_irq (&dev->lock);
retval = usb_ep_queue (ep, req, GFP_KERNEL);
spin_lock_irq (&dev->lock);
+ --dev->udc_usage;
}
dev->state = STATE_DEV_CONNECTED;
@@ -1134,6 +1137,7 @@ ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
retval = setup_req (dev->gadget->ep0, dev->req, len);
if (retval == 0) {
dev->state = STATE_DEV_CONNECTED;
+ ++dev->udc_usage;
spin_unlock_irq (&dev->lock);
if (copy_from_user (dev->req->buf, buf, len))
retval = -EFAULT;
@@ -1145,6 +1149,7 @@ ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
GFP_KERNEL);
}
spin_lock_irq(&dev->lock);
+ --dev->udc_usage;
if (retval < 0) {
clean_req (dev->gadget->ep0, dev->req);
} else
@@ -1246,9 +1251,21 @@ static long dev_ioctl (struct file *fd, unsigned code, unsigned long value)
struct usb_gadget *gadget = dev->gadget;
long ret = -ENOTTY;
- if (gadget->ops->ioctl)
+ spin_lock_irq(&dev->lock);
+ if (dev->state == STATE_DEV_OPENED ||
+ dev->state == STATE_DEV_UNBOUND) {
+ /* Not bound to a UDC */
+ } else if (gadget->ops->ioctl) {
+ ++dev->udc_usage;
+ spin_unlock_irq(&dev->lock);
+
ret = gadget->ops->ioctl (gadget, code, value);
+ spin_lock_irq(&dev->lock);
+ --dev->udc_usage;
+ }
+ spin_unlock_irq(&dev->lock);
+
return ret;
}
@@ -1466,10 +1483,12 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
if (value < 0)
break;
+ ++dev->udc_usage;
spin_unlock (&dev->lock);
value = usb_ep_queue (gadget->ep0, dev->req,
GFP_KERNEL);
spin_lock (&dev->lock);
+ --dev->udc_usage;
if (value < 0) {
clean_req (gadget->ep0, dev->req);
break;
@@ -1493,8 +1512,12 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
req->length = value;
req->zero = value < w_length;
+ ++dev->udc_usage;
spin_unlock (&dev->lock);
value = usb_ep_queue (gadget->ep0, req, GFP_KERNEL);
+ spin_lock(&dev->lock);
+ --dev->udc_usage;
+ spin_unlock(&dev->lock);
if (value < 0) {
DBG (dev, "ep_queue --> %d\n", value);
req->status = 0;
@@ -1521,21 +1544,24 @@ static void destroy_ep_files (struct dev_data *dev)
/* break link to FS */
ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles);
list_del_init (&ep->epfiles);
+ spin_unlock_irq (&dev->lock);
+
dentry = ep->dentry;
ep->dentry = NULL;
parent = d_inode(dentry->d_parent);
/* break link to controller */
+ mutex_lock(&ep->lock);
if (ep->state == STATE_EP_ENABLED)
(void) usb_ep_disable (ep->ep);
ep->state = STATE_EP_UNBOUND;
usb_ep_free_request (ep->ep, ep->req);
ep->ep = NULL;
+ mutex_unlock(&ep->lock);
+
wake_up (&ep->wait);
put_ep (ep);
- spin_unlock_irq (&dev->lock);
-
/* break link to dcache */
inode_lock(parent);
d_delete (dentry);
@@ -1606,6 +1632,11 @@ gadgetfs_unbind (struct usb_gadget *gadget)
spin_lock_irq (&dev->lock);
dev->state = STATE_DEV_UNBOUND;
+ while (dev->udc_usage > 0) {
+ spin_unlock_irq(&dev->lock);
+ usleep_range(1000, 2000);
+ spin_lock_irq(&dev->lock);
+ }
spin_unlock_irq (&dev->lock);
destroy_ep_files (dev);
]
|
| 101/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 21494
output: 39
thoughts: 382
Thoughts: **Analyzing a Potential Reference Count Issue in `gadgetfs_bind`**
Okay, let's re-examine this question. The core of the concern is whether `gadgetfs_bind` in `drivers/usb/gadget/legacy/inode.c` correctly handles failures. Specifically, is there a good reason it calls `gadgetfs_unbind` on failure, instead of just cleaning up manually? If it calls `gadgetfs_unbind` on failure, it seems like we might have a problem with reference counting. `gadgetfs_unbind` has a `put_dev` call. But if we haven't successfully *acquired* a reference (via `get_dev`), how can we release it? It seems off.
Let's dissect the failure path. If `gadgetfs_bind` fails, it calls `gadgetfs_unbind(gadget)`. Now, what happens inside that function?
`gadgetfs_unbind` first retrieves `struct dev_data *dev` using `get_gadget_data (gadget)`. Ah, right, I remember now that `get_gadget_data(gadget)` does return `dev`, because that was set previously via `set_gadget_data(gadget, dev)`. Okay, after some cleanup, it calls `put_dev(dev)`.
Wait a minute... why is it calling `gadgetfs_unbind` at all? Is there a legitimate reason for this behavior, or is it a design flaw? The key issue here is that `get_dev` isn't called until `gadgetfs_bind` succeeds! Therefore, calling `gadgetfs_unbind` in case of failure seems problematic, because it effectively tries to release a reference (`put_dev`) that has not been acquired, leading to a possible double-free or incorrect reference counting.
Could this be a bug? I think we should investigate other places where `get_dev` is called. For good measure, let's check `dev_release` in `drivers/usb/gadget/legacy/inode.c`. I'm starting to think we have a real problem here.
|
| 102/4 |
2026/07/31 06:31 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:dev_release]
Results: map[SourceCode:1190: static int
1191: dev_release (struct inode *inode, struct file *fd)
1192: {
1193: struct dev_data *dev = fd->private_data;
1194:
1195: /* closing ep0 === shutdown all */
1196:
1197: if (dev->gadget_registered) {
1198: usb_gadget_unregister_driver (&gadgetfs_driver);
1199: dev->gadget_registered = false;
1200: }
1201:
1202: /* at this point "good" hardware has disconnected the
1203: * device from USB; the host won't see it any more.
1204: * alternatively, all host requests will time out.
1205: */
1206:
1207: kfree (dev->buf);
1208: dev->buf = NULL;
1209:
1210: /* other endpoints were all decoupled from this device */
1211: spin_lock_irq(&dev->lock);
1212: dev->state = STATE_DEV_DISABLED;
1213: spin_unlock_irq(&dev->lock);
1214:
1215: put_dev (dev);
1216: return 0;
1217: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 103/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 22784
output: 39
thoughts: 108
Thoughts: **Tracing the Refcount of `dev`**
Okay, let's get down to brass tacks and track that `dev` refcount. My experience tells me these details matter when debugging kernel modules, so let's be methodical.
First, when `/dev/gadget/$CHIP` is mounted, `gadgetfs_fill_super` gets the call. That's the entry point. It then calls `dev_new()`. I know that function; it's a common pattern to allocate the device structure. And as I suspected, this call increments the refcount, setting `dev->count` to 1. Smart. This initialization tells me the refcount starts at 1. `the_device` gets assigned `dev` at this stage.
Next up, when we open `/dev/gadget/$CHIP`, `dev_open` is executed. Now, I need to understand what happens inside `dev_open` with regards to that `dev->count`, and where it's modified. Let's delve into that function...
|
| 104/4 |
2026/07/31 06:31 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:dev_open]
Results: map[SourceCode: 182: /**
183: * dev_open() - prepare an interface for use
184: * @dev: device to open
185: * @extack: netlink extended ack
186: *
187: * Takes a device from down to up state. The device's private open
188: * function is invoked and then the multicast lists are loaded. Finally
189: * the device is moved into the up state and a %NETDEV_UP message is
190: * sent to the netdev notifier chain.
191: *
192: * Calling this function on an active interface is a nop. On a failure
193: * a negative errno code is returned.
194: *
195: * Return: 0 on success, -errno on failure.
196: */
197: int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
198: {
199: int ret;
200:
201: netdev_lock_ops(dev);
202: ret = netif_open(dev, extack);
203: netdev_unlock_ops(dev);
204:
205: return ret;
206: }
SourceFile:net/core/dev_api.c]
|
| 105/4 |
2026/07/31 06:31 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 23548
output: 36
thoughts: 57
Thoughts: Here's my summary, as the expert:
**Navigating the Linux Kernel: A USB Gadget Dive**
Okay, so I was looking at `dev_open`, and initially thought it was the one we needed in `net/core/dev_api.c`. But that's not quite right for this particular USB gadget interaction. My instincts told me to look deeper, and that's when it dawned on me—the `inode.c` file within the USB gadget legacy driver likely holds the key. Time to quickly confirm this suspicion. Let's use `grepper` to pinpoint that specific implementation of `dev_open` within the `drivers/usb/gadget/legacy/inode.c` path. That should give me the exact function definition I'm after, and allow me to proceed with debugging or understanding the relevant code. This is definitely the right approach to zero in on the relevant driver.
|
| 106/4 |
2026/07/31 06:32 |
tool |
grepper |
0m
Args: map[Expression:\.open.*= PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:drivers/usb/gadget/legacy/inode.c=702=static const struct file_operations ep_io_operations = {
--
drivers/usb/gadget/legacy/inode.c-704-
drivers/usb/gadget/legacy/inode.c:705: .open = ep_open,
drivers/usb/gadget/legacy/inode.c-706- .release = ep_release,
--
drivers/usb/gadget/legacy/inode.c=1931=static const struct file_operations ep0_operations = {
drivers/usb/gadget/legacy/inode.c-1932-
drivers/usb/gadget/legacy/inode.c:1933: .open = gadget_dev_open,
drivers/usb/gadget/legacy/inode.c-1934- .read = ep0_read,
]
|
| 107/4 |
2026/07/31 06:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24064
output: 42
thoughts: 26
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience and written in the first person:
**Analyzing the Function Call: `gadget_dev_open`**
Okay, so the code's hit `gadget_dev_open`. That's the entry point, the critical function we're starting with. Time to dissect what's going on here. I need to understand what this function is doing, what its inputs are, and what its outputs will be. Specifically, how it's interacting with the underlying device drivers and the rest of the gadget subsystem. Let's dig into the details of the implementation. I'm looking for where it handles the initial setup, resource allocation, and any potential security checks or error conditions that might be present. Essentially, a deep dive into the initial configuration procedures. I will trace the control flows to look for how this function gets invoked and where the data it handles comes from.
|
| 108/4 |
2026/07/31 06:32 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadget_dev_open]
Results: map[SourceCode:1913: static int
1914: gadget_dev_open (struct inode *inode, struct file *fd)
1915: {
1916: struct dev_data *dev = inode->i_private;
1917: int value = -EBUSY;
1918:
1919: spin_lock_irq(&dev->lock);
1920: if (dev->state == STATE_DEV_DISABLED) {
1921: dev->ev_next = 0;
1922: dev->state = STATE_DEV_OPENED;
1923: fd->private_data = dev;
1924: get_dev (dev);
1925: value = 0;
1926: }
1927: spin_unlock_irq(&dev->lock);
1928: return value;
1929: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 109/4 |
2026/07/31 06:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 24606
output: 41
thoughts: 3149
Thoughts: **Analysis of `gadgetfs` Driver's Reference Counting and UAF Vulnerability**
Okay, let's break this down. My initial hunch about a reference counting issue in the `gadgetfs` driver seems correct. I've traced the `dev` struct's reference count through the `gadgetfs_fill_super`, `gadget_dev_open`, `dev_config`, `gadgetfs_bind`, and `gadgetfs_kill_sb` functions. I think I've found a critical flaw that leads to a Use-After-Free (UAF) condition.
Here's the problem: When `gadgetfs_bind` fails, specifically at the `enomem` label after an unsuccessful `usb_ep_alloc_request` or `activate_ep_files`, it calls `gadgetfs_unbind`. `gadgetfs_unbind` *does* clean up, but crucially, it includes a `put_dev(dev)` call that *decrements* the refcount on `dev`. However, `get_dev` is only called at the *end* of `gadgetfs_bind` when it succeeds, so, at `enomem`, it's decremented once more than it should.
This leads to `dev` being freed prematurely when the file descriptor is closed. The refcount is unbalanced. Then, later, when the filesystem is unmounted, `gadgetfs_kill_sb` attempts to `put_dev(the_device)`, and this is where the UAF or double free occurs, because `the_device` now points to memory that's already been freed. I confirmed this by tracing both successful and unsuccessful `gadgetfs_bind` scenarios.
I also considered the case of an `-ENODEV` error in `gadgetfs_bind` if the chip name check fails. In that case, the refcount is balanced; the problem *only* occurs if the driver attempts to unbind after a memory allocation failure.
I analyzed why `gadgetfs_unbind` is called when `gadgetfs_bind` fails, trying to find alternatives for cleanup. I found that `gadgetfs_unbind` sets the state of the gadget to `STATE_DEV_UNBOUND`, destroys endpoint files, clears the driver data in the USB gadget, frees any allocated requests, and crucially, calls `put_dev(dev)`.
If we *did* manual cleanup, when `usb_ep_alloc_request` fails, we just need to NULL out the `gadget` struct related data, and be done with it. Similarly, we would not need to call `gadgetfs_unbind` if `activate_ep_files` fails, but instead manually free the resources. I'll need to further analyze `activate_ep_files` to understand it fully. It seems that `gadgetfs_unbind` is too eager to decrement the refcount. I'll need to investigate where this logic originated from in the commit history to see if there was some other reason this was coded this way.
|
| 110/4 |
2026/07/31 06:32 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:activate_ep_files]
Results: map[SourceCode:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
1610: data->dev = dev;
1611: get_dev (dev);
1612:
1613: data->ep = ep;
1614: ep->driver_data = data;
1615:
1616: data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1617: if (!data->req)
1618: goto enomem1;
1619:
1620: err = gadgetfs_create_file (dev->sb, data->name,
1621: data, &ep_io_operations);
1622: if (err)
1623: goto enomem2;
1624: list_add_tail (&data->epfiles, &dev->epfiles);
1625: }
1626: return 0;
1627:
1628: enomem2:
1629: usb_ep_free_request (ep, data->req);
1630: enomem1:
1631: put_dev (dev);
1632: kfree (data);
1633: enomem0:
1634: DBG (dev, "%s enomem\n", __func__);
1635: destroy_ep_files (dev);
1636: return -ENOMEM;
1637: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 111/4 |
2026/07/31 06:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 29111
output: 41
thoughts: 226
Thoughts: **Analyzing Endpoint File Activation and Deactivation**
Okay, so I'm digging into this code, specifically around endpoint file handling. I just realized something significant: `activate_ep_files` *already* calls `destroy_ep_files(dev)` in the event of a failure. That's good; it means we're probably cleaning up correctly, or at least, should be.
Let's quickly confirm what happens when `activate_ep_files` hits an error. I'm seeing the error paths, `enomem0`, `enomem1`, and `enomem2`, all result in cleanup. Specifically, `enomem0` calls `destroy_ep_files(dev)` directly before returning `-ENOMEM`. That's the key.
Let me now refresh my understanding of how `destroy_ep_files(dev)` itself works, to make sure this whole sequence is sound. It looks like `destroy_ep_files` calls `put_ep(ep)` which is most likely responsible for freeing the individual endpoint resources.
Okay, this all makes sense now.
|
| 112/4 |
2026/07/31 06:32 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:destroy_ep_files]
Results: map[SourceCode:1554: static void destroy_ep_files (struct dev_data *dev)
1555: {
1556: DBG (dev, "%s %d\n", __func__, dev->state);
1557:
1558: /* dev->state must prevent interference */
1559: spin_lock_irq (&dev->lock);
1560: while (!list_empty(&dev->epfiles)) {
1561: struct ep_data *ep;
1562:
1563: /* break link to FS */
1564: ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles);
1565: list_del_init (&ep->epfiles);
1566: spin_unlock_irq (&dev->lock);
1567:
1568: /* break link to controller */
1569: mutex_lock(&ep->lock);
1570: if (ep->state == STATE_EP_ENABLED)
1571: (void) usb_ep_disable (ep->ep);
1572: ep->state = STATE_EP_UNBOUND;
1573: usb_ep_free_request (ep->ep, ep->req);
1574: ep->ep = NULL;
1575: mutex_unlock(&ep->lock);
1576:
1577: wake_up (&ep->wait);
1578:
1579: /* break link to dcache */
1580: simple_remove_by_name(dev->sb->s_root, ep->name, NULL);
1581:
1582: put_ep (ep);
1583:
1584: spin_lock_irq (&dev->lock);
1585: }
1586: spin_unlock_irq (&dev->lock);
1587: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 113/4 |
2026/07/31 06:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 30156
output: 39
thoughts: 29
Thoughts: Here's my take on the thought process, as requested:
**Deconstructing the `destroy_ep_files` Function**
Okay, hold on a second! I just realized something significant. This `destroy_ep_files` function, the one I'm trying to optimize, actually calls `put_ep(ep)` at some point. That connection wasn't immediately obvious, but it's crucial for understanding the whole picture. So, it's not simply about *removing* files, there's an operation being performed that relates to something being "put." I need to fully understand `put_ep` before I can truly grasp the implications of `destroy_ep_files`. Let's shift gears and dive into the implementation of `put_ep`.
|
| 114/4 |
2026/07/31 06:32 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:put_ep]
Results: map[SourceCode: 217: static void put_ep (struct ep_data *data)
218: {
219: if (likely (!refcount_dec_and_test (&data->count)))
220: return;
221: put_dev (data->dev);
222: /* needs no more cleanup */
223: BUG_ON (!list_empty (&data->epfiles));
224: BUG_ON (waitqueue_active (&data->wait));
225: kfree (data);
226: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 115/4 |
2026/07/31 06:32 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 30570
output: 34
thoughts: 1475
Thoughts: **Analysis of Device Reference Counting in gadgetfs_bind and gadgetfs_unbind**
Okay, let's break this down. My initial thought process was: I see `put_ep` calling `put_dev`. Then in `activate_ep_files`, I notice a `get_dev` being called for each endpoint file successfully created. So, the cleanup via `destroy_ep_files` seems correct, releasing the resources acquired by `activate_ep_files` if it fails. That felt solid.
But then, I hit a snag. If `activate_ep_files` fails, it returns `-ENOMEM` to `gadgetfs_bind`, which then calls `gadgetfs_unbind`. Inside `gadgetfs_unbind`, `destroy_ep_files` is called, but it's redundant because `activate_ep_files` already performed the cleanup and cleared `dev->epfiles`. Fine, that's harmlessly redundant. It frees the allocated request and calls `put_dev(dev)`. And that's where the problem arises: `get_dev(dev)` was *never* called in `gadgetfs_bind` before.
Looking closer at `gadgetfs_bind`, it's clear: `get_dev(dev)` is called *after* a successful `activate_ep_files`. In the error path, however, there's no corresponding `get_dev` before the call to `gadgetfs_unbind`. I need to double-check, in case there was a logic error. So, if `usb_ep_alloc_request` fails, or if `activate_ep_files` fails, the code jumps to `enomem` and calls `gadgetfs_unbind`, then calls `put_dev(dev)` without a corresponding `get_dev`.
This is the key point: in either failure scenario, the device's reference count is decremented via `put_dev` without an initial increment via `get_dev`. This is a definite leak of a reference. I'm seeing a clear and consistent pattern of an extra `put_dev` call.
Now, I'm trying to understand *why* this was done this way. Is there a reason why `gadgetfs_bind` uses `gadgetfs_unbind` for error handling instead of direct cleanup? Is there a reason why `get_dev` wasn't called earlier? Is it legacy code or a logical flaw? Now, the debugging begins!
I need to examine the history of this code. I need to use `git log` and `git show` to trace the evolution of `gadgetfs_bind` and `gadgetfs_unbind`, starting from the initial commit of `inode.c`. That should help me understand the rationale behind this design. Perhaps an earlier version had different logic. Maybe the `get_dev` call was introduced later, and the error path wasn't updated accordingly. I'm going to look for a past mistake!
|
| 116/4 |
2026/07/31 06:32 |
tool |
git-log |
10m
Error:
Args: map[CodeRegexp:gadgetfs_bind Count:1 Since:20 years]
Results:
|
| 117/4 |
2026/07/31 06:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 32757
output: 37
thoughts: 107
Thoughts: **Troubleshooting a Git Log Timeout**
Okay, so the `git log` command timed out again. I knew it, I should have anticipated this. It's almost certainly because the search scope was too broad, or we're looking way too far back in the commit history. Let's narrow this down. I need to be more precise in my command. I'm going to start by specifying a more focused `PathPrefix`, something like `"drivers/usb/gadget/legacy/inode.c"` or just `"drivers/usb/gadget/inode.c"`. That should significantly reduce the amount of data the command has to sift through.
Wait a second, before I do that, let me try a slightly different angle. Perhaps I should go right to the source. Instead of just filtering the log, I'm going to pull the initial commit for `drivers/usb/gadget/inode.c` specifically. Let's use `git show` on that initial commit, which I believe is `1da177e4c3f4`. Seeing the very beginning might give me the context I need and avoid a lengthy log search altogether.
|
| 118/4 |
2026/07/31 06:42 |
tool |
git-show |
0m
Args: map[Commit:1da177e4c3f4:drivers/usb/gadget/inode.c]
Results: map[Output:
Full output is too long, showing 1000 out of 2110 lines.
[/*
* inode.c -- user mode filesystem api for usb gadget controllers
*
* Copyright (C) 2003-2004 David Brownell
* Copyright (C) 2003 Agilent Technologies
*
* 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
*/
// #define DEBUG /* data to help fault diagnosis */
// #define VERBOSE /* extra debug messages (success too) */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/uts.h>
#include <linux/wait.h>
#include <linux/compiler.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/moduleparam.h>
#include <linux/usb_gadgetfs.h>
#include <linux/usb_gadget.h>
/*
* The gadgetfs API maps each endpoint to a file descriptor so that you
* can use standard synchronous read/write calls for I/O. There's some
* O_NONBLOCK and O_ASYNC/FASYNC style i/o support. Example usermode
* drivers show how this works in practice. You can also use AIO to
* eliminate I/O gaps between requests, to help when streaming data.
*
* Key parts that must be USB-specific are protocols defining how the
* read/write operations relate to the hardware state machines. There
* are two types of files. One type is for the device, implementing ep0.
* The other type is for each IN or OUT endpoint. In both cases, the
* user mode driver must configure the hardware before using it.
*
* - First, dev_config() is called when /dev/gadget/$CHIP is configured
* (by writing configuration and device descriptors). Afterwards it
* may serve as a source of device events, used to handle all control
* requests other than basic enumeration.
*
* - Then either immediately, or after a SET_CONFIGURATION control request,
* ep_config() is called when each /dev/gadget/ep* file is configured
* (by writing endpoint descriptors). Afterwards these files are used
* to write() IN data or to read() OUT data. To halt the endpoint, a
* "wrong direction" request is issued (like reading an IN endpoint).
*
* Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
* not possible on all hardware. For example, precise fault handling with
* respect to data left in endpoint fifos after aborted operations; or
* selective clearing of endpoint halts, to implement SET_INTERFACE.
*/
#define DRIVER_DESC "USB Gadget filesystem"
#define DRIVER_VERSION "24 Aug 2004"
static const char driver_desc [] = DRIVER_DESC;
static const char shortname [] = "gadgetfs";
MODULE_DESCRIPTION (DRIVER_DESC);
MODULE_AUTHOR ("David Brownell");
MODULE_LICENSE ("GPL");
/*----------------------------------------------------------------------*/
#define GADGETFS_MAGIC 0xaee71ee7
#define DMA_ADDR_INVALID (~(dma_addr_t)0)
/* /dev/gadget/$CHIP represents ep0 and the whole device */
enum ep0_state {
/* DISBLED is the initial state.
*/
STATE_DEV_DISABLED = 0,
/* Only one open() of /dev/gadget/$CHIP; only one file tracks
* ep0/device i/o modes and binding to the controller. Driver
* must always write descriptors to initialize the device, then
* the device becomes UNCONNECTED until enumeration.
*/
STATE_OPENED,
/* From then on, ep0 fd is in either of two basic modes:
* - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
* - SETUP: read/write will transfer control data and succeed;
* or if "wrong direction", performs protocol stall
*/
STATE_UNCONNECTED,
STATE_CONNECTED,
STATE_SETUP,
/* UNBOUND means the driver closed ep0, so the device won't be
* accessible again (DEV_DISABLED) until all fds are closed.
*/
STATE_DEV_UNBOUND,
};
/* enough for the whole queue: most events invalidate others */
#define N_EVENT 5
struct dev_data {
spinlock_t lock;
atomic_t count;
enum ep0_state state;
struct usb_gadgetfs_event event [N_EVENT];
unsigned ev_next;
struct fasync_struct *fasync;
u8 current_config;
/* drivers reading ep0 MUST handle control requests (SETUP)
* reported that way; else the host will time out.
*/
unsigned usermode_setup : 1,
setup_in : 1,
setup_can_stall : 1,
setup_out_ready : 1,
setup_out_error : 1,
setup_abort : 1;
/* the rest is basically write-once */
struct usb_config_descriptor *config, *hs_config;
struct usb_device_descriptor *dev;
struct usb_request *req;
struct usb_gadget *gadget;
struct list_head epfiles;
void *buf;
wait_queue_head_t wait;
struct super_block *sb;
struct dentry *dentry;
/* except this scratch i/o buffer for ep0 */
u8 rbuf [256];
};
static inline void get_dev (struct dev_data *data)
{
atomic_inc (&data->count);
}
static void put_dev (struct dev_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
/* needs no more cleanup */
BUG_ON (waitqueue_active (&data->wait));
kfree (data);
}
static struct dev_data *dev_new (void)
{
struct dev_data *dev;
dev = kmalloc (sizeof *dev, GFP_KERNEL);
if (!dev)
return NULL;
memset (dev, 0, sizeof *dev);
dev->state = STATE_DEV_DISABLED;
atomic_set (&dev->count, 1);
spin_lock_init (&dev->lock);
INIT_LIST_HEAD (&dev->epfiles);
init_waitqueue_head (&dev->wait);
return dev;
}
/*----------------------------------------------------------------------*/
/* other /dev/gadget/$ENDPOINT files represent endpoints */
enum ep_state {
STATE_EP_DISABLED = 0,
STATE_EP_READY,
STATE_EP_DEFER_ENABLE,
STATE_EP_ENABLED,
STATE_EP_UNBOUND,
};
struct ep_data {
struct semaphore lock;
enum ep_state state;
atomic_t count;
struct dev_data *dev;
/* must hold dev->lock before accessing ep or req */
struct usb_ep *ep;
struct usb_request *req;
ssize_t status;
char name [16];
struct usb_endpoint_descriptor desc, hs_desc;
struct list_head epfiles;
wait_queue_head_t wait;
struct dentry *dentry;
struct inode *inode;
};
static inline void get_ep (struct ep_data *data)
{
atomic_inc (&data->count);
}
static void put_ep (struct ep_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
put_dev (data->dev);
/* needs no more cleanup */
BUG_ON (!list_empty (&data->epfiles));
BUG_ON (waitqueue_active (&data->wait));
BUG_ON (down_trylock (&data->lock) != 0);
kfree (data);
}
/*----------------------------------------------------------------------*/
/* most "how to use the hardware" policy choices are in userspace:
* mapping endpoint roles (which the driver needs) to the capabilities
* which the usb controller has. most of those capabilities are exposed
* implicitly, starting with the driver name and then endpoint names.
*/
static const char *CHIP;
/*----------------------------------------------------------------------*/
/* NOTE: don't use dev_printk calls before binding to the gadget
* at the end of ep0 configuration, or after unbind.
*/
/* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
#define xprintk(d,level,fmt,args...) \
printk(level "%s: " fmt , shortname , ## args)
#ifdef DEBUG
#define DBG(dev,fmt,args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE
#define VDEBUG DBG
#else
#define VDEBUG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev,fmt,args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define WARN(dev,fmt,args...) \
xprintk(dev , KERN_WARNING , fmt , ## args)
#define INFO(dev,fmt,args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*----------------------------------------------------------------------*/
/* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
*
* After opening, configure non-control endpoints. Then use normal
* stream read() and write() requests; and maybe ioctl() to get more
* precise FIFO status when recovering from cancelation.
*/
static void epio_complete (struct usb_ep *ep, struct usb_request *req)
{
struct ep_data *epdata = ep->driver_data;
if (!req->context)
return;
if (req->status)
epdata->status = req->status;
else
epdata->status = req->actual;
complete ((struct completion *)req->context);
}
/* tasklock endpoint, returning when it's connected.
* still need dev->lock to use epdata->ep.
*/
static int
get_ready_ep (unsigned f_flags, struct ep_data *epdata)
{
int val;
if (f_flags & O_NONBLOCK) {
if (down_trylock (&epdata->lock) != 0)
goto nonblock;
if (epdata->state != STATE_EP_ENABLED) {
up (&epdata->lock);
nonblock:
val = -EAGAIN;
} else
val = 0;
return val;
}
if ((val = down_interruptible (&epdata->lock)) < 0)
return val;
newstate:
switch (epdata->state) {
case STATE_EP_ENABLED:
break;
case STATE_EP_DEFER_ENABLE:
DBG (epdata->dev, "%s wait for host\n", epdata->name);
if ((val = wait_event_interruptible (epdata->wait,
epdata->state != STATE_EP_DEFER_ENABLE
|| epdata->dev->state == STATE_DEV_UNBOUND
)) < 0)
goto fail;
goto newstate;
// case STATE_EP_DISABLED: /* "can't happen" */
// case STATE_EP_READY: /* "can't happen" */
default: /* error! */
pr_debug ("%s: ep %p not available, state %d\n",
shortname, epdata, epdata->state);
// FALLTHROUGH
case STATE_EP_UNBOUND: /* clean disconnect */
val = -ENODEV;
fail:
up (&epdata->lock);
}
return val;
}
static ssize_t
ep_io (struct ep_data *epdata, void *buf, unsigned len)
{
DECLARE_COMPLETION (done);
int value;
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
struct usb_request *req = epdata->req;
req->context = &done;
req->complete = epio_complete;
req->buf = buf;
req->length = len;
value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
} else
value = -ENODEV;
spin_unlock_irq (&epdata->dev->lock);
if (likely (value == 0)) {
value = wait_event_interruptible (done.wait, done.done);
if (value != 0) {
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
DBG (epdata->dev, "%s i/o interrupted\n",
epdata->name);
usb_ep_dequeue (epdata->ep, epdata->req);
spin_unlock_irq (&epdata->dev->lock);
wait_event (done.wait, done.done);
if (epdata->status == -ECONNRESET)
epdata->status = -EINTR;
} else {
spin_unlock_irq (&epdata->dev->lock);
DBG (epdata->dev, "endpoint gone\n");
epdata->status = -ENODEV;
}
}
return epdata->status;
}
return value;
}
/* handle a synchronous OUT bulk/intr/iso transfer */
static ssize_t
ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (data->desc.bEndpointAddress & USB_DIR_IN) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (unlikely (!kbuf))
goto free1;
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s read %d OUT, status %d\n",
data->name, len, value);
if (value >= 0 && copy_to_user (buf, kbuf, value))
value = -EFAULT;
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
/* handle a synchronous IN bulk/intr/iso transfer */
static ssize_t
ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (!(data->desc.bEndpointAddress & USB_DIR_IN)) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (!kbuf)
goto free1;
if (copy_from_user (kbuf, buf, len)) {
value = -EFAULT;
goto free1;
}
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s write %d IN, status %d\n",
data->name, len, value);
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
static int
ep_release (struct inode *inode, struct file *fd)
{
struct ep_data *data = fd->private_data;
/* clean up if this can be reopened */
if (data->state != STATE_EP_UNBOUND) {
data->state = STATE_EP_DISABLED;
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
put_ep (data);
return 0;
}
static int ep_ioctl (struct inode *inode, struct file *fd,
unsigned code, unsigned long value)
{
struct ep_data *data = fd->private_data;
int status;
if ((status = get_ready_ep (fd->f_flags, data)) < 0)
return status;
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL)) {
switch (code) {
case GADGETFS_FIFO_STATUS:
status = usb_ep_fifo_status (data->ep);
break;
case GADGETFS_FIFO_FLUSH:
usb_ep_fifo_flush (data->ep);
break;
case GADGETFS_CLEAR_HALT:
status = usb_ep_clear_halt (data->ep);
break;
default:
status = -ENOTTY;
}
} else
status = -ENODEV;
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return status;
}
/*----------------------------------------------------------------------*/
/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
struct kiocb_priv {
struct usb_request *req;
struct ep_data *epdata;
void *buf;
char __user *ubuf;
unsigned actual;
};
static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e)
{
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata;
int value;
local_irq_disable();
epdata = priv->epdata;
// spin_lock(&epdata->dev->lock);
kiocbSetCancelled(iocb);
if (likely(epdata && epdata->ep && priv->req))
value = usb_ep_dequeue (epdata->ep, priv->req);
else
value = -EINVAL;
// spin_unlock(&epdata->dev->lock);
local_irq_enable();
aio_put_req(iocb);
return value;
}
static ssize_t ep_aio_read_retry(struct kiocb *iocb)
{
struct kiocb_priv *priv = iocb->private;
ssize_t status = priv->actual;
/* we "retry" to get the right mm context for this: */
status = copy_to_user(priv->ubuf, priv->buf, priv->actual);
if (unlikely(0 != status))
status = -EFAULT;
else
status = priv->actual;
kfree(priv->buf);
kfree(priv);
aio_put_req(iocb);
return status;
}
static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
{
struct kiocb *iocb = req->context;
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata = priv->epdata;
/* lock against disconnect (and ideally, cancel) */
spin_lock(&epdata->dev->lock);
priv->req = NULL;
priv->epdata = NULL;
if (NULL == iocb->ki_retry
|| unlikely(0 == req->actual)
|| unlikely(kiocbIsCancelled(iocb))) {
kfree(req->buf);
kfree(priv);
iocb->private = NULL;
/* aio_complete() reports bytes-transferred _and_ faults */
if (unlikely(kiocbIsCancelled(iocb)))
aio_put_req(iocb);
else
aio_complete(iocb,
req->actual ? req->actual : req->status,
req->status);
} else {
/* retry() won't report both; so we hide some faults */
if (unlikely(0 != req->status))
DBG(epdata->dev, "%s fault %d len %d\n",
ep->name, req->status, req->actual);
priv->buf = req->buf;
priv->actual = req->actual;
kick_iocb(iocb);
}
spin_unlock(&epdata->dev->lock);
usb_ep_free_request(ep, req);
put_ep(epdata);
}
static ssize_t
ep_aio_rwtail(
struct kiocb *iocb,
char *buf,
size_t len,
struct ep_data *epdata,
char __user *ubuf
)
{
struct kiocb_priv *priv = (void *) &iocb->private;
struct usb_request *req;
ssize_t value;
priv = kmalloc(sizeof *priv, GFP_KERNEL);
if (!priv) {
value = -ENOMEM;
fail:
kfree(buf);
return value;
}
iocb->private = priv;
priv->ubuf = ubuf;
value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
if (unlikely(value < 0)) {
kfree(priv);
goto fail;
}
iocb->ki_cancel = ep_aio_cancel;
get_ep(epdata);
priv->epdata = epdata;
priv->actual = 0;
/* each kiocb is coupled to one usb_request, but we can't
* allocate or submit those if the host disconnected.
*/
spin_lock_irq(&epdata->dev->lock);
if (likely(epdata->ep)) {
req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
if (likely(req)) {
priv->req = req;
req->buf = buf;
req->length = len;
req->complete = ep_aio_complete;
req->context = iocb;
value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
if (unlikely(0 != value))
usb_ep_free_request(epdata->ep, req);
} else
value = -EAGAIN;
} else
value = -ENODEV;
spin_unlock_irq(&epdata->dev->lock);
up(&epdata->lock);
if (unlikely(value)) {
kfree(priv);
put_ep(epdata);
} else
value = -EIOCBQUEUED;
return value;
}
static ssize_t
ep_aio_read(struct kiocb *iocb, char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(epdata->desc.bEndpointAddress & USB_DIR_IN))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
iocb->ki_retry = ep_aio_read_retry;
return ep_aio_rwtail(iocb, buf, len, epdata, ubuf);
}
static ssize_t
ep_aio_write(struct kiocb *iocb, const char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(!(epdata->desc.bEndpointAddress & USB_DIR_IN)))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
if (unlikely(copy_from_user(buf, ubuf, len) != 0)) {
kfree(buf);
return -EFAULT;
}
return ep_aio_rwtail(iocb, buf, len, epdata, NULL);
}
/*----------------------------------------------------------------------*/
/* used after endpoint configuration */
static struct file_operations ep_io_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = ep_read,
.write = ep_write,
.ioctl = ep_ioctl,
.release = ep_release,
.aio_read = ep_aio_read,
.aio_write = ep_aio_write,
};
/* ENDPOINT INITIALIZATION
*
* fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
* status = write (fd, descriptors, sizeof descriptors)
*
* That write establishes the endpoint configuration, configuring
* the controller to process bulk, interrupt, or isochronous transfers
* at the right maxpacket size, and so on.
*
* The descriptors are message type 1, identified by a host order u32
* at the beginning of what's written. Descriptor order is: full/low
* speed descriptor, then optional high speed descriptor.
*/
static ssize_t
ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
struct usb_ep *ep;
u32 tag;
int value;
if ((value = down_interruptible (&data->lock)) < 0)
return value;
if (data->state != STATE_EP_READY) {
value = -EL2HLT;
goto fail;
}
value = len;
if (len < USB_DT_ENDPOINT_SIZE + 4)
goto fail0;
/* we might need to change message format someday */
if (copy_from_user (&tag, buf, 4)) {
goto fail1;
}
if (tag != 1) {
DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
goto fail0;
}
buf += 4;
len -= 4;
/* NOTE: audio endpoint extensions not accepted here;
* just don't include the extra bytes.
*/
/* full/low speed descriptor, then high speed */
if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->desc.bDescriptorType != USB_DT_ENDPOINT)
goto fail0;
if (len != USB_DT_ENDPOINT_SIZE) {
if (len != 2 * USB_DT_ENDPOINT_SIZE)
goto fail0;
if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->hs_desc.bDescriptorType
!= USB_DT_ENDPOINT) {
DBG(data->dev, "config %s, bad hs length or type\n",
data->name);
goto fail0;
}
}
value = len;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND) {
value = -ENOENT;
goto gone;
} else if ((ep = data->ep) == NULL) {
value = -ENODEV;
goto gone;
}
switch (data->dev->gadget->speed) {
case USB_SPEED_LOW:
case USB_SPEED_FULL:
value = usb_ep_enable (ep, &data->desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#ifdef HIGHSPEED
case USB_SPEED_HIGH:
/* fails if caller didn't provide that descriptor... */
value = usb_ep_enable (ep, &data->hs_desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#endif
default:
DBG (data->dev, "unconnected, %s init deferred\n",
data->name);
data->state = STATE_EP_DEFER_ENABLE;
}
if (value == 0)
fd->f_op = &ep_io_operations;
gone:
spin_unlock_irq (&data->dev->lock);
if (value < 0) {
fail:
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
up (&data->lock);
return value;
fail0:
value = -EINVAL;
goto fail;
fail1:
value = -EFAULT;
goto fail;
}
static int
ep_open (struct inode *inode, struct file *fd)
{
struct ep_data *data = inode->u.generic_ip;
int value = -EBUSY;
if (down_interruptible (&data->lock) != 0)
return -EINTR;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND)
value = -ENOENT;
else if (data->state == STATE_EP_DISABLED) {
value = 0;
data->state = STATE_EP_READY;
get_ep (data);
fd->private_data = data;
VDEBUG (data->dev, "%s ready\n", data->name);
} else
DBG (data->dev, "%s state %d\n",
data->name, data->state);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return value;
}
/* used before endpoint configuration */
static struct file_operations ep_config_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = ep_open,
.write = ep_config,
.release = ep_release,
};
/*----------------------------------------------------------------------*/
/* EP0 IMPLEMENTATION can be partly in userspace.
*
* Drivers that use this facility receive various events, including
* control requests the kernel doesn't handle. Drivers that don't
* use this facility may be too simple-minded for real applications.
*/
static inline void ep0_readable (struct dev_data *dev)
{
wake_up (&dev->wait);
kill_fasync (&dev->fasync, SIGIO, POLL_IN);
}
static void clean_req (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
if (req->buf != dev->rbuf) {
usb_ep_free_buffer (ep, req->buf, req->dma, req->length);
req->buf = dev->rbuf;
req->dma = DMA_ADDR_INVALID;
}
req->complete = epio_complete;
dev->setup_out_ready = 0;
}
static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
int free = 1;
/* for control OUT, data must still get to userspace */
if (!dev->setup_in) {
dev->setup_out_error = (req->status != 0);
if (!dev->setup_out_error)
free = 0;
dev->setup_out_ready = 1;
ep0_readable (dev);
} else if (dev->state == STATE_SETUP)
dev->state = STATE_CONNECTED;
/* clean up as appropriate */
if (free && req->buf != &dev->rbuf)
clean_req (ep, req);
req->complete = epio_complete;
}
static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
{
struct dev_data *dev = ep->driver_data;
if (dev->setup_out_ready) {
DBG (dev, "ep0 request busy!\n");
return -EBUSY;
}
if (len > sizeof (dev->rbuf))
req->buf = usb_ep_alloc_buffer (ep, len, &req->dma, GFP_ATOMIC);
if (req->buf == 0) {
req->buf = dev->rbuf;
return -ENOMEM;
}
req->complete = ep0_complete;
req->length = len;
return 0;
}
static ssize_t
ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct dev_data *dev = fd->private_data;
ssize_t retval;
enum ep0_state state;
spin_lock_irq (&dev->lock);
/* report fd mode change before acting on it */
if (dev->setup_abort) {
dev->setup_abort = 0;
retval = -EIDRM;
goto done;
}
/* control DATA stage */
if ((state = dev->state) == STATE_SETUP) {
if (dev->setup_in) { /* stall IN */
VDEBUG(dev, "ep0in stall\n");
(void) usb_ep_set_halt (dev->gadget->ep0);
retval = -EL2HLT;
dev->state = STATE_CONNECTED;
} else if (len == 0) { /* ack SET_CONFIGURATION etc */
struct usb_ep *ep = dev->gadget->ep0;
struct usb_request *req = dev->req;
if ((retval = setup_req (ep, req, 0)) == 0)
retval = usb_ep_queue (ep, req, GFP_ATOMIC);
dev->state = STATE_CONNECTED;
/* assume that was SET_CONFIGURATION */
if (dev->current_config) {
unsigned power;
#ifdef HIGHSPEED
if (dev->gadget->speed == USB_SPEED_HIGH)
power = dev->hs_config->bMaxPower;
else
#endif
power = dev->config->bMaxPower;
usb_gadget_vbus_draw(dev->gadget, 2 * power);
}
} else { /* collect OUT data */
if ((fd->f_flags & O_NONBLOCK) != 0
&& !dev->setup_out_ready) {
retval = -EAGAIN;
goto done;
}
spin_unlock_irq (&dev->lock);
retval = wait_event_interruptible (dev->wait,
dev->setup_out_ready != 0);
]
]
|
| 119/4 |
2026/07/31 06:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 43437
output: 42
thoughts: 97
Thoughts: **Initial Exploration of the `inode.c` File**
Alright, this is the original `inode.c` file, dating back to 2005. Fascinating. My first instinct is to understand the original implementation of `gadgetfs_bind`. I want to see the initial approach, the context in which it was conceived. I could use `grepper` to pinpoint it within the initial commit, that's a good plan. However, I think it might be more efficient to just scan the rest of the file and get some context, since I know where to look. Let's start reading around line 1001 to understand the broader structure and then quickly search for that.
|
| 120/4 |
2026/07/31 06:42 |
tool |
read-file |
0m
Args: map[File:drivers/usb/gadget/legacy/inode.c FirstLine:1600 LineCount:100]
Results: map[Contents:1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
1610: data->dev = dev;
1611: get_dev (dev);
1612:
1613: data->ep = ep;
1614: ep->driver_data = data;
1615:
1616: data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1617: if (!data->req)
1618: goto enomem1;
1619:
1620: err = gadgetfs_create_file (dev->sb, data->name,
1621: data, &ep_io_operations);
1622: if (err)
1623: goto enomem2;
1624: list_add_tail (&data->epfiles, &dev->epfiles);
1625: }
1626: return 0;
1627:
1628: enomem2:
1629: usb_ep_free_request (ep, data->req);
1630: enomem1:
1631: put_dev (dev);
1632: kfree (data);
1633: enomem0:
1634: DBG (dev, "%s enomem\n", __func__);
1635: destroy_ep_files (dev);
1636: return -ENOMEM;
1637: }
1638:
1639: static void
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
1643:
1644: DBG (dev, "%s\n", __func__);
1645:
1646: spin_lock_irq (&dev->lock);
1647: dev->state = STATE_DEV_UNBOUND;
1648: while (dev->udc_usage > 0) {
1649: spin_unlock_irq(&dev->lock);
1650: usleep_range(1000, 2000);
1651: spin_lock_irq(&dev->lock);
1652: }
1653: spin_unlock_irq (&dev->lock);
1654:
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
1665:
1666: static struct dev_data *the_device;
1667:
1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
]
|
| 121/4 |
2026/07/31 06:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 45189
output: 30
thoughts: 893
Thoughts: **Analyzing a Potential Use-After-Free Vulnerability in the GadgetFS Driver**
Okay, let's dive into this. First, I need to go back to the source. The initial commit, `1da177e4c3f4`, should be the starting point. Let me check the code. I'm going to focus on `gadgetfs_bind` and `gadgetfs_unbind`. Hmm, interesting. The structure of these functions seems identical to the current version. Now, the key question is *why* `gadgetfs_unbind` gets called on failure. Is there a compelling reason beyond straightforward cleanup?
No, I don't see one. It looks like a classic mistake: the author was trying to reuse `gadgetfs_unbind` to avoid redundant cleanup code, but missed the critical fact that `gadgetfs_unbind` calls `put_dev(dev)`, decreasing the reference count. Let me double-check. In `gadgetfs_bind`, `get_dev(dev)` is only called on *success*. The failure path triggers `gadgetfs_unbind(gadget)`, which, as we know, calls `put_dev(dev)`. Since we never called `get_dev(dev)` in the failure path, this results in an extra `put_dev(dev)` call.
Right, so, is there anywhere else `get_dev` is called? No. `the_device` is initialized in `gadgetfs_fill_super` and its reference count is 1. When the user opens `/dev/gadget/$CHIP`, `gadget_dev_open` is called which, naturally, calls `get_dev(dev)`. The reference count is now 2. If `gadgetfs_bind` fails, it calls `gadgetfs_unbind(gadget)`, which then calls `put_dev(dev)`. The reference count is now 1. When the user closes `/dev/gadget/$CHIP`, `dev_release` is called, which in turn calls `put_dev(dev)`. The reference count drops to 0, which frees `dev`! But wait! `the_device` still points to `dev`! This is bad. When the filesystem is unmounted, `gadgetfs_kill_sb` is called, which then calls `put_dev(the_device)`. That's a Use-After-Free (UAF) situation. Or perhaps, a double-free, even.
Can this be triggered in any other way? Yes, if `usb_gadget_register_driver` or `gadgetfs_bind` fails, this entire sequence of events unfolds. Let's see if other files or drivers do something similar. I need to search for relevant patches or discussions about this issue. I'll search for "gadgetfs_bind" and "gadgetfs_unbind" on Google or in the kernel mailing lists. Or maybe consider a different, unrelated cause... Is it possible `gadgetfs_unbind` is called because it is the standard unbind callback for the driver? Does the driver core ever call it in these error scenarios? No, that's not how the Linux kernel's USB gadget subsystem works. The driver core doesn't call `unbind` if `bind` fails. Let me verify this by tracing how `bind` and `unbind` are actually called within the gadget core. I need to search for something like `->bind` or `driver->bind` in `drivers/usb/gadget/udc/core.c` or similar places.
|
| 122/4 |
2026/07/31 06:42 |
tool |
grepper |
0m
Args: map[Expression:\.bind\( PathPrefix:drivers/usb/gadget/]
Results: map[Output:drivers/usb/gadget/composite.c=450=EXPORT_SYMBOL_GPL(usb_function_activate);
--
drivers/usb/gadget/composite.c-457- *
drivers/usb/gadget/composite.c:458: * usb_interface_id() is called from usb_function.bind() callbacks to
drivers/usb/gadget/composite.c-459- * allocate new interface IDs. The function driver will then store that
]
|
| 123/4 |
2026/07/31 06:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 47006
output: 30
thoughts: 20
Thoughts: Here's my thought process, summarized as you requested:
**Navigating the USB Gadget Driver Landscape**
Okay, so I need to find where the `driver->bind` function is defined within the USB gadget framework. My immediate instinct is to look in the `drivers/usb/gadget/` directory. That's the logical place to start digging, given that we're talking about gadget drivers. I'm assuming that's where the core structure and related driver functions would reside. I'm really looking to understand how a USB gadget driver initializes and is "bound" to the underlying hardware. Knowing `driver->bind` is fundamental to that process. Let's start the search and see what we find. I'm hoping it's a relatively straightforward search and I can find the definition quickly.
|
| 124/4 |
2026/07/31 06:42 |
tool |
grepper |
0m
Args: map[Expression:driver->bind PathPrefix:drivers/usb/gadget/]
Results: map[Output:drivers/usb/gadget/composite.c=2689=int usb_composite_probe(struct usb_composite_driver *driver)
--
drivers/usb/gadget/composite.c-2692-
drivers/usb/gadget/composite.c:2693: if (!driver || !driver->dev || !driver->bind)
drivers/usb/gadget/composite.c-2694- return -EINVAL;
--
drivers/usb/gadget/udc/core.c=1641=static int gadget_bind_driver(struct device *dev)
--
drivers/usb/gadget/udc/core.c-1661-
drivers/usb/gadget/udc/core.c:1662: ret = driver->bind(udc->gadget, driver);
drivers/usb/gadget/udc/core.c-1663- if (ret)
--
drivers/usb/gadget/udc/core.c=1740=int usb_gadget_register_driver_owner(struct usb_gadget_driver *driver,
--
drivers/usb/gadget/udc/core.c-1744-
drivers/usb/gadget/udc/core.c:1745: if (!driver || !driver->bind || !driver->setup)
drivers/usb/gadget/udc/core.c-1746- return -EINVAL;
]
|
| 125/4 |
2026/07/31 06:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 47590
output: 43
thoughts: 40
Thoughts: Okay, let's dive into this. Here's how I'd approach understanding the failure handling within `gadget_bind_driver`, as an expert:
**Investigating Failure Handling in `gadget_bind_driver`**
Alright, the objective is clear: I need to understand how the `gadget_bind_driver` function, specifically within `drivers/usb/gadget/udc/core.c`, responds when the `driver->bind` function fails. This is a critical point in the driver binding process; failure here indicates the driver is not compatible or cannot initialize correctly with the current UDC controller. I need to see how the code gracefully handles this and what cleanup operations are performed. Are there retries? Are error messages informative? Are resources correctly released? Understanding this is vital for debugging device attachment problems, preventing resource leaks, and generally ensuring the robustness of the USB gadget system. I will look for any error code propagation or handling of return values. I suspect there may be logging to the kernel as well. It's imperative to look at the surrounding code to determine how this potential error is handled and if there are any mechanisms for recovery or graceful degradation.
|
| 126/4 |
2026/07/31 06:42 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/udc/core.c Name:gadget_bind_driver]
Results: map[SourceCode:1641: static int gadget_bind_driver(struct device *dev)
1642: {
1643: struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1644: struct usb_udc *udc = gadget->udc;
1645: struct usb_gadget_driver *driver = container_of(dev->driver,
1646: struct usb_gadget_driver, driver);
1647: int ret = 0;
1648:
1649: mutex_lock(&udc_lock);
1650: if (driver->is_bound) {
1651: mutex_unlock(&udc_lock);
1652: return -ENXIO; /* Driver binds to only one gadget */
1653: }
1654: driver->is_bound = true;
1655: udc->driver = driver;
1656: mutex_unlock(&udc_lock);
1657:
1658: dev_dbg(&udc->dev, "binding gadget driver [%s]\n", driver->function);
1659:
1660: usb_gadget_udc_set_speed(udc, driver->max_speed);
1661:
1662: ret = driver->bind(udc->gadget, driver);
1663: if (ret)
1664: goto err_bind;
1665:
1666: mutex_lock(&udc->connect_lock);
1667: ret = usb_gadget_udc_start_locked(udc);
1668: if (ret) {
1669: mutex_unlock(&udc->connect_lock);
1670: goto err_start;
1671: }
1672: usb_gadget_enable_async_callbacks(udc);
1673: udc->allow_connect = true;
1674: ret = usb_udc_connect_control_locked(udc);
1675: if (ret)
1676: goto err_connect_control;
1677:
1678: mutex_unlock(&udc->connect_lock);
1679:
1680: kobject_uevent(&udc->dev.kobj, KOBJ_CHANGE);
1681: return 0;
1682:
1683: err_connect_control:
1684: udc->allow_connect = false;
1685: usb_gadget_disable_async_callbacks(udc);
1686: if (gadget->irq)
1687: synchronize_irq(gadget->irq);
1688: usb_gadget_udc_stop_locked(udc);
1689: mutex_unlock(&udc->connect_lock);
1690:
1691: err_start:
1692: driver->unbind(udc->gadget);
1693:
1694: err_bind:
1695: if (ret != -EISNAM)
1696: dev_err(&udc->dev, "failed to start %s: %d\n",
1697: driver->function, ret);
1698:
1699: mutex_lock(&udc_lock);
1700: udc->driver = NULL;
1701: driver->is_bound = false;
1702: mutex_unlock(&udc_lock);
1703:
1704: return ret;
1705: }
SourceFile:drivers/usb/gadget/udc/core.c]
|
| 127/4 |
2026/07/31 06:42 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 48924
output: 40
thoughts: 2098
Thoughts: **Bug Hunt: Gadgetfs Reference Counting and State Machine Mishap**
Right, let's break this down. My initial observation is that if `driver->bind` fails, the `gadget` core *doesn't* call `driver->unbind`. Makes sense, the `bind` routine handles its own cleanup. But this means `driver->bind` needs to clean up after itself when it fails. And for `gadgetfs_bind`, it calls `gadgetfs_unbind` on failure. Now, that's where things get interesting. `gadgetfs_unbind` eventually calls `put_dev(dev)`. But a `get_dev(dev)` is *only* called on success at the end of `gadgetfs_bind`. This screams "reference counting bug"! If `gadgetfs_bind` fails, it's calling `put_dev` without a corresponding `get_dev`, leading to a double-free or use-after-free situation.
Okay, let's be methodical. If `gadgetfs_bind` *did* handle its own cleanup after failure, what would it need to do? Basically, release `dev->req`, clear `gadget->ep0->driver_data`, `dev->gadget`, and `set_gadget_data`. And that's it! No `put_dev` needed because `get_dev` wasn't called. So, refcount is fine if we skip `gadgetfs_unbind`.
Double-checking... what else does `gadgetfs_unbind` do? It sets `dev->state = STATE_DEV_UNBOUND`. Now, what if the user tries to register the driver again? That's when things get even worse. If the `driver` is `STATE_DEV_UNBOUND` will it even work?
Looking at `dev_config`, if `dev->state > STATE_DEV_OPENED`, it jumps into the `ep0_write` path. And looking at the enum, `STATE_DEV_UNBOUND` is definitely greater than `STATE_DEV_OPENED`. Which, means if `gadgetfs_bind` fails, and we call `gadgetfs_unbind`, then *any* subsequent attempt to register the driver fails too.
So, this bug does not only introduce a reference counting bug, but also places the device in an unrecoverable state!
|
| 128/4 |
2026/07/31 06:43 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:ep0_write]
Results: map[SourceCode:1124: static ssize_t
1125: ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1126: {
1127: struct dev_data *dev = fd->private_data;
1128: ssize_t retval = -ESRCH;
1129:
1130: /* report fd mode change before acting on it */
1131: if (dev->setup_abort) {
1132: dev->setup_abort = 0;
1133: retval = -EIDRM;
1134:
1135: /* data and/or status stage for control request */
1136: } else if (dev->state == STATE_DEV_SETUP) {
1137:
1138: len = min_t(size_t, len, dev->setup_wLength);
1139: if (dev->setup_in) {
1140: retval = setup_req (dev->gadget->ep0, dev->req, len);
1141: if (retval == 0) {
1142: dev->state = STATE_DEV_CONNECTED;
1143: ++dev->udc_usage;
1144: spin_unlock_irq (&dev->lock);
1145: if (copy_from_user (dev->req->buf, buf, len))
1146: retval = -EFAULT;
1147: else {
1148: if (len < dev->setup_wLength)
1149: dev->req->zero = 1;
1150: retval = usb_ep_queue (
1151: dev->gadget->ep0, dev->req,
1152: GFP_KERNEL);
1153: }
1154: spin_lock_irq(&dev->lock);
1155: --dev->udc_usage;
1156: if (retval < 0) {
1157: clean_req (dev->gadget->ep0, dev->req);
1158: } else
1159: retval = len;
1160:
1161: return retval;
1162: }
1163:
1164: /* can stall some OUT transfers */
1165: } else if (dev->setup_can_stall) {
1166: VDEBUG(dev, "ep0out stall\n");
1167: (void) usb_ep_set_halt (dev->gadget->ep0);
1168: retval = -EL2HLT;
1169: dev->state = STATE_DEV_CONNECTED;
1170: } else {
1171: DBG(dev, "bogus ep0out stall!\n");
1172: }
1173: } else
1174: DBG (dev, "fail %s, state %d\n", __func__, dev->state);
1175:
1176: return retval;
1177: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 129/4 |
2026/07/31 06:43 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 52434
output: 49
thoughts: 1037
Thoughts: **Analyzing USB Gadget Driver State Transitions**
Okay, here's the situation I've got my head wrapped around. If `dev->state` gets stuck as `STATE_DEV_UNBOUND`, the `ep0_write` function is going to throw an `-ESRCH` error. Basically, the user is dead in the water because they can't retry or recover from this state. It's a non-recoverable error.
The core of the problem stems from what happens when `gadgetfs_bind` fails. Initially, I was thinking the state should transition to `STATE_DEV_UNBOUND`. However, a failure in `gadgetfs_bind` really means the registration of the driver failed, and the device was never actually bound in the first place. So, the right approach is to leave the state as `STATE_DEV_OPENED`. This keeps things open for the user, allowing them to fix whatever the underlying problem is—maybe there's a memory issue, or the wrong controller is plugged in, and retry writing the configuration.
Let's dig into the details: I checked `dev_config` and it looks like:
```c
spin_lock_irq(&dev->lock);
if (dev->state > STATE_DEV_OPENED) {
value = ep0_write(fd, buf, len, ptr);
spin_unlock_irq(&dev->lock);
return value;
}
spin_unlock_irq(&dev->lock);
```
So, if `dev->state` is `STATE_DEV_OPENED`, it proceeds to parse the descriptors and register the driver. If registration fails, it jumps to `fail`:
```c
fail:
dev->config = NULL;
dev->hs_config = NULL;
dev->dev = NULL;
spin_unlock_irq (&dev->lock);
pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev);
kfree (dev->buf);
dev->buf = NULL;
return value;
```
Here's the kicker: The `fail` block *doesn't* actually change `dev->state`! That means if `gadgetfs_bind` fails *without* calling `gadgetfs_unbind` (which sets `dev->state = STATE_DEV_UNBOUND`), `dev->state` *remains* as `STATE_DEV_OPENED`. This means the user *could* actually retry writing the configuration.
Unfortunately, `gadgetfs_bind` *does* call `gadgetfs_unbind` on failure, setting `dev->state = STATE_DEV_UNBOUND`. This is what locks the device in an unrecoverable state. Any subsequent write attempt to `ep0` will fail, and the user will have to close and reopen the device. That's a definite side effect of calling `gadgetfs_unbind` on failure.
Now, let's explore some other potential side effects. What about `dev->gadget`? I see:
```c
dev->gadget = gadget;
```
in `gadgetfs_bind`. So, if `gadgetfs_bind` fails and `gadgetfs_unbind` gets called, it should clear `dev->gadget`! However, the code:
```c
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
...
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
```
Wait, `gadgetfs_unbind` does *not* clear `dev->gadget`! That means `dev->gadget` still points to the `gadget` structure even though the driver is unbound! Dangling pointer!
So, `dev->gadget` is now a
|
| 130/4 |
2026/07/31 06:43 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c IncludeSnippetLines:10 Name:dev_data::gadget]
Results: map[References:[map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:activate_ep_files SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1599 SourceSnippet:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:activate_ep_files SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1599 SourceSnippet:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:activate_ep_files SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1599 SourceSnippet:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:activate_ep_files SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1599 SourceSnippet:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:config_buf SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1316 SourceSnippet:1306: static int
1307: config_buf (struct dev_data *dev, u8 type, unsigned index)
1308: {
1309: int len;
1310: int hs = 0;
1311:
1312: /* only one configuration */
1313: if (index > 0)
1314: return -EINVAL;
1315:
1316: if (gadget_is_dualspeed(dev->gadget)) {
1317: hs = (dev->gadget->speed == USB_SPEED_HIGH);
1318: if (type == USB_DT_OTHER_SPEED_CONFIG)
1319: hs = !hs;
1320: }
1321: if (hs) {
1322: dev->req->buf = dev->hs_config;
1323: len = le16_to_cpu(dev->hs_config->wTotalLength);
1324: } else {
1325: dev->req->buf = dev->config;
1326: len = le16_to_cpu(dev->config->wTotalLength);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:config_buf SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1317 SourceSnippet:1307: config_buf (struct dev_data *dev, u8 type, unsigned index)
1308: {
1309: int len;
1310: int hs = 0;
1311:
1312: /* only one configuration */
1313: if (index > 0)
1314: return -EINVAL;
1315:
1316: if (gadget_is_dualspeed(dev->gadget)) {
1317: hs = (dev->gadget->speed == USB_SPEED_HIGH);
1318: if (type == USB_DT_OTHER_SPEED_CONFIG)
1319: hs = !hs;
1320: }
1321: if (hs) {
1322: dev->req->buf = dev->hs_config;
1323: len = le16_to_cpu(dev->hs_config->wTotalLength);
1324: } else {
1325: dev->req->buf = dev->config;
1326: len = le16_to_cpu(dev->config->wTotalLength);
1327: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_read SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:937 SourceSnippet: 927: dev->setup_abort = 0;
928: retval = -EIDRM;
929: goto done;
930: }
931:
932: /* control DATA stage */
933: if ((state = dev->state) == STATE_DEV_SETUP) {
934:
935: if (dev->setup_in) { /* stall IN */
936: VDEBUG(dev, "ep0in stall\n");
937: (void) usb_ep_set_halt (dev->gadget->ep0);
938: retval = -EL2HLT;
939: dev->state = STATE_DEV_CONNECTED;
940:
941: } else if (len == 0) { /* ack SET_CONFIGURATION etc */
942: struct usb_ep *ep = dev->gadget->ep0;
943: struct usb_request *req = dev->req;
944:
945: if ((retval = setup_req (ep, req, 0)) == 0) {
946: ++dev->udc_usage;
947: spin_unlock_irq (&dev->lock);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_read SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:942 SourceSnippet: 932: /* control DATA stage */
933: if ((state = dev->state) == STATE_DEV_SETUP) {
934:
935: if (dev->setup_in) { /* stall IN */
936: VDEBUG(dev, "ep0in stall\n");
937: (void) usb_ep_set_halt (dev->gadget->ep0);
938: retval = -EL2HLT;
939: dev->state = STATE_DEV_CONNECTED;
940:
941: } else if (len == 0) { /* ack SET_CONFIGURATION etc */
942: struct usb_ep *ep = dev->gadget->ep0;
943: struct usb_request *req = dev->req;
944:
945: if ((retval = setup_req (ep, req, 0)) == 0) {
946: ++dev->udc_usage;
947: spin_unlock_irq (&dev->lock);
948: retval = usb_ep_queue (ep, req, GFP_KERNEL);
949: spin_lock_irq (&dev->lock);
950: --dev->udc_usage;
951: }
952: dev->state = STATE_DEV_CONNECTED;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_read SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:958 SourceSnippet: 948: retval = usb_ep_queue (ep, req, GFP_KERNEL);
949: spin_lock_irq (&dev->lock);
950: --dev->udc_usage;
951: }
952: dev->state = STATE_DEV_CONNECTED;
953:
954: /* assume that was SET_CONFIGURATION */
955: if (dev->current_config) {
956: unsigned power;
957:
958: if (gadget_is_dualspeed(dev->gadget)
959: && (dev->gadget->speed
960: == USB_SPEED_HIGH))
961: power = dev->hs_config->bMaxPower;
962: else
963: power = dev->config->bMaxPower;
964: usb_gadget_vbus_draw(dev->gadget, 2 * power);
965: }
966:
967: } else { /* collect OUT data */
968: if ((fd->f_flags & O_NONBLOCK) != 0
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_read SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:959 SourceSnippet: 949: spin_lock_irq (&dev->lock);
950: --dev->udc_usage;
951: }
952: dev->state = STATE_DEV_CONNECTED;
953:
954: /* assume that was SET_CONFIGURATION */
955: if (dev->current_config) {
956: unsigned power;
957:
958: if (gadget_is_dualspeed(dev->gadget)
959: && (dev->gadget->speed
960: == USB_SPEED_HIGH))
961: power = dev->hs_config->bMaxPower;
962: else
963: power = dev->config->bMaxPower;
964: usb_gadget_vbus_draw(dev->gadget, 2 * power);
965: }
966:
967: } else { /* collect OUT data */
968: if ((fd->f_flags & O_NONBLOCK) != 0
969: && !dev->setup_out_ready) {
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_read SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:964 SourceSnippet: 954: /* assume that was SET_CONFIGURATION */
955: if (dev->current_config) {
956: unsigned power;
957:
958: if (gadget_is_dualspeed(dev->gadget)
959: && (dev->gadget->speed
960: == USB_SPEED_HIGH))
961: power = dev->hs_config->bMaxPower;
962: else
963: power = dev->config->bMaxPower;
964: usb_gadget_vbus_draw(dev->gadget, 2 * power);
965: }
966:
967: } else { /* collect OUT data */
968: if ((fd->f_flags & O_NONBLOCK) != 0
969: && !dev->setup_out_ready) {
970: retval = -EAGAIN;
971: goto done;
972: }
973: spin_unlock_irq (&dev->lock);
974: retval = wait_event_interruptible (dev->wait,
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_read SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1000 SourceSnippet: 990: else {
991: len = min (len, (size_t)dev->req->actual);
992: ++dev->udc_usage;
993: spin_unlock_irq(&dev->lock);
994: if (copy_to_user (buf, dev->req->buf, len))
995: retval = -EFAULT;
996: else
997: retval = len;
998: spin_lock_irq(&dev->lock);
999: --dev->udc_usage;
1000: clean_req (dev->gadget->ep0, dev->req);
1001: /* NOTE userspace can't yet choose to stall */
1002: }
1003: }
1004: goto done;
1005: }
1006:
1007: /* else normal: return event data */
1008: if (len < sizeof dev->event [0]) {
1009: retval = -EINVAL;
1010: goto done;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_write SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1140 SourceSnippet:1130: /* report fd mode change before acting on it */
1131: if (dev->setup_abort) {
1132: dev->setup_abort = 0;
1133: retval = -EIDRM;
1134:
1135: /* data and/or status stage for control request */
1136: } else if (dev->state == STATE_DEV_SETUP) {
1137:
1138: len = min_t(size_t, len, dev->setup_wLength);
1139: if (dev->setup_in) {
1140: retval = setup_req (dev->gadget->ep0, dev->req, len);
1141: if (retval == 0) {
1142: dev->state = STATE_DEV_CONNECTED;
1143: ++dev->udc_usage;
1144: spin_unlock_irq (&dev->lock);
1145: if (copy_from_user (dev->req->buf, buf, len))
1146: retval = -EFAULT;
1147: else {
1148: if (len < dev->setup_wLength)
1149: dev->req->zero = 1;
1150: retval = usb_ep_queue (
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_write SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1151 SourceSnippet:1141: if (retval == 0) {
1142: dev->state = STATE_DEV_CONNECTED;
1143: ++dev->udc_usage;
1144: spin_unlock_irq (&dev->lock);
1145: if (copy_from_user (dev->req->buf, buf, len))
1146: retval = -EFAULT;
1147: else {
1148: if (len < dev->setup_wLength)
1149: dev->req->zero = 1;
1150: retval = usb_ep_queue (
1151: dev->gadget->ep0, dev->req,
1152: GFP_KERNEL);
1153: }
1154: spin_lock_irq(&dev->lock);
1155: --dev->udc_usage;
1156: if (retval < 0) {
1157: clean_req (dev->gadget->ep0, dev->req);
1158: } else
1159: retval = len;
1160:
1161: return retval;
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_write SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1157 SourceSnippet:1147: else {
1148: if (len < dev->setup_wLength)
1149: dev->req->zero = 1;
1150: retval = usb_ep_queue (
1151: dev->gadget->ep0, dev->req,
1152: GFP_KERNEL);
1153: }
1154: spin_lock_irq(&dev->lock);
1155: --dev->udc_usage;
1156: if (retval < 0) {
1157: clean_req (dev->gadget->ep0, dev->req);
1158: } else
1159: retval = len;
1160:
1161: return retval;
1162: }
1163:
1164: /* can stall some OUT transfers */
1165: } else if (dev->setup_can_stall) {
1166: VDEBUG(dev, "ep0out stall\n");
1167: (void) usb_ep_set_halt (dev->gadget->ep0);
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep0_write SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1167 SourceSnippet:1157: clean_req (dev->gadget->ep0, dev->req);
1158: } else
1159: retval = len;
1160:
1161: return retval;
1162: }
1163:
1164: /* can stall some OUT transfers */
1165: } else if (dev->setup_can_stall) {
1166: VDEBUG(dev, "ep0out stall\n");
1167: (void) usb_ep_set_halt (dev->gadget->ep0);
1168: retval = -EL2HLT;
1169: dev->state = STATE_DEV_CONNECTED;
1170: } else {
1171: DBG(dev, "bogus ep0out stall!\n");
1172: }
1173: } else
1174: DBG (dev, "fail %s, state %d\n", __func__, dev->state);
1175:
1176: return retval;
1177: }
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:ep_config SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:784 SourceSnippet: 774: if (data->dev->state == STATE_DEV_UNBOUND) {
775: value = -ENOENT;
776: goto gone;
777: } else {
778: ep = data->ep;
779: if (ep == NULL) {
780: value = -ENODEV;
781: goto gone;
782: }
783: }
784: switch (data->dev->gadget->speed) {
785: case USB_SPEED_LOW:
786: case USB_SPEED_FULL:
787: ep->desc = &data->desc;
788: break;
789: case USB_SPEED_HIGH:
790: /* fails if caller didn't provide that descriptor... */
791: ep->desc = &data->hs_desc;
792: break;
793: default:
794: DBG(data->dev, "unconnected, %s init abandoned\n",
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:gadget_dev_ioctl SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1254 SourceSnippet:1251: static long gadget_dev_ioctl (struct file *fd, unsigned code, unsigned long value)
1252: {
1253: struct dev_data *dev = fd->private_data;
1254: struct usb_gadget *gadget = dev->gadget;
1255: long ret = -ENOTTY;
1256:
1257: spin_lock_irq(&dev->lock);
1258: if (dev->state == STATE_DEV_OPENED ||
1259: dev->state == STATE_DEV_UNBOUND) {
1260: /* Not bound to a UDC */
1261: } else if (gadget->ops->ioctl) {
1262: ++dev->udc_usage;
1263: spin_unlock_irq(&dev->lock);
1264:
] map[ReferenceKind:writes ReferencingEntityKind:function ReferencingEntityName:gadgetfs_bind SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1682 SourceSnippet:1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
] map[ReferenceKind:reads ReferencingEntityKind:function ReferencingEntityName:gadgetfs_setup SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1391 SourceSnippet:1381: req->context = NULL;
1382: switch (ctrl->bRequest) {
1383:
1384: case USB_REQ_GET_DESCRIPTOR:
1385: if (ctrl->bRequestType != USB_DIR_IN)
1386: goto unrecognized;
1387: switch (w_value >> 8) {
1388:
1389: case USB_DT_DEVICE:
1390: value = min (w_length, (u16) sizeof *dev->dev);
1391: dev->dev->bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
1392: req->buf = dev->dev;
1393: break;
1394: case USB_DT_DEVICE_QUALIFIER:
1395: if (!dev->hs_config)
1396: break;
1397: value = min (w_length, (u16)
1398: sizeof (struct usb_qualifier_descriptor));
1399: make_qualifier (dev);
1400: break;
1401: case USB_DT_OTHER_SPEED_CONFIG:
]] TruncatedOutput:true]
|
| 131/4 |
2026/07/31 06:43 |
llm |
codeexpert |
0m
Model:
Tokens:
input: 61685
output: 902
thoughts: 2535
Thoughts: **Analysis of `gadgetfs_bind` and `gadgetfs_unbind`**
Okay, so I've been digging into the `gadget_dev_ioctl` function, and the way the `gadgetfs` driver handles binding and unbinding. Specifically, I'm focusing on the interaction between `gadgetfs_bind` and `gadgetfs_unbind`, and whether it makes sense to call the latter on failure of the former.
No, there is no valid reason why `gadgetfs_bind` should call `gadgetfs_unbind` on failure. In fact, doing so is a bug that causes several issues, most notably a reference counting imbalance leading to a Use-After-Free (UAF) or double free.
Let's break down the problem step-by-step:
1. **Reference Counting Bug (UAF / Double Free)**: The root cause is an improper handling of the reference count for the `dev` structure (which represents the device data associated with the gadget).
* `dev` is initialized with a reference count of 1 in `dev_new()` (called during the filesystem mount in `gadgetfs_fill_super`).
* When the user opens a file descriptor for `/dev/gadget/$CHIP` (via `gadget_dev_open`), `get_dev(dev)` is *not* called at this time.
* If `gadgetfs_bind` *succeeds*, it increments the reference count to 2 with `get_dev(dev)` (line 1699), as the open file descriptor represents a second reference.
* If `gadgetfs_bind` *fails*, it calls `gadgetfs_unbind()` (line 1703). Now, `gadgetfs_unbind` calls `put_dev(dev)`. This *decrements* the reference count *back* to 1! However, the only *increment* happens at the very *end* of `gadgetfs_bind`, when everything succeeds. This implies a broken reference count.
* When the user closes the file descriptor (via `dev_release`), `put_dev(dev)` is called which decrements the reference count *again*, to 0, which frees the `dev` structure.
* When the filesystem is unmounted (via `gadgetfs_kill_sb`), `put_dev(the_device)` is called, where `the_device` references the freed `dev` and a Use-After-Free or double free is triggered.
2. **Dangling Pointer**: `gadgetfs_unbind` does *not* clear `dev->gadget`. This leaves a dangling pointer in `dev->gadget` if a subsequent operation attempts to access it.
3. **Irrecoverable State**: `gadgetfs_unbind` sets `dev->state = STATE_DEV_UNBOUND`. This means the user *cannot* retry the configuration write on the open file descriptor. If we cleaned up manually (as I'll describe shortly), `dev->state` would remain `STATE_DEV_OPENED`, allowing the user to potentially re-attempt the configuration.
4. **Redundant Cleanup**: If `activate_ep_files` fails during `gadgetfs_bind`, it already calls `destroy_ep_files(dev)` internally to clean up the endpoint files it created. Calling `gadgetfs_unbind` *after* that results in a redundant call to `destroy_ep_files(dev)`.
How should this be fixed? Manual cleanup is the way to go:
Here's how `gadgetfs_bind` should be modified to handle failures without calling `gadgetfs_unbind`:
* If `usb_ep_alloc_request` fails:
```c
if (!dev->req) {
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
}
```
* If `activate_ep_files` fails:
```c
if (activate_ep_files (dev) < 0) {
usb_ep_free_request(gadget->ep0, dev->req);
dev->req = NULL;
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
}
```
This *manual* cleanup is perfectly balanced:
* It avoids the broken reference count decrement.
* It clears the
|
| 132/4 |
2026/07/31 06:43 |
tool |
set-results |
0m
Args: map[Answer:No, there is no valid reason why `gadgetfs_bind` should call `gadgetfs_unbind` on failure. In fact, doing so is a bug that introduces several critical issues, most notably a reference counting imbalance that leads to a Use-After-Free (UAF) or double free.
### 1. Reference Counting Bug (UAF / Double Free)
The reference count of the `dev_data` structure (`dev->count`) is managed as follows:
- **Initialization**: Set to `1` in `dev_new()` when the filesystem is mounted (via `gadgetfs_fill_super`).
- **File Open**: Incremented to `2` in `gadget_dev_open()` when the user opens `/dev/gadget/$CHIP`.
- **Successful Bind**: Incremented to `3` via `get_dev(dev)` at the very end of `gadgetfs_bind()` (line 1699).
- **Failed Bind**: If `gadgetfs_bind()` fails (e.g., due to memory allocation failure in `usb_ep_alloc_request` or `activate_ep_files`), it jumps to `enomem` and calls `gadgetfs_unbind(gadget)`.
- Inside `gadgetfs_unbind()`, `put_dev(dev)` is called, which decrements the reference count of `dev` to `1`.
- However, `get_dev(dev)` was **never called** because the bind failed before reaching line 1699.
- When the user subsequently closes the open file descriptor, `dev_release()` is called and invokes `put_dev(dev)`, decrementing the reference count to `0` and freeing `dev`.
- Finally, when the filesystem is unmounted, `gadgetfs_kill_sb()` is called and invokes `put_dev(the_device)`. Since `the_device` points to the already-freed `dev`, this results in a **Use-After-Free (UAF) or double free**.
### 2. Other Issues Caused by Calling `gadgetfs_unbind` on Failure
- **Dangling Pointer**: `gadgetfs_unbind()` does not clear `dev->gadget`, leaving a dangling pointer to the `gadget` structure in `dev->gadget`.
- **Irrecoverable State**: `gadgetfs_unbind()` sets `dev->state = STATE_DEV_UNBOUND`. This prevents the user from retrying the configuration write on the open file descriptor. If manual cleanup was done instead, `dev->state` would remain `STATE_DEV_OPENED`, allowing the user to potentially retry the configuration write.
- **Redundant Cleanup**: If `activate_ep_files()` fails, it already calls `destroy_ep_files(dev)` internally to clean up any endpoint files it created. Calling `gadgetfs_unbind()` subsequently results in a redundant call to `destroy_ep_files(dev)`.
### 3. How Manual Cleanup Should Look
Instead of calling `gadgetfs_unbind()`, `gadgetfs_bind()` should perform manual cleanup on failure:
- **If `usb_ep_alloc_request` fails**:
```c
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
- **If `activate_ep_files` fails**:
```c
usb_ep_free_request(gadget->ep0, dev->req);
dev->req = NULL;
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
This manual cleanup is perfectly balanced, avoids the reference count drop, clears the dangling pointer, leaves the state as `STATE_DEV_OPENED` for retries, and avoids redundant cleanup.]
Results: map[Answer:No, there is no valid reason why `gadgetfs_bind` should call `gadgetfs_unbind` on failure. In fact, doing so is a bug that introduces several critical issues, most notably a reference counting imbalance that leads to a Use-After-Free (UAF) or double free.
### 1. Reference Counting Bug (UAF / Double Free)
The reference count of the `dev_data` structure (`dev->count`) is managed as follows:
- **Initialization**: Set to `1` in `dev_new()` when the filesystem is mounted (via `gadgetfs_fill_super`).
- **File Open**: Incremented to `2` in `gadget_dev_open()` when the user opens `/dev/gadget/$CHIP`.
- **Successful Bind**: Incremented to `3` via `get_dev(dev)` at the very end of `gadgetfs_bind()` (line 1699).
- **Failed Bind**: If `gadgetfs_bind()` fails (e.g., due to memory allocation failure in `usb_ep_alloc_request` or `activate_ep_files`), it jumps to `enomem` and calls `gadgetfs_unbind(gadget)`.
- Inside `gadgetfs_unbind()`, `put_dev(dev)` is called, which decrements the reference count of `dev` to `1`.
- However, `get_dev(dev)` was **never called** because the bind failed before reaching line 1699.
- When the user subsequently closes the open file descriptor, `dev_release()` is called and invokes `put_dev(dev)`, decrementing the reference count to `0` and freeing `dev`.
- Finally, when the filesystem is unmounted, `gadgetfs_kill_sb()` is called and invokes `put_dev(the_device)`. Since `the_device` points to the already-freed `dev`, this results in a **Use-After-Free (UAF) or double free**.
### 2. Other Issues Caused by Calling `gadgetfs_unbind` on Failure
- **Dangling Pointer**: `gadgetfs_unbind()` does not clear `dev->gadget`, leaving a dangling pointer to the `gadget` structure in `dev->gadget`.
- **Irrecoverable State**: `gadgetfs_unbind()` sets `dev->state = STATE_DEV_UNBOUND`. This prevents the user from retrying the configuration write on the open file descriptor. If manual cleanup was done instead, `dev->state` would remain `STATE_DEV_OPENED`, allowing the user to potentially retry the configuration write.
- **Redundant Cleanup**: If `activate_ep_files()` fails, it already calls `destroy_ep_files(dev)` internally to clean up any endpoint files it created. Calling `gadgetfs_unbind()` subsequently results in a redundant call to `destroy_ep_files(dev)`.
### 3. How Manual Cleanup Should Look
Instead of calling `gadgetfs_unbind()`, `gadgetfs_bind()` should perform manual cleanup on failure:
- **If `usb_ep_alloc_request` fails**:
```c
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
- **If `activate_ep_files` fails**:
```c
usb_ep_free_request(gadget->ep0, dev->req);
dev->req = NULL;
gadget->ep0->driver_data = NULL;
set_gadget_data(gadget, NULL);
dev->gadget = NULL;
return -ENOMEM;
```
This manual cleanup is perfectly balanced, avoids the reference count drop, clears the dangling pointer, leaves the state as `STATE_DEV_OPENED` for retries, and avoids redundant cleanup.]
|
| 133/2 |
2026/07/31 06:43 |
llm |
debugger |
0m
Model:
Tokens:
input: 56241
output: 966
thoughts: 17
Thoughts: Okay, here's my summary, presented as your expert thoughts:
**Confirmation and Finalization**
Ah, excellent. The codeexpert’s response aligns precisely with my own initial assessment. It’s a validation of my understanding and approach. Now, with this reinforcement in place, I can confidently proceed to finalize the response. The pieces are all in place, and the analysis is sound. Time to articulate the concluding arguments.
|
| 134/1 |
2026/07/31 06:43 |
agent |
history-explorer |
10m
Model:
Instruction:
You are an experienced Linux kernel developer researching prior art for fixing a kernel bug.
You are given a bug explanation. This explanation details the root cause of the bug resulting
from debugging, but does not provide the final fix strategy. Your goal is to explore how
similar bugs were fixed in the past in the same subsystem or files.
CRITICAL: Do NOT attempt to debug the issue further or write a patch for it yourself.
Your ONLY objective is to research and provide the necessary historical context.
Use the git-log tool with the Since parameter set to "3 years" to focus on recent history.
Search for commits that address issues with similar root causes (e.g. similar missing locks,
incorrect refcounting, or similar error path bugs) in the affected files.
Your final reply must summarize your findings: what idioms, locking rules, or common patterns
should be followed when writing a fix for this bug based on how previous similar bugs were addressed.
If you find no relevant past fixes, clearly state that.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash is:
==================================================================
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Not tainted syzkaller #1 PREEMPT
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
print_address_description+0xb0/0x238 mm/kasan/report.c:378
print_report+0x68/0x84 mm/kasan/report.c:482
kasan_report+0x8c/0xc4 mm/kasan/report.c:595
__kasan_check_byte+0x3c/0x54 mm/kasan/common.c:574
kasan_check_byte include/linux/kasan.h:402 [inline]
lock_acquire+0xa4/0x364 kernel/locking/lockdep.c:5842
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Allocated by task 5241:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_alloc_info+0x44/0x54 mm/kasan/generic.c:570
poison_kmalloc_redzone mm/kasan/common.c:398 [inline]
__kasan_kmalloc+0x9c/0xb4 mm/kasan/common.c:415
kasan_kmalloc include/linux/kasan.h:263 [inline]
__kmalloc_cache_noprof+0x2e8/0x5ec mm/slub.c:5489
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
dev_new drivers/usb/gadget/legacy/inode.c:176 [inline]
gadgetfs_fill_super+0x19c/0x370 drivers/usb/gadget/legacy/inode.c:2054
vfs_get_super+0xb8/0x148 fs/super.c:1273
get_tree_single+0x30/0x40 fs/super.c:1300
gadgetfs_get_tree+0x28/0x38 drivers/usb/gadget/legacy/inode.c:2085
vfs_get_tree+0x90/0x28c fs/super.c:1700
fc_mount+0x24/0xac fs/namespace.c:1198
do_new_mount_fc fs/namespace.c:3765 [inline]
do_new_mount+0x2a4/0x538 fs/namespace.c:3841
path_mount+0x5f0/0xa88 fs/namespace.c:4161
do_mount+0xe8/0x148 fs/namespace.c:4174
__do_sys_mount fs/namespace.c:4390 [inline]
__se_sys_mount fs/namespace.c:4367 [inline]
__arm64_sys_mount+0x334/0x380 fs/namespace.c:4367
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Freed by task 5331:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_free_info+0x58/0x70 mm/kasan/generic.c:584
poison_slab_object mm/kasan/common.c:253 [inline]
__kasan_slab_free+0x74/0xa4 mm/kasan/common.c:285
kasan_slab_free include/linux/kasan.h:235 [inline]
slab_free_hook mm/slub.c:2677 [inline]
slab_free mm/slub.c:6377 [inline]
kfree+0x188/0x690 mm/slub.c:6692
put_dev+0x8c/0xf8 drivers/usb/gadget/legacy/inode.c:169
dev_release+0x100/0x15c drivers/usb/gadget/legacy/inode.c:1215
__fput+0x338/0x74c fs/file_table.c:512
____fput+0x20/0x30 fs/file_table.c:540
task_work_run+0x1cc/0x25c kernel/task_work.c:233
resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]
__exit_to_user_mode_loop kernel/entry/common.c:70 [inline]
exit_to_user_mode_loop+0x10c/0x17c kernel/entry/common.c:101
__exit_to_user_mode_prepare include/linux/irq-entry-common.h:207 [inline]
syscall_exit_to_user_mode_prepare include/linux/irq-entry-common.h:230 [inline]
arm64_syscall_exit_to_user_mode arch/arm64/kernel/entry-common.c:88 [inline]
el0_svc+0x18c/0x260 arch/arm64/kernel/entry-common.c:737
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
The buggy address belongs to the object at ffff0000dbe16000
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 24 bytes inside of
freed 1024-byte region [ffff0000dbe16000, ffff0000dbe16400)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff0000dbe15000 pfn:0x11be10
head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
flags: 0x5ffc00000000240(workingset|head|node=0|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
raw: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
head: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000003 fffffdffc36f8401 00000000ffffffff 00000000ffffffff
head: ffffffffffffffff 0000000000000000 00000000ffffffff 0000000000000008
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff0000dbe15f00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff0000dbe15f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff0000dbe16000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff0000dbe16080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff0000dbe16100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
------------[ cut here ]------------
UBSAN: array-index-out-of-bounds in /app/workdir/cache/src/3735123449433f9e6f9fb5b55ddd9994cbcf15f0/kernel/locking/qspinlock.h:68:9
index 13031 is out of range for type 'unsigned long[8]'
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
ubsan_epilogue+0x14/0x48 lib/ubsan.c:233
__ubsan_handle_out_of_bounds+0xd0/0xf8 lib/ubsan.c:455
decode_tail kernel/locking/qspinlock.h:68 [inline]
queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
---[ end trace ]---
Unable to handle kernel paging request at virtual address ffff800088b48710
KASAN: probably user-memory-access in range [0x0000000445a43880-0x0000000445a43887]
Mem abort info:
ESR = 0x0000000096000047
EC = 0x25: DABT (current EL), IL = 32 bits
SET = 0, FnV = 0
EA = 0, S1PTW = 0
FSC = 0x07: level 3 translation fault
Data abort info:
ISV = 0, ISS = 0x00000047, ISS2 = 0x00000000
CM = 0, WnR = 1, TnD = 0, TagAccess = 0
GCS = 0, Overlay = 0, DirtyBit = 0
swapper pgtable: 4k pages, 48-bit VAs, pgdp=000000021aeb5000
[ffff800088b48710] pgd=0000000000000000, p4d=10000002211ac003, pud=10000002211ad003, pmd=10000002211b1003, pte=0000000000000000
Internal error: Oops: 0000000096000047 [#1] SMP
Modules linked in:
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
pstate: 834000c5 (Nzcv daIF +PAN -UAO +TCO +DIT -SSBS BTYPE=--)
pc : queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:288
lr : decode_tail kernel/locking/qspinlock.h:68 [inline]
lr : queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
sp : ffff800097c37560
x29: ffff800097c37600 x28: ffff800088b48710 x27: 1fffe00019980afa
x26: 1fffe0001b7c2c00 x25: ffff0001add9f708 x24: dfff800000000000
x23: ffff700012f86eb0 x22: ffff0001add9f700 x21: 1fffe00035bb3ee0
x20: ffff0000ccc057d0 x19: ffff0000dbe16000 x18: 0000000000000000
x17: 3d3d3d3d3d3d3d3d x16: 0000000000000001 x15: 0000000000000000
x14: 0000000000000000 x13: 0000000000000001 x12: 0000000000000004
x11: ffff700011474c6c x10: ffff800088b48700 x9 : ffff800088b48710
x8 : 0000000000000000 x7 : 0000000000000001 x6 : ffff80008048d694
x5 : 0000000000000000 x4 : 0000000000000000 x3 : ffff8000802f6c98
x2 : 0000000000000002 x1 : 0000000000000004 x0 : ffff0001add9f708
Call trace:
queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:291 (P)
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Code: aa1c03e0 968a785a 910022c0 52800081 (f9000396)
---[ end trace 0000000000000000 ]---
----------------
Code disassembly (best guess):
0: aa1c03e0 mov x0, x28
4: 968a785a bl 0xfffffffffa29e16c
8: 910022c0 add x0, x22, #0x8
c: 52800081 mov w1, #0x4 // #4
* 10: f9000396 str x22, [x28] <-- trapping instruction
The explanation of the root cause of the bug is:
The root cause of this KASAN slab-use-after-free is a reference counting bug in the error path of `gadgetfs_bind()` in `drivers/usb/gadget/legacy/inode.c`.
When the gadget driver is being bound, `gadgetfs_bind()` performs several initialization steps. If it succeeds, it takes a reference to the `dev` object by calling `get_dev(dev)` at the very end of the function. This reference is meant to be balanced by a call to `put_dev(dev)` inside `gadgetfs_unbind()` when the driver is eventually unbound.
However, if `gadgetfs_bind()` fails midway (e.g., due to the fault injection causing `activate_ep_files()` to fail), it jumps to the `enomem` label and calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**.
### Detailed Trace
1. **Initialization**: When the gadgetfs is mounted, `gadgetfs_fill_super()` calls `dev_new()`, which initializes the `dev` object with a refcount of `1`.
2. **First Open**: The reproducer opens the `ep0` file (`dummy_udc`). This calls `gadget_dev_open()`, which increments the refcount to `2` via `get_dev(dev)`.
3. **Configuration**: The reproducer writes to the `ep0` file descriptor, triggering `dev_config()`. This parses the descriptors and calls `usb_gadget_register_driver()`, which in turn calls `gadgetfs_bind()`.
4. **Fault Injection**: Inside `gadgetfs_bind()`, `activate_ep_files()` fails due to the injected memory allocation failure.
5. **The Bug**: `gadgetfs_bind()` jumps to the `enomem` label and calls `gadgetfs_unbind()`. `gadgetfs_unbind()` calls `put_dev(dev)`, dropping the refcount to `1`. (It should have remained `2` because `gadgetfs_bind()` never took its reference).
6. **File Close**: The `write()` syscall returns `-ENOMEM`. The reproducer process exits (or closes the file descriptor), triggering `dev_release()`. This calls `put_dev(dev)`, dropping the refcount to `0`. The `dev` object is freed.
7. **Use-After-Free**: The reproducer (or another thread) opens the `ep0` file again. `gadget_dev_open()` is called, which accesses the freed `dev` object via `inode->i_private` to acquire `dev->lock`, resulting in the KASAN slab-use-after-free crash.
### The Fix
Instead of calling `gadgetfs_unbind()` on failure, `gadgetfs_bind()` should manually undo the specific initialization steps it performed before the failure.
Note that `activate_ep_files()` already cleans up after itself if it fails (by calling `destroy_ep_files()`), so we only need to free `dev->req` (if it was allocated) and clear the gadget data pointers.
```c
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,12 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
```
By doing this manual cleanup, we avoid the unbalanced `put_dev(dev)`, prevent `dev->state` from being incorrectly set to `STATE_DEV_UNBOUND` (which would prevent the user from retrying the configuration write), and avoid redundant calls to `destroy_ep_files()`.
Reply: Based on a review of recent commits in the USB gadget subsystem, the root cause of this bug stems from a well-known anti-pattern: **calling a full `unbind` or `remove` function from within the error path of a `bind` or `probe` function.**
Full cleanup functions typically assume that the object was fully initialized (e.g., all references were taken, all memory was allocated). When invoked on a partially initialized object, they often drop references that were never acquired, free memory that was never allocated, or double-free resources.
Here are the historical patterns and idioms used to fix similar bugs in this subsystem:
### 1. Manual, Step-by-Step Cleanup via `goto` Labels
The standard kernel idiom for error paths is to manually undo exactly the steps that succeeded, in reverse order, rather than calling a monolithic cleanup function.
* **`62783c30d78a` ("USB: gadget: f_hid: Fix memory leak in hidg_bind error path")**: In `hidg_bind()`, an error path failed to free descriptors. The fix restructured the error handling by adding specific `goto` labels (`fail_free_all`, `fail_free_descs`) to manually clean up resources in reverse order of allocation.
* **`782be79e4551` ("usb: gadget: lpc32xx_udc: fix clock imbalance in error path")**: Fixed an issue where an error path disabled a clock that hadn't been enabled yet. The fix introduced proper granular `goto` labels to ensure only initialized resources were cleaned up.
### 2. Avoiding Monolithic Cleanup Functions in Error Paths
Calling a full teardown function on a partially initialized object frequently leads to refcount imbalances or double frees.
* **`c8547c74988e` ("usb: gadget: net2280: Fix double free in probe error path")**: The `net2280_probe()` error path called the full `net2280_remove()` function, which dropped a gadget reference, and then explicitly called `kfree(dev)`. This resulted in a double free. The fix involved removing the redundant cleanup and letting the lifecycle callbacks handle it correctly.
### 3. Refcounting and Pointer Clearing in Error Paths
There is a history of similar bugs in the exact same file (`drivers/usb/gadget/legacy/inode.c`) and subsystem where error paths failed to properly balance refcounts or clear stale pointers.
* **`501e38a5531e` ("usb: gadget: clear related members when goto fail")**: In `drivers/usb/gadget/legacy/inode.c`, the `dev_config()` error path left stale pointers in the `dev` struct, leading to a Use-After-Free. The fix was to manually clear `dev->config`, `dev->hs_config`, and `dev->dev` under the `fail:` label, which is identical to your proposed strategy of clearing `gadget->ep0->driver_data` and `dev->gadget`.
* **`30adce93d5c4` ("usb: gadget: f_printer: take kref only for successful open")**: Fixed a bug where `printer_open()` incremented a `kref` regardless of whether the open succeeded or failed. Because VFS doesn't call `->release()` on a failed open, the reference was leaked. The fix was to only take the reference on the successful path.
### Conclusion
Your proposed fix strategy—removing the call to `gadgetfs_unbind()` and replacing it with manual cleanup (freeing `dev->req` and clearing the gadget data pointers)—is exactly the right approach. It perfectly aligns with established kernel idioms for error path handling by ensuring that only the resources actually allocated by `gadgetfs_bind()` prior to the failure are cleaned up, thus preventing the unbalanced `put_dev()` that causes the Use-After-Free.
|
| 135/2 |
2026/07/31 06:43 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 11242
output: 35
thoughts: 230
Thoughts: **Analyzing Potential Use-After-Free Vulnerabilities in USB Gadget Legacy Code**
Okay, so we've got a use-after-free situation, specifically within the USB gadget legacy code. This issue centers around an error path in a `bind` function (`gadgetfs_bind`) incorrectly calling an `unbind` function (`gadgetfs_unbind`), which then releases a reference that was never actually acquired in the first place. That's a classic memory management problem, and finding similar patterns is key.
My immediate thought is to zero in on potential regressions or similar issues within the same subsystem. That means focusing on the `drivers/usb/gadget/legacy/` directory and anything related to USB gadget functionality. Specifically, that troublesome file `drivers/usb/gadget/legacy/inode.c` is where the bug resides.
To find more of these, I'll leverage `git-log`. I need to look for commits that touch files in those directories and include keywords related to the problem. Let's start with a focused search. Keywords like "refcount", "use-after-free", "unbind", "bind", and "error path" should be a good starting point. To make this manageable, I'll limit the search to the past three years. This way, I can focus on recent history for similar problems.
First, I should search for commits specifically touching `drivers/usb/gadget/legacy/inode.c`. That's the most direct starting point.
|
| 136/2 |
2026/07/31 06:43 |
tool |
git-log |
0m
Args: map[PathPrefix:drivers/usb/gadget/legacy/inode.c Since:3 years]
Results: map[Output:bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
57db9d428ba5 convert gadgetfs
b65e3b11e923 gadgetfs: switch to simple_remove_by_name()
f99b3917789d fs: rename generic_delete_inode() and generic_drop_inode()
bad356bb50e6 functionfs, gadgetfs: use simple_recursive_removal()
bd3cf1a9396e USB: gadget: Replace deprecated strncpy() with strscpy()
5b6dc50e9ed8 USB: gadget: Use str_enable_disable-like helpers
cb787f4ac0c2 [tree-wide] finally take no_llseek out
69f73ca33d6b legacy: convert to new timestamp accessors
]
|
| 137/2 |
2026/07/31 06:43 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 12077
output: 39
thoughts: 43
Thoughts: Okay, here's my summary, framed as my internal thought process:
**USB Gadget Driver Analysis**
Alright, looking at these commits in `drivers/usb/gadget/legacy/inode.c`, it seems like it's primarily refactoring. That's a good starting point, but refactoring often exposes latent issues or uncovers underlying architectural weaknesses. My gut says it's time to broaden the search. I should really check the entire `drivers/usb/gadget/` directory more thoroughly. These types of changes often indicate that there might be some broader issues lurking, maybe in other aspects of the gadget driver implementation. Let's see if we can find some other code that would benefit from this kind of review. There's a good chance this reveals some common, systemic flaws.
|
| 138/2 |
2026/07/31 06:44 |
tool |
git-log |
0m
Args: map[MessageRegexps:[refcount] PathPrefix:drivers/usb/gadget/ Since:3 years]
Results: map[Output:5650c18d93a1 usb: gadget: f_midi: cancel pending IN work before freeing the midi object
]
|
| 139/2 |
2026/07/31 06:44 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 12370
output: 42
thoughts: 27
Thoughts: Here's my thought process, summarized as you requested:
**Navigating a Potential Memory Corruption Issue**
Okay, so I'm suspecting we might have a memory corruption issue, likely something related to a use-after-free vulnerability, or possibly a related problem in how resources are managed after their release. To start my investigation, I'm going to leverage my existing knowledge of common memory safety issues, and begin by searching for some specific keywords and patterns. Let's start with a focused search. I'll include terms like "use-after-free" and "UAF," as those are the most obvious flags. It's likely an error path might be involved, so I will add that term as well. Finally, because the issue could be around unbinding resources, I'll search for "unbind" as that also gives useful context. Hopefully, this initial targeting will help narrow down the problem quickly. I'll need to then analyze the results and see if any code snippets or log entries jump out at me.
|
| 140/2 |
2026/07/31 06:44 |
tool |
git-log |
0m
Args: map[MessageRegexps:[use-after-free] PathPrefix:drivers/usb/gadget/ Since:3 years]
Results: map[Output:5650c18d93a1 usb: gadget: f_midi: cancel pending IN work before freeing the midi object
0583f2fbf8f8 usb: gadget: udc: bdc: free IRQ and drain func_wake_notify before teardown
79e2d75725c8 usb: gadget: f_tcm: synchronize delayed set_alt with teardown
67e511d2989e usb: gadget: udc: Fix use-after-free in gadget_match_driver
30adce93d5c4 usb: gadget: f_printer: take kref only for successful open
2796646f6d89 usb: gadget: f_fs: serialize DMABUF cancel against request completion
eba2936bbe6b usb: gadget: uvc: fix NULL pointer dereference during unbind race
0d6c8144ca4d usb: gadget: f_ncm: Fix atomic context locking issue
56a512a9b410 usb: gadget: f_ncm: align net_device lifecycle with bind/unbind
baeb66fbd420 usb: gadget: udc: fix use-after-free in usb_gadget_state_work
]
|
| 141/2 |
2026/07/31 06:44 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 12963
output: 25
thoughts: 31
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm already deep in the weeds of kernel development:
**Analyzing a USB Gadget Driver Change**
Right, let's take a look at commit `30adce93d5c4`, specifically the change related to the USB gadget's `f_printer` function, and how it handles the reference count (`kref`) during the `open` operation. My gut feeling is this is likely something subtle, potentially related to resource management and preventing a double-free or a similar memory leak. The phrase "take kref only for successful open" immediately flags that this isn't a simple increment-on-open/decrement-on-close pattern. It strongly suggests a more nuanced approach, maybe to avoid holding a reference count when an `open` call fails for some reason. Gotta dig into the code and see what conditions are considered a successful open, and if any other related functions are affected, to fully grok the context. This could be addressing a race condition or a potential use-after-free issue. Time to dive into the diff.
|
| 142/2 |
2026/07/31 06:44 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 30adce93d5c4a5a1ec29d9249e3fdfcc391d406b
Author: Xu Rao <raoxu@uniontech.com>
Date: Fri Jun 26 14:46:17 2026 +0800
usb: gadget: f_printer: take kref only for successful open
printer_open() returns -EBUSY when the character device is already
open, but it increments dev->kref regardless of the return value. VFS
does not call ->release() for a failed open, so every rejected second
open permanently leaks one reference.
Move kref_get() into the successful-open branch.
Fixes: e8d5f92b8d30 ("usb: gadget: function: printer: fix use-after-free in __lock_acquire")
Cc: stable <stable@kernel.org>
Signed-off-by: Xu Rao <raoxu@uniontech.com>
Link: https://patch.msgid.link/80295742B820DA9B+20260626064617.4090626-1-raoxu@uniontech.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/function/f_printer.c b/drivers/usb/gadget/function/f_printer.c
index e4f7828ae75d..837f753d0cae 100644
--- a/drivers/usb/gadget/function/f_printer.c
+++ b/drivers/usb/gadget/function/f_printer.c
@@ -363,12 +363,11 @@ printer_open(struct inode *inode, struct file *fd)
ret = 0;
/* Change the printer status to show that it's on-line. */
dev->printer_status |= PRINTER_SELECTED;
+ kref_get(&dev->kref);
}
spin_unlock_irqrestore(&dev->lock, flags);
- kref_get(&dev->kref);
-
return ret;
}
]
|
| 143/2 |
2026/07/31 06:44 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 13842
output: 27
thoughts: 51
Thoughts: Okay, here's my take on those thoughts, framed as my own reasoning:
**Analyzing a Potential Refcounting Issue**
Alright, this looks like we've got a refcounting bug lurking in the error handling of the `open` function. That's never good, and we need to nail this down fast. The symptoms likely involve a resource being released prematurely, leading to a subsequent use-after-free issue.
To get a clearer picture, I should probably examine commit `67e511d2989e usb: gadget: udc: Fix use-after-free in gadget_match_driver`. That specific commit description is screaming "related problem" at me. It probably addresses a similar issue in a different part of the codebase, which would give me useful hints regarding potential underlying causes or a similar pattern that I can leverage to understand the problem better. I'll need to see how they approached the fix there. From there I can determine how this scenario relates.
|
| 144/2 |
2026/07/31 06:44 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 67e511d2989eb1c8c588b599ce2fcc6bb8e6f7ea
Author: Jimmy Hu <hhhuuu@google.com>
Date: Thu Jun 25 15:37:04 2026 +0800
usb: gadget: udc: Fix use-after-free in gadget_match_driver
The udc structure acts as the management structure for the gadget,
but their lifecycles are decoupled. A race condition exists where
usb_del_gadget() frees the udc memory (e.g., via mode-switch work)
while gadget_match_driver() concurrently accesses the freed udc memory
(e.g., via configfs), causing a Use-After-Free (UAF) that triggers a
NULL pointer dereference when the freed memory is zeroed:
[39430.908615][ T1171] Unable to handle kernel NULL pointer dereference at virtual address 0000000000000000
[39430.911397][ T1171] pc : __pi_strcmp+0x20/0x140
[39430.911441][ T1171] lr : gadget_match_driver+0x34/0x60
...
[39430.911890][ T1171] usb_gadget_register_driver_owner+0x50/0xf8
[39430.911910][ T1171] gadget_dev_desc_UDC_store+0xf4/0x140
[39430.931308][ T1171] configfs_write_iter+0xec/0x134
[39430.957058][ T1171] Workqueue: events_freezable __dwc3_set_mode
[39430.957287][ T1171] dwc3_gadget_exit+0x34/0x8c
[39430.957304][ T1171] __dwc3_set_mode+0xc0/0x664
Fix this by ensuring the udc structure remains allocated until the
gadget is released. To achieve this, introduce a new
usb_gadget_release() routine to the core. When the gadget is added,
usb_add_gadget() stores the gadget's release routine in the udc
structure and takes a reference to the udc. When the gadget is
released, usb_gadget_release() drops the reference to the udc and
then calls the gadget's release routine.
Suggested-by: Alan Stern <stern@rowland.harvard.edu>
Cc: stable <stable@kernel.org>
Signed-off-by: Jimmy Hu <hhhuuu@google.com>
Reviewed-by: Alan Stern <stern@rowland.harvard.edu>
Link: https://patch.msgid.link/20260625073705.803880-1-hhhuuu@google.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/udc/core.c b/drivers/usb/gadget/udc/core.c
index 60340ff9edbf..f6da12b553a0 100644
--- a/drivers/usb/gadget/udc/core.c
+++ b/drivers/usb/gadget/udc/core.c
@@ -31,8 +31,9 @@ static const struct bus_type gadget_bus_type;
/**
* struct usb_udc - describes one usb device controller
* @driver: the gadget driver pointer. For use by the class code
- * @dev: the child device to the actual controller
* @gadget: the gadget. For use by the class code
+ * @gadget_release: the gadget's release routine
+ * @dev: the child device to the actual controller
* @list: for use by the udc class driver
* @vbus: for udcs who care about vbus status, this value is real vbus status;
* for udcs who do not care about vbus status, this value is always true
@@ -53,6 +54,7 @@ static const struct bus_type gadget_bus_type;
struct usb_udc {
struct usb_gadget_driver *driver;
struct usb_gadget *gadget;
+ void (*gadget_release)(struct device *dev);
struct device dev;
struct list_head list;
bool vbus;
@@ -1362,6 +1364,17 @@ static void usb_udc_nop_release(struct device *dev)
dev_vdbg(dev, "%s\n", __func__);
}
+static void usb_gadget_release(struct device *dev)
+{
+ struct usb_gadget *gadget = dev_to_usb_gadget(dev);
+ struct usb_udc *udc = gadget->udc;
+ /* Cache the gadget's release routine to prevent UAF */
+ void (*release)(struct device *dev) = udc->gadget_release;
+
+ put_device(&udc->dev);
+ release(dev);
+}
+
/**
* usb_initialize_gadget - initialize a gadget and its embedded struct device
* @parent: the parent device to this udc. Usually the controller driver's
@@ -1418,6 +1431,14 @@ int usb_add_gadget(struct usb_gadget *gadget)
mutex_init(&udc->connect_lock);
udc->started = false;
+ /*
+ * Align decoupled lifecycles: take a UDC reference to ensure it
+ * remains allocated until the gadget is released, requiring an
+ * override of the gadget's release routine to drop it.
+ */
+ udc->gadget_release = gadget->dev.release;
+ gadget->dev.release = usb_gadget_release;
+ get_device(&udc->dev);
mutex_lock(&udc_lock);
list_add_tail(&udc->list, &udc_list);
@@ -1462,6 +1483,12 @@ int usb_add_gadget(struct usb_gadget *gadget)
mutex_lock(&udc_lock);
list_del(&udc->list);
mutex_unlock(&udc_lock);
+ /*
+ * Revert the override and drop the UDC reference to prevent
+ * leaking the UDC if the gadget was statically allocated.
+ */
+ gadget->dev.release = udc->gadget_release;
+ put_device(&udc->dev);
err_put_udc:
put_device(&udc->dev);
]
|
| 145/2 |
2026/07/31 06:44 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 15937
output: 24
thoughts: 45
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Lifecycle Decoupling Bug Identified**
Alright, this feels like a classic lifecycle decoupling bug rearing its ugly head. The initial assessment immediately flagged it; that specific phrasing always sets off alarm bells in my head. My gut tells me this is related to something being freed prematurely, leading to a subsequent access of that memory region, resulting in undefined behavior or, worse, a crash.
My next step is clear: let's dive straight into the code. The commit hash, `baeb66fbd420 usb: gadget: udc: fix use-after-free in usb_gadget_state_work`, is our primary focus. That commit message hints directly at the problem, so it's probably the most relevant fix. I'll need to carefully examine the before-and-after of that specific change, focusing on how the `usb_gadget_state_work` function interacts with device object lifecycles, and which resources it accesses. I anticipate this will be a matter of understanding how that USB gadget state machine manages its internal data structures, and how proper reference counting, or careful synchronization, was introduced to fix the race condition.
|
| 146/2 |
2026/07/31 06:44 |
tool |
git-show |
0m
Args:
Results: map[Output:commit baeb66fbd4201d1c4325074e78b1f557dff89b5b
Author: Jimmy Hu <hhhuuu@google.com>
Date: Thu Oct 23 05:49:45 2025 +0000
usb: gadget: udc: fix use-after-free in usb_gadget_state_work
A race condition during gadget teardown can lead to a use-after-free
in usb_gadget_state_work(), as reported by KASAN:
BUG: KASAN: invalid-access in sysfs_notify+0x2c/0xd0
Workqueue: events usb_gadget_state_work
The fundamental race occurs because a concurrent event (e.g., an
interrupt) can call usb_gadget_set_state() and schedule gadget->work
at any time during the cleanup process in usb_del_gadget().
Commit 399a45e5237c ("usb: gadget: core: flush gadget workqueue after
device removal") attempted to fix this by moving flush_work() to after
device_del(). However, this does not fully solve the race, as a new
work item can still be scheduled *after* flush_work() completes but
before the gadget's memory is freed, leading to the same use-after-free.
This patch fixes the race condition robustly by introducing a 'teardown'
flag and a 'state_lock' spinlock to the usb_gadget struct. The flag is
set during cleanup in usb_del_gadget() *before* calling flush_work() to
prevent any new work from being scheduled once cleanup has commenced.
The scheduling site, usb_gadget_set_state(), now checks this flag under
the lock before queueing the work, thus safely closing the race window.
Fixes: 5702f75375aa9 ("usb: gadget: udc-core: move sysfs_notify() to a workqueue")
Cc: stable <stable@kernel.org>
Signed-off-by: Jimmy Hu <hhhuuu@google.com>
Link: https://patch.msgid.link/20251023054945.233861-1-hhhuuu@google.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/udc/core.c b/drivers/usb/gadget/udc/core.c
index 694653761c44..8dbe79bdc0f9 100644
--- a/drivers/usb/gadget/udc/core.c
+++ b/drivers/usb/gadget/udc/core.c
@@ -1126,8 +1126,13 @@ static void usb_gadget_state_work(struct work_struct *work)
void usb_gadget_set_state(struct usb_gadget *gadget,
enum usb_device_state state)
{
+ unsigned long flags;
+
+ spin_lock_irqsave(&gadget->state_lock, flags);
gadget->state = state;
- schedule_work(&gadget->work);
+ if (!gadget->teardown)
+ schedule_work(&gadget->work);
+ spin_unlock_irqrestore(&gadget->state_lock, flags);
trace_usb_gadget_set_state(gadget, 0);
}
EXPORT_SYMBOL_GPL(usb_gadget_set_state);
@@ -1361,6 +1366,8 @@ static void usb_udc_nop_release(struct device *dev)
void usb_initialize_gadget(struct device *parent, struct usb_gadget *gadget,
void (*release)(struct device *dev))
{
+ spin_lock_init(&gadget->state_lock);
+ gadget->teardown = false;
INIT_WORK(&gadget->work, usb_gadget_state_work);
gadget->dev.parent = parent;
@@ -1535,6 +1542,7 @@ EXPORT_SYMBOL_GPL(usb_add_gadget_udc);
void usb_del_gadget(struct usb_gadget *gadget)
{
struct usb_udc *udc = gadget->udc;
+ unsigned long flags;
if (!udc)
return;
@@ -1548,6 +1556,13 @@ void usb_del_gadget(struct usb_gadget *gadget)
kobject_uevent(&udc->dev.kobj, KOBJ_REMOVE);
sysfs_remove_link(&udc->dev.kobj, "gadget");
device_del(&gadget->dev);
+ /*
+ * Set the teardown flag before flushing the work to prevent new work
+ * from being scheduled while we are cleaning up.
+ */
+ spin_lock_irqsave(&gadget->state_lock, flags);
+ gadget->teardown = true;
+ spin_unlock_irqrestore(&gadget->state_lock, flags);
flush_work(&gadget->work);
ida_free(&gadget_id_numbers, gadget->id_number);
cancel_work_sync(&udc->vbus_work);
diff --git a/include/linux/usb/gadget.h b/include/linux/usb/gadget.h
index 3aaf19e77558..8285b19a25e0 100644
--- a/include/linux/usb/gadget.h
+++ b/include/linux/usb/gadget.h
@@ -376,6 +376,9 @@ struct usb_gadget_ops {
* can handle. The UDC must support this and all slower speeds and lower
* number of lanes.
* @state: the state we are now (attached, suspended, configured, etc)
+ * @state_lock: Spinlock protecting the `state` and `teardown` members.
+ * @teardown: True if the device is undergoing teardown, used to prevent
+ * new work from being scheduled during cleanup.
* @name: Identifies the controller hardware type. Used in diagnostics
* and sometimes configuration.
* @dev: Driver model state for this abstract device.
@@ -451,6 +454,8 @@ struct usb_gadget {
enum usb_ssp_rate max_ssp_rate;
enum usb_device_state state;
+ spinlock_t state_lock;
+ bool teardown;
const char *name;
struct device dev;
unsigned isoch_delay;
]
|
| 147/2 |
2026/07/31 06:44 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 17995
output: 39
thoughts: 36
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Diagnosing a USB Gadget Driver Workqueue Issue**
Right, this smells strongly like a race condition lurking within a workqueue. Given the context, I'm betting it's somewhere in the USB gadget driver code. The symptoms probably manifest as inconsistent behavior, intermittent errors, or even data corruption related to device unbinding or resource cleanup.
Let's drill down. I need to pinpoint where things are going sideways. My gut says the error is happening on the "error path". I'm thinking the unbinding or clean up functions are the best place to start. I'll focus my search on the `drivers/usb/gadget/` directory. I'll search for the keywords "error path," "cleanup," and "unbind" within that directory to try and hone in on the specific code sections handling these operations. That's where the most likely vulnerabilities will be. From there, I can analyze the surrounding code to understand the locking, synchronization, and error handling mechanisms to pinpoint the source of the race.
|
| 148/2 |
2026/07/31 06:44 |
tool |
git-log |
0m
Args: map[MessageRegexps:[error path] PathPrefix:drivers/usb/gadget/ Since:3 years]
Results: map[Output:0583f2fbf8f8 usb: gadget: udc: bdc: free IRQ and drain func_wake_notify before teardown
29a142d3e8b3 USB: gadget: snps-udc: fix device name leak on probe failure
6b874d00c466 USB: gadget: fsl-udc: fix device name leak on probe failure
2796646f6d89 usb: gadget: f_fs: serialize DMABUF cancel against request completion
68aa70648b62 usb: gadget: uvc: hold opts->lock across XU walks in uvc_function_bind
c8547c74988e usb: gadget: net2280: Fix double free in probe error path
2c863dbbeac7 usb: gadget: f_hid: Add missing error code
782be79e4551 usb: gadget: lpc32xx_udc: fix clock imbalance in error path
62783c30d78a USB: gadget: f_hid: Fix memory leak in hidg_bind error path
725d1f1e338b usb: gadget: pxa25x_udc: Convert to platform remove callback returning void
]
|
| 149/2 |
2026/07/31 06:44 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 18623
output: 27
thoughts: 36
Thoughts: Okay, let's dive into this commit, `62783c30d78a USB: gadget: f_hid: Fix memory leak in hidg_bind error path`. From the title itself, it's clear we're dealing with the USB gadget framework, specifically the HID (Human Interface Device) function driver, and a bug related to memory leaks within the error handling of the `hidg_bind` function. This is a common area for subtle bugs to creep in, especially when dealing with device binding and resource allocation. Let me see how the code addresses the leak in the error paths. I need to understand what resources are being allocated during the binding process and ensure they're being properly freed if something goes wrong. A missing `kfree()` call here, an unreleased reference there... that's where these types of leaks often hide. I'll need to carefully analyze the function's flow, tracing the error paths to pinpoint exactly where the leak occurs and verify that the proposed fix properly addresses it. Good practice and the right use of memory allocators in USB gadget code is often a cause of concern as the code can get pretty dense.
|
| 150/2 |
2026/07/31 06:45 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 62783c30d78aecf9810dae46fd4d11420ad38b74
Author: Yuhao Jiang <danisjiang@gmail.com>
Date: Mon Jun 23 17:48:44 2025 +0800
USB: gadget: f_hid: Fix memory leak in hidg_bind error path
In hidg_bind(), if alloc_workqueue() fails after usb_assign_descriptors()
has successfully allocated the USB descriptors, the current error handling
does not call usb_free_all_descriptors() to free the allocated descriptors,
resulting in a memory leak.
Restructure the error handling by adding proper cleanup labels:
- fail_free_all: cleans up workqueue and descriptors
- fail_free_descs: cleans up descriptors only
- fail: original cleanup for earlier failures
This ensures that allocated resources are properly freed in reverse order
of their allocation, preventing the memory leak when alloc_workqueue() fails.
Fixes: a139c98f760ef ("USB: gadget: f_hid: Add GET_REPORT via userspace IOCTL")
Cc: stable@vger.kernel.org
Signed-off-by: Yuhao Jiang <danisjiang@gmail.com>
Link: https://lore.kernel.org/r/20250623094844.244977-1-danisjiang@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c
index 97a62b926415..8e1d1e884050 100644
--- a/drivers/usb/gadget/function/f_hid.c
+++ b/drivers/usb/gadget/function/f_hid.c
@@ -1278,18 +1278,19 @@ static int hidg_bind(struct usb_configuration *c, struct usb_function *f)
if (!hidg->workqueue) {
status = -ENOMEM;
- goto fail;
+ goto fail_free_descs;
}
/* create char device */
cdev_init(&hidg->cdev, &f_hidg_fops);
status = cdev_device_add(&hidg->cdev, &hidg->dev);
if (status)
- goto fail_free_descs;
+ goto fail_free_all;
return 0;
-fail_free_descs:
+fail_free_all:
destroy_workqueue(hidg->workqueue);
+fail_free_descs:
usb_free_all_descriptors(f);
fail:
ERROR(f->config->cdev, "hidg_bind FAILED\n");
]
|
| 151/2 |
2026/07/31 06:45 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 19698
output: 27
thoughts: 45
Thoughts: Okay, here's my take on those thoughts, framed from my own expert perspective:
**Error Path Cleanup – Standard Procedure**
Alright, another error path cleanup, seems pretty routine. Let's see... the commit title is `c8547c74988e usb: gadget: net2280: Fix double free in probe error path`. Right, that rings a bell. The net2280 gadget driver. Double free in the probe path? That's a classic memory management bug. We've seen this pattern a few times before. I need to dig into the details to understand the specific context, of course, but the potential ramifications are pretty clear – corruption, instability, possibly even a security vulnerability if we're unlucky. This requires a careful inspection of the allocation and deallocation logic within the `probe` function, especially any conditional paths that might lead to a resource being freed twice. I'm going to pull up the patch and the surrounding code, and see where they went wrong.
|
| 152/2 |
2026/07/31 06:45 |
tool |
git-show |
0m
Args:
Results: map[Output:commit c8547c74988e0b5f4cbb1b895e2a57aae084f070
Author: Guangshuo Li <lgs201920130244@gmail.com>
Date: Mon Apr 27 23:36:51 2026 +0800
usb: gadget: net2280: Fix double free in probe error path
usb_initialize_gadget() installs gadget_release() as the release
callback for the embedded gadget device. The struct net2280 instance is
therefore released through gadget_release() when the gadget device's last
reference is dropped.
The probe error path calls net2280_remove(), which tears down the
partially initialized device and drops the gadget reference with
usb_put_gadget(). Calling kfree(dev) afterwards can free the same object
again.
Drop the explicit kfree() and let the gadget device release callback
handle the final free. This issue was found by a static analysis tool
I am developing.
Fixes: f770fbec4165 ("USB: UDC: net2280: Fix memory leaks")
Cc: stable <stable@kernel.org>
Signed-off-by: Guangshuo Li <lgs201920130244@gmail.com>
Reviewed-by: Alan Stern <stern@rowland.harvard.edu>
Link: https://patch.msgid.link/20260427153651.337846-1-lgs201920130244@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/udc/net2280.c b/drivers/usb/gadget/udc/net2280.c
index d02765bd49ce..7c5f30cfd24d 100644
--- a/drivers/usb/gadget/udc/net2280.c
+++ b/drivers/usb/gadget/udc/net2280.c
@@ -3790,10 +3790,8 @@ static int net2280_probe(struct pci_dev *pdev, const struct pci_device_id *id)
return 0;
done:
- if (dev) {
+ if (dev)
net2280_remove(pdev);
- kfree(dev);
- }
return retval;
}
]
|
| 153/2 |
2026/07/31 06:45 |
llm |
history-explorer |
5m
Model:
Tokens:
input: 20672
output: 37
thoughts: 49
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Double Free in the Gadgetfs Context**
Alright, this looks like a classic double free issue. I'm seeing `kfree` called after `usb_put_gadget`, which immediately screams memory corruption. We're releasing the same memory region twice, and that's a recipe for disaster in the kernel. This is likely in a gadgetfs context, I'd bet. Let's dig deeper. The likely place to start is the binding routine for the gadget filesystem. I'll search for "gadgetfs_bind" within `drivers/usb/gadget/legacy/inode.c`, as I'd expect that's where device and driver interaction begins in this legacy gadget. That should provide the context for where the double free might be happening, and where the associated memory structures are allocated and released. The call trace should be visible using a debugger, but identifying the callsites of the bind function will at least expose the control flow.
|
| 154/2 |
2026/07/31 06:50 |
tool |
grepper |
0m
Args: map[Expression:gadgetfs_bind PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:drivers/usb/gadget/legacy/inode.c=1666=static struct dev_data *the_device;
drivers/usb/gadget/legacy/inode.c-1667-
drivers/usb/gadget/legacy/inode.c:1668:static int gadgetfs_bind(struct usb_gadget *gadget,
drivers/usb/gadget/legacy/inode.c-1669- struct usb_gadget_driver *driver)
--
drivers/usb/gadget/legacy/inode.c=1746=static struct usb_gadget_driver gadgetfs_driver = {
drivers/usb/gadget/legacy/inode.c-1747- .function = (char *) driver_desc,
drivers/usb/gadget/legacy/inode.c:1748: .bind = gadgetfs_bind,
drivers/usb/gadget/legacy/inode.c-1749- .unbind = gadgetfs_unbind,
--
drivers/usb/gadget/legacy/inode.c=1801=dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
--
drivers/usb/gadget/legacy/inode.c-1875-
drivers/usb/gadget/legacy/inode.c:1876: /* triggers gadgetfs_bind(); then we can enumerate. */
drivers/usb/gadget/legacy/inode.c-1877- spin_unlock_irq (&dev->lock);
]
|
| 155/2 |
2026/07/31 06:50 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 21364
output: 39
thoughts: 14
Thoughts: Okay, let's dive into this. Here's my thought process on dissecting the history of `gadgetfs_bind`:
**Analyzing the Evolution of `gadgetfs_bind`**
Alright, so I need to understand the evolution of `gadgetfs_bind`. My immediate approach will be to leverage the existing tools and knowledge I have. I'm going to want to see the commit history, obviously. That's the bedrock of understanding any code's development. I'll be looking for key events – when it was first introduced, significant changes, refactorings, bug fixes related to its binding behaviour, API changes, and any discussions surrounding its design or purpose. I'll likely use `git log` with appropriate filtering to start. I'll be looking to see if there are any specific commit messages that jump out at me as indicating major design decisions or potential pain points.
Next, I'll consider where `gadgetfs_bind` fits within the broader `gadgetfs` architecture. What does it bind to? Is it a crucial entry point for device configuration? Is there any associated kernel documentation or mailing list discussions that could shed light on its rationale? Knowing how this particular function is meant to work will give me a greater understanding of why certain changes are made.
If I find any interesting changes, I'll dig into the code itself, looking at its interaction with other parts of the gadgetfs system. Are there any dependencies? Potential race conditions or concurrency issues that have been addressed over time? How does it handle errors? Are there any obvious security considerations related to the binding process? I'll probably cross-reference the commit history with any bug reports or mailing list threads to see if they're connected.
I'm hoping to build a clear picture of its history: why it exists, what it does, how it has changed, and what lessons we can glean from its development. I need to be able to understand the function inside and out, from implementation all the way to evolution.
|
| 156/2 |
2026/07/31 06:50 |
tool |
git-log |
0m
Args: map[SourcePath:drivers/usb/gadget/legacy/inode.c SymbolName:gadgetfs_bind]
Results: map[Output:ffe0b3350625 usb: gadget: remove global variable composite in composite.c
765f5b830e54 usb: gadget: defer setting maxpacket till ->setup()
00274921a052 USB: gadget code switches to pr_err() and friends
7489d1494318 USB: gadgetfs cleanups
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 157/2 |
2026/07/31 06:51 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 21967
output: 39
thoughts: 47
Thoughts: Okay, let me think this through.
**Analyzing Git History for Gadgetfs Bind/Unbind Operations**
Right, so I'm trying to get a handle on the recent changes related to `gadgetfs`. I initially thought about using a `git-log` query with the `Since: "3 years"` filter to get a broad view, but then I realized there haven't been any recent commits for `gadgetfs_bind`, which is odd. This suggests that the activity might be elsewhere, or possibly focused on the unbind process. Therefore, I need to shift gears and drill down. It seems prudent to investigate the history of `gadgetfs_unbind` instead. That's where I will start looking for clues. Let's see what that history reveals.
|
| 158/2 |
2026/07/31 06:51 |
tool |
git-log |
0m
Args: map[SourcePath:drivers/usb/gadget/legacy/inode.c SymbolName:gadgetfs_unbind]
Results: map[Output:520b72fc64de USB: gadgetfs: Fix crash caused by inadequate synchronization
441b62c1edb9 USB: replace remaining __FUNCTION__ occurrences
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 159/2 |
2026/07/31 06:51 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 22296
output: 37
thoughts: 12
Thoughts: Here's my take on those thoughts:
**Analyzing the `dev_config` History**
Okay, so I need to understand what's been going on with `dev_config`. It's a key configuration file, so I need to see how it's evolved. Time to delve into the version control history. I want to see when it was created, what changes have been made, and why. Are there any recent modifications that might be causing issues? Perhaps a regression? Or maybe I need to understand how some recent feature was deployed to `dev` first. I'm thinking I'll start with the commit log, filtering by the filename to get a clear picture of its life cycle. From there, I can examine individual commits and compare versions to pinpoint any specific modifications that might be relevant to the current problem, or just to get a good overall context.
|
| 160/2 |
2026/07/31 06:51 |
tool |
git-log |
0m
Args: map[SourcePath:drivers/usb/gadget/legacy/inode.c SymbolName:dev_config]
Results: map[Output:af1969a2d734 USB: gadget: Rename usb_gadget_probe_driver()
501e38a5531e usb: gadget: clear related members when goto fail
89f3594d0de5 usb: gadget: don't release an existing dev->buf
d13cce757954 usb: gadget: legacy: fix redundant initialization warnings
b6e7aeeaf235 USB: gadgetfs: Fix a potential memory leak in 'dev_config()'
5b5e0928f742 lib/vsprintf.c: remove %Z support
890e6c236dcd USB: gadgetfs: remove unnecessary assignment
1c069b057dcf USB: gadgetfs: fix checks of wTotalLength in config descriptors
add333a81a16 USB: gadgetfs: fix use-after-free bug
0994b0a25755 usb: gadgetfs: restrict upper bound on device configuration size
]
|
| 161/2 |
2026/07/31 06:51 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 22780
output: 27
thoughts: 54
Thoughts: Okay, let's dive into these commits.
**Analyzing USB Gadget Driver Vulnerabilities**
Alright, I'm taking a look at `501e38a5531e usb: gadget: clear related members when goto fail` and `add333a81a16 USB: gadgetfs: fix use-after-free bug`. My initial thought is that these are *critical* patches. We're talking about the USB gadget driver, which is a common attack surface. A "goto fail" can be particularly nasty, and a use-after-free situation... well, that’s just asking for trouble.
Let's break it down: The first commit, `501e38a5531e`, suggests a potential resource leak or data corruption issue when the USB gadget driver encounters an error. The phrase "clear related members" suggests that some cleanup is missing in the error handling path. A `goto fail` in error paths often indicates that there might be complex cleanup requirements, and if those aren't meticulously handled, it can lead to memory corruption or resource exhaustion. I'll need to look closely at the control flow around the `goto` to understand *exactly* what's being cleared and why. I'm wondering if the fix addresses a specific race condition or a more general design flaw. I'll want to see how this commit impacts the data structures.
The second commit, `add333a81a16`, immediately flags a potential memory corruption vulnerability. "Use-after-free" is a classic vulnerability that can lead to arbitrary code execution, denial-of-service, or data leaks. The fact that it's in `gadgetfs` is significant because gadgetfs is often exposed to user-space applications. This suggests a potential attack vector from an unprivileged process. My main concern here is understanding the root cause: What's the dangling pointer, how is it freed incorrectly, and how is it later accessed? I need to know the specific context where the pointer is being accessed *after* it's freed. Is there a race condition? Is there an incorrect reference count? I'm going to want to examine the commit in detail to determine the scope of the vulnerability and understand if there's potential for further exploitation. And, of course, I'll be looking at the fix: Does it correctly address the underlying issue, or is it just a band-aid?
My next step is to examine the diffs of these commits in detail. I'll be looking for potential side effects and for a clear understanding of the vulnerability and its fix. I'll also want to see if these commits are part of a larger security initiative within the USB subsystem, and I will be looking for related commits.
|
| 162/2 |
2026/07/31 06:51 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 501e38a5531efbd77d5c73c0ba838a889bfc1d74
Author: Hangyu Hua <hbh25y@gmail.com>
Date: Sat Jan 1 01:21:38 2022 +0800
usb: gadget: clear related members when goto fail
dev->config and dev->hs_config and dev->dev need to be cleaned if
dev_config fails to avoid UAF.
Acked-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: Hangyu Hua <hbh25y@gmail.com>
Link: https://lore.kernel.org/r/20211231172138.7993-3-hbh25y@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index eaad03c0252f..25c8809e0a38 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1875,8 +1875,8 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
value = usb_gadget_probe_driver(&gadgetfs_driver);
if (value != 0) {
- kfree (dev->buf);
- dev->buf = NULL;
+ spin_lock_irq(&dev->lock);
+ goto fail;
} else {
/* at this point "good" hardware has for the first time
* let the USB the host see us. alternatively, if users
@@ -1893,6 +1893,9 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
return value;
fail:
+ dev->config = NULL;
+ dev->hs_config = NULL;
+ dev->dev = NULL;
spin_unlock_irq (&dev->lock);
pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev);
kfree (dev->buf);
]
|
| 163/2 |
2026/07/31 06:51 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 24092
output: 25
thoughts: 42
Thoughts: Okay, here's my interpretation of those thoughts, summarized from my perspective as a seasoned developer:
**Fixing a subtle but critical bug**
Alright, this looks like a cleanup operation in the `dev_config` module's error handling. My gut tells me this could be a point of instability, so I need to make sure this is solid. The real question is: why are we here?
Let's quickly check this commit... I'm recalling something about a fix related to a "use-after-free" bug in the `USB: gadgetfs` subsystem, commit `add333a81a16`. I have to see what this commit addresses because if there was a use-after-free situation, error-handling cleanup becomes even more critical. I want to make sure the fix is correctly implemented. A memory corruption bug in the USB stack is *never* a good thing. I have to see if this cleanup correctly mitigates the consequences of that bug.
|
| 164/2 |
2026/07/31 06:51 |
tool |
git-show |
0m
Args:
Results: map[Output:commit add333a81a16abbd4f106266a2553677a165725f
Author: Alan Stern <stern@rowland.harvard.edu>
Date: Fri Dec 9 15:18:43 2016 -0500
USB: gadgetfs: fix use-after-free bug
Andrey Konovalov reports that fuzz testing with syzkaller causes a
KASAN use-after-free bug report in gadgetfs:
BUG: KASAN: use-after-free in gadgetfs_setup+0x208a/0x20e0 at addr ffff88003dfe5bf2
Read of size 2 by task syz-executor0/22994
CPU: 3 PID: 22994 Comm: syz-executor0 Not tainted 4.9.0-rc7+ #16
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
ffff88006df06a18 ffffffff81f96aba ffffffffe0528500 1ffff1000dbe0cd6
ffffed000dbe0cce ffff88006df068f0 0000000041b58ab3 ffffffff8598b4c8
ffffffff81f96828 1ffff1000dbe0ccd ffff88006df06708 ffff88006df06748
Call Trace:
<IRQ> [ 201.343209] [< inline >] __dump_stack lib/dump_stack.c:15
<IRQ> [ 201.343209] [<ffffffff81f96aba>] dump_stack+0x292/0x398 lib/dump_stack.c:51
[<ffffffff817e4dec>] kasan_object_err+0x1c/0x70 mm/kasan/report.c:159
[< inline >] print_address_description mm/kasan/report.c:197
[<ffffffff817e5080>] kasan_report_error+0x1f0/0x4e0 mm/kasan/report.c:286
[< inline >] kasan_report mm/kasan/report.c:306
[<ffffffff817e562a>] __asan_report_load_n_noabort+0x3a/0x40 mm/kasan/report.c:337
[< inline >] config_buf drivers/usb/gadget/legacy/inode.c:1298
[<ffffffff8322c8fa>] gadgetfs_setup+0x208a/0x20e0 drivers/usb/gadget/legacy/inode.c:1368
[<ffffffff830fdcd0>] dummy_timer+0x11f0/0x36d0 drivers/usb/gadget/udc/dummy_hcd.c:1858
[<ffffffff814807c1>] call_timer_fn+0x241/0x800 kernel/time/timer.c:1308
[< inline >] expire_timers kernel/time/timer.c:1348
[<ffffffff81482de6>] __run_timers+0xa06/0xec0 kernel/time/timer.c:1641
[<ffffffff814832c1>] run_timer_softirq+0x21/0x80 kernel/time/timer.c:1654
[<ffffffff84f4af8b>] __do_softirq+0x2fb/0xb63 kernel/softirq.c:284
The cause of the bug is subtle. The dev_config() routine gets called
twice by the fuzzer. The first time, the user data contains both a
full-speed configuration descriptor and a high-speed config
descriptor, causing dev->hs_config to be set. But it also contains an
invalid device descriptor, so the buffer containing the descriptors is
deallocated and dev_config() returns an error.
The second time dev_config() is called, the user data contains only a
full-speed config descriptor. But dev->hs_config still has the stale
pointer remaining from the first call, causing the routine to think
that there is a valid high-speed config. Later on, when the driver
dereferences the stale pointer to copy that descriptor, we get a
use-after-free access.
The fix is simple: Clear dev->hs_config if the passed-in data does not
contain a high-speed config descriptor.
Signed-off-by: Alan Stern <stern@rowland.harvard.edu>
Reported-by: Andrey Konovalov <andreyknvl@google.com>
Tested-by: Andrey Konovalov <andreyknvl@google.com>
CC: <stable@vger.kernel.org>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 01ed3bc0c3c8..f1ca33942607 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1800,6 +1800,8 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
goto fail;
kbuf += total;
length -= total;
+ } else {
+ dev->hs_config = NULL;
}
/* could support multiple configs, using another encoding! */
]
|
| 165/2 |
2026/07/31 06:51 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 25930
output: 41
thoughts: 43
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Stale Pointer Alert: GadgetFS Error Path Analysis**
Alright, another classic stale pointer situation rearing its head in `dev_config`. This is likely a familiar scenario. My gut tells me this could be bubbling up from a specific error path within the `gadgetfs_bind` function. Time to drill down into `drivers/usb/gadget/legacy/inode.c`. That's where I need to focus my attention, especially on how `gadgetfs_bind` handles errors. Need to see if a reference isn't being properly managed somewhere, possibly leading to a use-after-free or memory corruption. I'll be looking for any instance where a pointer might be left dangling in a failure case. Let's see if we can find it.
|
| 166/2 |
2026/07/31 06:51 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_bind]
Results: map[SourceCode:1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 167/2 |
2026/07/31 06:51 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 26781
output: 41
thoughts: 56
Thoughts: Okay, here's my take on those thoughts, framed as my own reasoning:
**Analyzing the GadgetFS Unbind Bug**
Right, so the core issue seems to be a subtle reference counting problem within `gadgetfs_unbind`. The bug manifests because we're calling that unbind function on an error path, a detail which is always worth scrutinizing. This is classic reference counting madness. The core of it all is that we're dropping a reference to something that we never actually grabbed, specifically within the error handling flow. The potential leak lies specifically within the last statement inside `gadgetfs_unbind`. It looks like `get_dev(dev)` is at the end of the problematic function. The core of this issue is a race condition. It looks like it will happen if `gadgetfs_unbind` is called on the error path. Okay, it's time to dive into that `gadgetfs_unbind` function and see exactly where this errant release is happening. I need to trace the code flow and confirm precisely which reference is being prematurely dropped.
|
| 168/2 |
2026/07/31 06:52 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/usb/gadget/legacy/inode.c Name:gadgetfs_unbind]
Results: map[SourceCode:1639: static void
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
1643:
1644: DBG (dev, "%s\n", __func__);
1645:
1646: spin_lock_irq (&dev->lock);
1647: dev->state = STATE_DEV_UNBOUND;
1648: while (dev->udc_usage > 0) {
1649: spin_unlock_irq(&dev->lock);
1650: usleep_range(1000, 2000);
1651: spin_lock_irq(&dev->lock);
1652: }
1653: spin_unlock_irq (&dev->lock);
1654:
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 169/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 27545
output: 43
thoughts: 92
Thoughts: Okay, here's my take on those thoughts, framed from my expert perspective:
**Debugging a USB Gadget Driver Issue**
Right, so I see the problem. `gadgetfs_unbind` is calling `put_dev(dev)`. That's where the cleanup logic is. The proposed fix, from my understanding, involves a much more targeted approach: manually undoing the initialization steps performed within `gadgetfs_bind`, instead of relying on the full `gadgetfs_unbind` function. That strongly suggests that the unbind function is doing more than just cleanup, potentially leading to undesirable side effects in certain error scenarios.
My next step is to see if this pattern has been addressed elsewhere in the USB gadget subsystem. I'll need to dig through `drivers/usb/gadget/` and look for instances where they've made a conscious decision *not* to call an `unbind`-like function on an error path, but instead opted for manual cleanup logic. I'm specifically looking for cases where they've streamlined error handling by avoiding a potentially heavy-handed cleanup operation. The key will be understanding the specific context of those scenarios and how the chosen solution was justified. This will give me a better understanding of the trade-offs and potential pitfalls of this kind of manual cleanup approach. I want to build a mental map of best practices and see if this is an established pattern or a one-off scenario.
|
| 170/2 |
2026/07/31 06:52 |
tool |
git-log |
0m
Args: map[MessageRegexps:[error path unbind] PathPrefix:drivers/usb/gadget/ Since:3 years]
Results:
|
| 171/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 27990
output: 43
thoughts: 12
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, presented in the first person:
**Navigating the Unknown: My Strategy**
Alright, when facing a potential problem or a complex process, I immediately gravitate towards a disciplined approach. The first thing that comes to mind is to map out the "error path." I need to understand, anticipate, and define *all* the ways this thing can go sideways. What are the failure points? What are the potential exceptions? What data corruption risks are there? Thinking about the error path is crucial because I can design the system's defensive mechanisms proactively, so I can handle any contingency. It's not about being pessimistic; it's about being prepared.
Following closely on this is the "cleanup" phase. It's almost intrinsically linked to error handling. If something goes wrong, how do I cleanly roll back, recover, or at least leave the system in a consistent, non-corrupted state? This isn't just about deleting temporary files; it's about atomicity, transactional behavior, and ensuring data integrity. It’s also about resource management, preventing memory leaks, and restoring the system to a known good state. This has to be a robust and reliable process because there are many ways this step can go wrong if not well thought out.
|
| 172/2 |
2026/07/31 06:52 |
tool |
git-log |
0m
Args: map[MessageRegexps:[error path cleanup] PathPrefix:drivers/usb/gadget/ Since:3 years]
Results: map[Output:2796646f6d89 usb: gadget: f_fs: serialize DMABUF cancel against request completion
62783c30d78a USB: gadget: f_hid: Fix memory leak in hidg_bind error path
]
|
| 173/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 28393
output: 44
thoughts: 13
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, and delivered as a first-person summary:
**Thinking Through Error Handling and Resource Management**
Alright, I'm at a point in the design where I need to think seriously about robustifying this system. Specifically, I'm considering how to handle potential failures and ensuring that I'm not leaking resources. "Error path" immediately comes to mind. This isn't just about throwing exceptions or returning error codes; it's about the entire *strategy* for what happens when something goes wrong. How do I gracefully unwind the stack? How do I ensure that partially completed operations don't leave the system in an inconsistent state? What are the recovery mechanisms? I need to map out every possible failure scenario and have a clear, well-defined process for handling each one.
Then, linked to this, is "refcount." This brings me to resource management. I know that naive approaches to allocation and deallocation can be incredibly fragile, especially in complex multi-threaded environments. I need to make sure that I'm implementing proper garbage collection, or using smart pointers, or some other mechanism to accurately keep track of all the resources used. I should be able to rely on that approach to avoid leaks and double frees. I'm definitely thinking about memory, but this also applies to file handles, network connections, mutexes, and any other finite resource. Essentially, how can I guarantee that every resource is allocated and deallocated correctly, regardless of whether the happy path is hit or an error is encountered? It's all connected. Error handling and resource management are two sides of the same coin in a robust system.
|
| 174/2 |
2026/07/31 06:52 |
tool |
git-log |
0m
Args: map[MessageRegexps:[error path refcount] PathPrefix:drivers/usb/gadget/ Since:3 years]
Results:
|
| 175/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 28812
output: 43
thoughts: 12
Thoughts: Okay, here's my attempt at summarizing those thoughts from an expert's perspective, in the first person:
**Navigating the Technical Landscape**
Right, let's see, what's the best approach here? I need to think about how to address potential problems. "Error path" – that's a good starting point. I need to consider all the ways things could go wrong, all the edge cases and unexpected inputs. I should map out the different failure scenarios, right down to the root cause. This includes not just the obvious ones but the more obscure ones that can really trip you up. A robust system needs to handle those gracefully. Then, I should think about "reference". This might mean: how something points or is pointed at. Is the error a problem of scope or source of a call or return? This could also relate to the external sources the system relies on, the documentation, the test results, or the specification documents. I'll need to double check those. I need to trace the connections and dependencies. A clear mental model of the system's references is essential. Both ideas are likely to be related, I just need to investigate the links, the commonalities, and the best way to leverage both concepts to arrive at a solution.
|
| 176/2 |
2026/07/31 06:52 |
tool |
git-log |
0m
Args: map[MessageRegexps:[error path reference] PathPrefix:drivers/usb/gadget/ Since:3 years]
Results: map[Output:0583f2fbf8f8 usb: gadget: udc: bdc: free IRQ and drain func_wake_notify before teardown
2796646f6d89 usb: gadget: f_fs: serialize DMABUF cancel against request completion
68aa70648b62 usb: gadget: uvc: hold opts->lock across XU walks in uvc_function_bind
c8547c74988e usb: gadget: net2280: Fix double free in probe error path
782be79e4551 usb: gadget: lpc32xx_udc: fix clock imbalance in error path
]
|
| 177/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 29301
output: 26
thoughts: 36
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating a USB Gadget Driver Bug**
Right, let's dive into this commit: `782be79e4551 usb: gadget: lpc32xx_udc: fix clock imbalance in error path`. Sounds like a classic clocking issue in the error handling of a USB gadget driver. LPC32xx, that takes me back... it's been a while, but I know that architecture well enough. Clock imbalances in USB drivers are notorious – can lead to all sorts of intermittent failures, data corruption, and generally infuriating debugging sessions. I'd wager this "error path" is likely a situation where a USB transaction gets interrupted, or a device is unplugged mid-transfer, and the clocking isn't gracefully managed. Probably some resource release, or lack thereof. Let's dig in and see if my hunch is right. I’m thinking there is a good chance that this fix involves proper clock gating, or perhaps a more refined clock request/release sequence within those error handling routines. I’m interested to see how they addressed the imbalance. I’m thinking this looks like a good one to review!
|
| 178/2 |
2026/07/31 06:52 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 782be79e4551550d7a82b1957fc0f7347e6d461f
Author: Johan Hovold <johan@kernel.org>
Date: Thu Dec 18 16:35:15 2025 +0100
usb: gadget: lpc32xx_udc: fix clock imbalance in error path
A recent change fixing a device reference leak introduced a clock
imbalance by reusing an error path so that the clock may be disabled
before having been enabled.
Note that the clock framework allows for passing in NULL clocks so there
is no risk for a NULL pointer dereference.
Also drop the bogus I2C client NULL check added by the offending commit
as the pointer has already been verified to be non-NULL.
Fixes: c84117912bdd ("USB: lpc32xx_udc: Fix error handling in probe")
Cc: stable@vger.kernel.org
Cc: Ma Ke <make24@iscas.ac.cn>
Signed-off-by: Johan Hovold <johan@kernel.org>
Reviewed-by: Vladimir Zapolskiy <vz@mleia.com>
Link: https://patch.msgid.link/20251218153519.19453-2-johan@kernel.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/udc/lpc32xx_udc.c b/drivers/usb/gadget/udc/lpc32xx_udc.c
index 73c0f28a8585..a962d4294fbe 100644
--- a/drivers/usb/gadget/udc/lpc32xx_udc.c
+++ b/drivers/usb/gadget/udc/lpc32xx_udc.c
@@ -3020,7 +3020,7 @@ static int lpc32xx_udc_probe(struct platform_device *pdev)
pdev->dev.dma_mask = &lpc32xx_usbd_dmamask;
retval = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
if (retval)
- goto i2c_fail;
+ goto err_put_client;
udc->board = &lpc32xx_usbddata;
@@ -3040,7 +3040,7 @@ static int lpc32xx_udc_probe(struct platform_device *pdev)
udc->udp_irq[i] = platform_get_irq(pdev, i);
if (udc->udp_irq[i] < 0) {
retval = udc->udp_irq[i];
- goto i2c_fail;
+ goto err_put_client;
}
}
@@ -3048,7 +3048,7 @@ static int lpc32xx_udc_probe(struct platform_device *pdev)
if (IS_ERR(udc->udp_baseaddr)) {
dev_err(udc->dev, "IO map failure\n");
retval = PTR_ERR(udc->udp_baseaddr);
- goto i2c_fail;
+ goto err_put_client;
}
/* Get USB device clock */
@@ -3056,14 +3056,14 @@ static int lpc32xx_udc_probe(struct platform_device *pdev)
if (IS_ERR(udc->usb_slv_clk)) {
dev_err(udc->dev, "failed to acquire USB device clock\n");
retval = PTR_ERR(udc->usb_slv_clk);
- goto i2c_fail;
+ goto err_put_client;
}
/* Enable USB device clock */
retval = clk_prepare_enable(udc->usb_slv_clk);
if (retval < 0) {
dev_err(udc->dev, "failed to start USB device clock\n");
- goto i2c_fail;
+ goto err_put_client;
}
/* Setup deferred workqueue data */
@@ -3165,9 +3165,10 @@ static int lpc32xx_udc_probe(struct platform_device *pdev)
dma_free_coherent(&pdev->dev, UDCA_BUFF_SIZE,
udc->udca_v_base, udc->udca_p_base);
i2c_fail:
- if (udc->isp1301_i2c_client)
- put_device(&udc->isp1301_i2c_client->dev);
clk_disable_unprepare(udc->usb_slv_clk);
+err_put_client:
+ put_device(&udc->isp1301_i2c_client->dev);
+
dev_err(udc->dev, "%s probe failed, %d\n", driver_name, retval);
return retval;
@@ -3195,10 +3196,9 @@ static void lpc32xx_udc_remove(struct platform_device *pdev)
dma_free_coherent(&pdev->dev, UDCA_BUFF_SIZE,
udc->udca_v_base, udc->udca_p_base);
- if (udc->isp1301_i2c_client)
- put_device(&udc->isp1301_i2c_client->dev);
-
clk_disable_unprepare(udc->usb_slv_clk);
+
+ put_device(&udc->isp1301_i2c_client->dev);
}
#ifdef CONFIG_PM
]
|
| 179/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 31184
output: 29
thoughts: 33
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Standard Error Path Cleanup - Nothing New Here**
Alright, another error path cleanup with a `goto` label construct. Seen this a thousand times. Standard operating procedure in the kernel, ensuring resources are properly released when things go sideways. No surprises there. But, let's see if this is something worth digging deeper into. I don't see anything immediately amiss. However, since this is a `gadgetfs` change, and I have had some experience working in that area, I should do my due diligence. Best to check the recent history and how this fix ties in with other changes. Let's see... I'll pull up the git log and search for commits mentioning "gadgetfs_bind" across the entire kernel. This will give me a broader view of the context surrounding this fix. It'll reveal any recent refactoring efforts or related bug reports that this might address. Hopefully, the surrounding commits offer enough context to feel confident in the change.
|
| 180/2 |
2026/07/31 06:52 |
tool |
git-log |
0m
Args: map[MessageRegexps:[gadgetfs_bind] Since:3 years]
Results:
|
| 181/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 31481
output: 29
thoughts: 16
Thoughts: Here's my thought process, summarized as you requested:
**Investigating a Potential Issue with Gadgetfs Unbinding**
Okay, so I'm trying to track down something specific related to `gadgetfs`. It's likely a tricky issue, and my first instinct is to dive into the git history. The easiest way to do that is to start with a targeted search. I'm going to punch in `"gadgetfs_unbind"` into the `git log` to hopefully uncover any commits that touch on that particular function. I'm expecting this function, if it's the root cause, to have a trail. I want to see when it was added, how it was used, any bugs or fixes associated with it. Hopefully, this search will provide valuable insights into any related issues or changes. From there, I can analyze the commit messages and code diffs to see if I can understand the nature of any related problems. This is my go-to approach for diving deep into a specific area within a large project.
|
| 182/2 |
2026/07/31 06:52 |
tool |
git-log |
0m
Args: map[MessageRegexps:[gadgetfs_unbind] Since:3 years]
Results:
|
| 183/2 |
2026/07/31 06:52 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 31754
output: 27
thoughts: 14
Thoughts: Okay, here's my attempt at summarizing that thought process, tailored for an expert audience:
**Investigating "gadgetfs" in the Git History**
Alright, so I need to dig into something related to "gadgetfs." The first step, naturally, is to go straight to the source: the project's Git history. "gadgetfs" is a pretty specific term, so a simple `git log` should get me pointed in the right direction, or at least help me establish its provenance. I'm expecting this search to be relatively precise, and if there are too many results I'll be prepared to refine it with more specific search terms like author, date range, or context (e.g., commit messages containing "gadgetfs" *and* "USB" or "kernel"). Let's get to work and see what the log reveals.
|
| 184/2 |
2026/07/31 06:52 |
tool |
git-log |
0m
Args: map[MessageRegexps:[gadgetfs] Since:3 years]
Results: map[Output:4e036c10e7f4 usb: gadget: f_fs: copy only received bytes on short ep0 read
57db9d428ba5 convert gadgetfs
b65e3b11e923 gadgetfs: switch to simple_remove_by_name()
bad356bb50e6 functionfs, gadgetfs: use simple_recursive_removal()
e8033bde451e usb: raw-gadget: properly handle interrupted requests
fc85c59b85d1 usb: gadgetfs: return USB_GADGET_DELAYED_STATUS from setup()
3551ff7c5cff usb: gadget: clarify usage of USB_GADGET_DELAYED_STATUS
]
|
| 185/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 32164
output: 26
thoughts: 35
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing the GadgetFS USB Status Handling Patch**
Alright, let's dive into this commit, `fc85c59b85d1 usb: gadgetfs: return USB_GADGET_DELAYED_STATUS from setup()`. My initial thought is, this is likely aimed at addressing some subtle timing issue or race condition within the gadgetfs subsystem. The mention of `USB_GADGET_DELAYED_STATUS` specifically flags my interest. It implies that the standard USB request handling within `setup()` wasn't sufficient, and we need to defer the status signaling under certain conditions.
I'm immediately considering the implications for device enumeration, endpoint configuration, and transaction completion. What scenarios within the gadgetfs driver would necessitate a delayed status return? Perhaps it's related to handling control requests that depend on external resources or require complex state transitions before a definitive acknowledgement can be provided. I need to understand what triggered this change.
I'm also curious about the specific use cases impacted. Is this a performance optimization, a bug fix, or addressing a specific class of device interaction that was previously unreliable? The details in the commit message will be key, but I'm mentally parsing the typical gadgetfs request flows to anticipate what this patch might be affecting. I expect that a delayed status return in `setup()` will probably need careful synchronization to avoid subsequent requests.
|
| 186/2 |
2026/07/31 06:53 |
tool |
git-show |
0m
Args:
Results: map[Output:commit fc85c59b85d111f51b58ecf08485fa74ac5471cd
Author: Andrey Konovalov <andreyknvl@gmail.com>
Date: Mon Aug 28 17:43:04 2023 +0200
usb: gadgetfs: return USB_GADGET_DELAYED_STATUS from setup()
Return USB_GADGET_DELAYED_STATUS from the setup() callback for 0-length
transfers as a workaround to stop some UDC drivers (e.g. dwc3) from
automatically proceeding with the status stage.
This workaround should be removed once all UDC drivers are fixed to
always delay the status stage until a response is queued to EP0.
Reviewed-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: Andrey Konovalov <andreyknvl@gmail.com>
Link: https://lore.kernel.org/r/a8d2b91f9890dc21daa359183e84879ff4525180.1693237258.git.andreyknvl@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index ce9e31f3d26b..6b929defc2d2 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -31,6 +31,12 @@
#include <linux/usb/gadgetfs.h>
#include <linux/usb/gadget.h>
+#include <linux/usb/composite.h> /* for USB_GADGET_DELAYED_STATUS */
+
+/* Undef helpers from linux/usb/composite.h as gadgetfs redefines them */
+#undef DBG
+#undef ERROR
+#undef INFO
/*
@@ -1511,7 +1517,16 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
event->u.setup = *ctrl;
ep0_readable (dev);
spin_unlock (&dev->lock);
- return 0;
+ /*
+ * Return USB_GADGET_DELAYED_STATUS as a workaround to
+ * stop some UDC drivers (e.g. dwc3) from automatically
+ * proceeding with the status stage for 0-length
+ * transfers.
+ * Should be removed once all UDC drivers are fixed to
+ * always delay the status stage until a response is
+ * queued to EP0.
+ */
+ return w_length == 0 ? USB_GADGET_DELAYED_STATUS : 0;
}
}
]
|
| 187/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 33290
output: 45
thoughts: 29
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Investigating Error Paths in `inode.c`**
Okay, time to dig into `drivers/usb/gadget/legacy/inode.c` again. I'm specifically thinking about error handling – that's often where the nastiest surprises hide. I need to comb through this file with a fine-tooth comb, focusing on any potential edge cases in the error paths. I'm looking for anything that might lead to resource leaks, incorrect state transitions, or even worse, security vulnerabilities. Let's see if there are any subtle bugs lurking in those less-trodden branches of the code. This kind of code is easy to write, difficult to get right. Let's see if I can find them.
|
| 188/2 |
2026/07/31 06:53 |
tool |
git-log |
0m
Args: map[MessageRegexps:[error path] PathPrefix:drivers/usb/gadget/legacy/inode.c Since:10 years]
Results:
|
| 189/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 33546
output: 44
thoughts: 22
Thoughts: Okay, here's my understanding, tailored for an expert audience, and written as my own thought process:
**Diving into `drivers/usb/gadget/legacy/inode.c`**
Alright, time to dig in. I'm taking a look at `drivers/usb/gadget/legacy/inode.c`. The task, as I understand it, is to test the word "leak". I'm thinking about how the word "leak" could be used within this file and the contexts that would make sense. This particular file's function is to handle the legacy inode calls within the USB gadget driver, so I'm envisioning the ways that the word "leak" could relate to this. Maybe resource leaks? Data leaks? Memory leaks? Are there any potential vulnerabilities to check? I'll probably start by grepping the file and surrounding source files for the string "leak" to get a better sense of how it's used elsewhere, if at all, and what my targets should be. This seems like a promising starting point for finding something interesting.
|
| 190/2 |
2026/07/31 06:53 |
tool |
git-log |
0m
Args: map[MessageRegexps:[leak] PathPrefix:drivers/usb/gadget/legacy/inode.c Since:10 years]
Results: map[Output:bad356bb50e6 functionfs, gadgetfs: use simple_recursive_removal()
87bed3d7d26c usb: gadget: Fix memleak in gadgetfs_fill_super
b6e7aeeaf235 USB: gadgetfs: Fix a potential memory leak in 'dev_config()'
]
|
| 191/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 33925
output: 25
thoughts: 30
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating a USB Gadgetfs Memory Leak Fix**
Right, let's dive into this commit, `87bed3d7d26c usb: gadget: Fix memleak in gadgetfs_fill_super`. Gadgetfs... always a potential source of interesting little quirks. My gut feeling is this is likely a fairly straightforward issue, but a memory leak in the filesystem context always demands careful attention. You don't want to be the reason some user has a kernel panic when plugging in a USB drive.
"gadgetfs_fill_super"... that's the function responsible for actually mounting the filesystem. So, it's during *initialization*, specifically when the superblock is being populated. Memory leaks here are particularly nasty because they can potentially occur every time the device is plugged in or a new configuration is activated, gradually consuming system resources over time.
I need to quickly see what allocation and deallocation functions are being used in that `gadgetfs_fill_super` code and what the associated control flow is. Are they using the correct wrappers, or maybe a missing `kfree` in a failure path? I'll probably look for missing `put_device()` calls that can lead to a leak of device instances, which are very common in the USB subsystem.
I'm betting the fix probably involves a conditional `kfree()` or `put_device()` in an error handling branch. Let's see if this hunch holds up. I need to understand the exact conditions triggering the leak and confirm the proposed solution properly covers the case. I need to make sure this commit doesn't introduce any new regressions. Time to see what the commit message and code diff tell me.
|
| 192/2 |
2026/07/31 06:53 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 87bed3d7d26c974948a3d6e7176f304b2d41272b
Author: Zhang Qilong <zhangqilong3@huawei.com>
Date: Tue Nov 17 10:16:29 2020 +0800
usb: gadget: Fix memleak in gadgetfs_fill_super
usb_get_gadget_udc_name will alloc memory for CHIP
in "Enomem" branch. we should free it before error
returns to prevent memleak.
Fixes: 175f712119c57 ("usb: gadget: provide interface for legacy gadgets to get UDC name")
Reported-by: Hulk Robot <hulkci@huawei.com>
Acked-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: Zhang Qilong <zhangqilong3@huawei.com>
Link: https://lore.kernel.org/r/20201117021629.1470544-3-zhangqilong3@huawei.com
Cc: stable <stable@vger.kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 1b430b36d0a6..71e7d10dd76b 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -2039,6 +2039,9 @@ gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc)
return 0;
Enomem:
+ kfree(CHIP);
+ CHIP = NULL;
+
return -ENOMEM;
}
]
|
| 193/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 34886
output: 25
thoughts: 32
Thoughts: Here's my take on those thoughts:
**Analyzing a Potential Memory Leak in Gadgetfs**
Okay, so I'm looking at commit `b6e7aeeaf235 USB: gadgetfs: Fix a potential memory leak in 'dev_config()'`. I need to dig into this. "Potential memory leak" always gets my attention; these can be insidious, leading to long-term stability problems, performance degradation, and, frankly, I don't want to deal with a system that's leaking resources. Gadgetfs... right, it's that userspace USB gadget interface. That means this could impact a wide range of devices and applications that rely on it – something to be taken seriously. Let's see what the fix entails and where the leak actually was lurking within `dev_config()`. I need to figure out the specific allocations involved, how the error paths were handled (or *weren't* handled), and what resources were potentially orphaned. Gotta check if it's a double-free, a missed kfree, or something more subtle. Time to dive into the code!
|
| 194/2 |
2026/07/31 06:53 |
tool |
git-show |
0m
Args:
Results: map[Output:commit b6e7aeeaf235901c42ec35de4633c7c69501d303
Author: Christophe JAILLET <christophe.jaillet@wanadoo.fr>
Date: Tue Feb 21 22:33:11 2017 +0100
USB: gadgetfs: Fix a potential memory leak in 'dev_config()'
'kbuf' is allocated just a few lines above using 'memdup_user()'.
If the 'if (dev->buf)' test fails, this memory is never released.
Signed-off-by: Christophe JAILLET <christophe.jaillet@wanadoo.fr>
Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.com>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index a2615d64d07c..0513dfa008e6 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1782,8 +1782,10 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
spin_lock_irq (&dev->lock);
value = -EINVAL;
- if (dev->buf)
+ if (dev->buf) {
+ kfree(kbuf);
goto fail;
+ }
dev->buf = kbuf;
/* full or low speed config */
]
|
| 195/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 35615
output: 48
thoughts: 27
Thoughts: Okay, here's my attempt at summarizing the thought process, as if I were having them:
**Hunting Down a Potential UAF Vulnerability in USB Gadget Code**
Alright, I need to get to the bottom of this potential vulnerability. My gut feeling is leading me towards a "use-after-free" situation, and the `drivers/usb/gadget/legacy/inode.c` file feels like a likely candidate. It’s got a lot of device interaction, memory management, and it's dealing with the legacy portion, which sometimes means it's a bit less scrutinized than the newer code. I’m thinking there might be some nuance there. I'll need to meticulously trace the allocation and deallocation of inodes and related data structures within that code. I’ll need to understand how the USB gadget driver interacts with the file system abstraction. I’ll be paying close attention to any places where a freed inode might be accessed later, particularly within interrupt handlers or concurrent operations. I'll be looking for subtle race conditions or pointer management errors. Time to dive in!
|
| 196/2 |
2026/07/31 06:53 |
tool |
git-log |
0m
Args: map[MessageRegexps:[use-after-free] PathPrefix:drivers/usb/gadget/legacy/inode.c Since:10 years]
Results: map[Output:d18dcfe9860e USB: gadgetfs: Fix race between mounting and unmounting
f16443a034c7 USB: gadgetfs, dummy-hcd, net2280: fix locking for callbacks
8d66db50b2ac drivers, usb: convert ep_data.count from atomic_t to refcount_t
b7ddc981d7b9 drivers, usb: convert dev_data.count from atomic_t to refcount_t
add333a81a16 USB: gadgetfs: fix use-after-free bug
]
|
| 197/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 36070
output: 25
thoughts: 28
Thoughts: Okay, here's my take on those thoughts, framed as an expert's inner monologue:
**Investigating a GadgetFS Race Condition**
Alright, let's dive into this `d18dcfe9860e USB: gadgetfs: Fix race between mounting and unmounting` commit. Immediately, the phrasing "race between mounting and unmounting" sets off a few alarms. This suggests a classic concurrency issue – a situation where multiple threads or processes are trying to access and modify the same resources (in this case, presumably related to the gadgetfs filesystem) at the same time, potentially leading to data corruption, kernel panics, or other undesirable behaviors.
My initial assumption is that we're dealing with a specific scenario within the gadgetfs framework. I'm imagining a situation where a USB gadget is being configured, perhaps with a new function, and there's a delicate dance between the mount and unmount operations of the filesystem that manages the gadget's exposed functionality. The kernel likely needs to ensure that the filesystem is completely initialized before accepting data, or similarly uninitialized prior to unmounting it. This commit is likely addressing a flaw in the locking mechanisms or synchronization primitives employed in gadgetfs, leaving a window for an unsafe operation.
I'll need to dig into the commit itself to understand the specific code paths involved. My first step will be to look at the introduced changes and understand the nature of the lock (mutex, spinlock, etc.) and what it is protecting (data structures, states, critical sections). The patch description is vital here, I must understand exactly the circumstances that trigger the race. From there I'll be looking for any signs of improperly ordered operations, use-after-free conditions (if memory is a factor in the race) or any missing fences or barriers that could lead to memory corruption.
It's likely that a small, overlooked detail in the existing code exposed the race. I'm curious to see what the fix is, and if it introduces any performance overhead. A good fix will minimize the performance impact while correctly ensuring that the mount and unmount operations are fully synchronized. This seems like a common enough failure scenario, and I will be looking to see if the fix is generally applicable, or targeted to a very specific case.
|
| 198/2 |
2026/07/31 06:53 |
tool |
git-show |
0m
Args:
Results: map[Output:commit d18dcfe9860e842f394e37ba01ca9440ab2178f4
Author: Alan Stern <stern@rowland.harvard.edu>
Date: Fri Dec 23 09:59:09 2022 -0500
USB: gadgetfs: Fix race between mounting and unmounting
The syzbot fuzzer and Gerald Lee have identified a use-after-free bug
in the gadgetfs driver, involving processes concurrently mounting and
unmounting the gadgetfs filesystem. In particular, gadgetfs_fill_super()
can race with gadgetfs_kill_sb(), causing the latter to deallocate
the_device while the former is using it. The output from KASAN says,
in part:
BUG: KASAN: use-after-free in instrument_atomic_read_write include/linux/instrumented.h:102 [inline]
BUG: KASAN: use-after-free in atomic_fetch_sub_release include/linux/atomic/atomic-instrumented.h:176 [inline]
BUG: KASAN: use-after-free in __refcount_sub_and_test include/linux/refcount.h:272 [inline]
BUG: KASAN: use-after-free in __refcount_dec_and_test include/linux/refcount.h:315 [inline]
BUG: KASAN: use-after-free in refcount_dec_and_test include/linux/refcount.h:333 [inline]
BUG: KASAN: use-after-free in put_dev drivers/usb/gadget/legacy/inode.c:159 [inline]
BUG: KASAN: use-after-free in gadgetfs_kill_sb+0x33/0x100 drivers/usb/gadget/legacy/inode.c:2086
Write of size 4 at addr ffff8880276d7840 by task syz-executor126/18689
CPU: 0 PID: 18689 Comm: syz-executor126 Not tainted 6.1.0-syzkaller #0
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/26/2022
Call Trace:
<TASK>
...
atomic_fetch_sub_release include/linux/atomic/atomic-instrumented.h:176 [inline]
__refcount_sub_and_test include/linux/refcount.h:272 [inline]
__refcount_dec_and_test include/linux/refcount.h:315 [inline]
refcount_dec_and_test include/linux/refcount.h:333 [inline]
put_dev drivers/usb/gadget/legacy/inode.c:159 [inline]
gadgetfs_kill_sb+0x33/0x100 drivers/usb/gadget/legacy/inode.c:2086
deactivate_locked_super+0xa7/0xf0 fs/super.c:332
vfs_get_super fs/super.c:1190 [inline]
get_tree_single+0xd0/0x160 fs/super.c:1207
vfs_get_tree+0x88/0x270 fs/super.c:1531
vfs_fsconfig_locked fs/fsopen.c:232 [inline]
The simplest solution is to ensure that gadgetfs_fill_super() and
gadgetfs_kill_sb() are serialized by making them both acquire a new
mutex.
Signed-off-by: Alan Stern <stern@rowland.harvard.edu>
Reported-and-tested-by: syzbot+33d7ad66d65044b93f16@syzkaller.appspotmail.com
Reported-and-tested-by: Gerald Lee <sundaywind2004@gmail.com>
Link: https://lore.kernel.org/linux-usb/CAO3qeMVzXDP-JU6v1u5Ags6Q-bb35kg3=C6d04DjzA9ffa5x1g@mail.gmail.com/
Fixes: e5d82a7360d1 ("vfs: Convert gadgetfs to use the new mount API")
CC: <stable@vger.kernel.org>
Link: https://lore.kernel.org/r/Y6XCPXBpn3tmjdCC@rowland.harvard.edu
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 01c3ead7d1b4..d605bc2e7e8f 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -229,6 +229,7 @@ static void put_ep (struct ep_data *data)
*/
static const char *CHIP;
+static DEFINE_MUTEX(sb_mutex); /* Serialize superblock operations */
/*----------------------------------------------------------------------*/
@@ -2010,13 +2011,20 @@ gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc)
{
struct inode *inode;
struct dev_data *dev;
+ int rc;
- if (the_device)
- return -ESRCH;
+ mutex_lock(&sb_mutex);
+
+ if (the_device) {
+ rc = -ESRCH;
+ goto Done;
+ }
CHIP = usb_get_gadget_udc_name();
- if (!CHIP)
- return -ENODEV;
+ if (!CHIP) {
+ rc = -ENODEV;
+ goto Done;
+ }
/* superblock */
sb->s_blocksize = PAGE_SIZE;
@@ -2053,13 +2061,17 @@ gadgetfs_fill_super (struct super_block *sb, struct fs_context *fc)
* from binding to a controller.
*/
the_device = dev;
- return 0;
+ rc = 0;
+ goto Done;
-Enomem:
+ Enomem:
kfree(CHIP);
CHIP = NULL;
+ rc = -ENOMEM;
- return -ENOMEM;
+ Done:
+ mutex_unlock(&sb_mutex);
+ return rc;
}
/* "mount -t gadgetfs path /dev/gadget" ends up here */
@@ -2081,6 +2093,7 @@ static int gadgetfs_init_fs_context(struct fs_context *fc)
static void
gadgetfs_kill_sb (struct super_block *sb)
{
+ mutex_lock(&sb_mutex);
kill_litter_super (sb);
if (the_device) {
put_dev (the_device);
@@ -2088,6 +2101,7 @@ gadgetfs_kill_sb (struct super_block *sb)
}
kfree(CHIP);
CHIP = NULL;
+ mutex_unlock(&sb_mutex);
}
/*----------------------------------------------------------------------*/
]
|
| 199/2 |
2026/07/31 06:53 |
llm |
history-explorer |
0m
Model:
Tokens:
input: 38520
output: 863
thoughts: 1422
Thoughts: **Analyzing the Race Condition Fix in gadgetfs_bind**
Okay, so I'm looking at this proposed fix for the `gadgetfs_bind` race condition, and it's making sense. We've got a use-after-free situation stemming from an unbalanced reference count. The problem, as I see it, is that `gadgetfs_bind` calls `gadgetfs_unbind` on an error, which in turn calls `put_dev(dev)`. However, `get_dev(dev)` is *only* called on success, so the `put_dev` in the error path is premature. The fix - manually undo the initialization steps in the error path, instead of calling a full unbind - is the right direction.
Now, let's look at similar issues I've seen in the USB gadget subsystem to validate this approach. I've found a few commits that illustrate the common patterns here:
* First, `30adce93d5c4`, "usb: gadget: f\_printer: take kref only for successful open". This is relevant because it shows a refcounting issue in an error path, though it's a leak (not a UAF) where the refcount was incremented unconditionally. The solution was to move the `kref_get()` into the success branch, very similar logic.
* Then there's `67e511d2989e`, "usb: gadget: udc: Fix use-after-free in gadget\_match\_driver." This had a race due to memory being freed while still in use, so they took a reference.
* Next up is `62783c30d78a`, "USB: gadget: f\_hid: Fix memory leak in hidg\_bind error path." This is an interesting case because it highlights *exactly* the preferred error handling pattern. It shows manual cleanup with `goto` labels to free resources in reverse order, which is *precisely* what we're aiming for here.
* `c8547c74988e`, "usb: gadget: net2280: Fix double free in probe error path", is critical. It shows the dangers of a full "remove" call in the error path. The `net2280_remove()` dropped a gadget reference that was already handled, leading to a double free. This is a classic anti-pattern that we're trying to avoid!
* `782be79e4551` "usb: gadget: lpc32xx\_udc: fix clock imbalance in error path". This case is about reusing an error path that causes an imbalance.
* `501e38a5531e` "usb: gadget: clear related members when goto fail" this is in the same file as one of the bugs we're fixing (`drivers/usb/gadget/legacy/inode.c`), and fixed a UAF by *specifically* clearing struct members in the error path. This is key: explicit cleanup over generic.
* `87bed3d7d26c` "usb: gadget: Fix memleak in gadgetfs\_fill\_super" is also in the same file and is fixing a memory leak using a specific cleanup.
So, the overarching pattern, as I see it, is that calling a full `unbind` or `remove` function in a `bind` or `probe` error path is a recipe for bugs. These unbind/remove functions are generally designed to handle *fully* initialized objects and don't account for partial initialization, leading to unbalanced refcounts, double frees, and null pointer dereferences. I'm thinking specifically of that `net2280` commit (`c8547c74988e`), which underscores the danger of calling a full cleanup function and then performing *additional* cleanup. This can easily lead to memory corruption.
The correct approach, as demonstrated by the `f_hid` fix (`62783c30d78a`), is to use specific `goto` labels to carefully undo the initialization steps *in reverse order*. This *manual* undoing perfectly aligns with what we're proposing here: freeing the request, and clearing the pointers to ensure everything is well-defined. The `f_printer` fix (`30adce93d5c4`) is another example of a refcounting issue in the error path.
In conclusion, I'm confident that the proposed strategy—of manually undoing the specific initialization steps (like freeing `dev->req` and clearing the pointers) rather than blindly calling `gadgetfs_unbind()`—is the correct approach and aligns perfectly with the established idioms for error path cleanup
|
| 200/1 |
2026/07/31 06:54 |
action |
kernel-scratch-checkouter |
0m
Results: map[KernelScratchSrc:/app/workdir/cache/tmp/tmp2447486768]
|
| 201/1 |
2026/07/31 06:55 |
loop |
|
38m
|
| 202/2 |
2026/07/31 06:55 |
iteration |
0 |
38m
|
| 203/3 |
2026/07/31 06:55 |
agent |
patch-generator |
8m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with creating a fix for a kernel bug.
You will be given a crash report, an initial explanation of the root cause done by another
kernel expert, and a summary of how similar bugs were fixed in the past.
Use the codeeditor tool to do code edits.
Note: you will not see your changes when looking at the code using codesearch tools.
Use the patch-diff tool to review the modifications you applied.
Your final reply should contain explanation of what you did in the patch and why
(details not present in the initial explanation of the bug).
Your fix must not just prevent the given crash, but also be the best fix for the underlying
root cause from the software engineering point of view. There can be several ways to fix the
same bug. Consider alternatives, and pick the best one. For example, additional checks may be
added at different locations/functions, it's usually better to place them earlier in the
execution to avoid multiple checks at various locations later.
Frequently the same coding mistake is done in several locations in the source code.
Check if your fix should be extended/applied to similar cases around to fix other similar bugs.
But don't go too wide, don't try to fix problems kernel-wide, fix similar issues
in the same file only.
If you are changing post-conditions of a function, consider all callers of the functions,
and if they need to be updated to handle new post-conditions. For example, if you make
a function that previously never returned a NULL, return NULL, consider if callers
need to be updated to handle NULL return value.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
==================================================================
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Not tainted syzkaller #1 PREEMPT
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
print_address_description+0xb0/0x238 mm/kasan/report.c:378
print_report+0x68/0x84 mm/kasan/report.c:482
kasan_report+0x8c/0xc4 mm/kasan/report.c:595
__kasan_check_byte+0x3c/0x54 mm/kasan/common.c:574
kasan_check_byte include/linux/kasan.h:402 [inline]
lock_acquire+0xa4/0x364 kernel/locking/lockdep.c:5842
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Allocated by task 5241:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_alloc_info+0x44/0x54 mm/kasan/generic.c:570
poison_kmalloc_redzone mm/kasan/common.c:398 [inline]
__kasan_kmalloc+0x9c/0xb4 mm/kasan/common.c:415
kasan_kmalloc include/linux/kasan.h:263 [inline]
__kmalloc_cache_noprof+0x2e8/0x5ec mm/slub.c:5489
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
dev_new drivers/usb/gadget/legacy/inode.c:176 [inline]
gadgetfs_fill_super+0x19c/0x370 drivers/usb/gadget/legacy/inode.c:2054
vfs_get_super+0xb8/0x148 fs/super.c:1273
get_tree_single+0x30/0x40 fs/super.c:1300
gadgetfs_get_tree+0x28/0x38 drivers/usb/gadget/legacy/inode.c:2085
vfs_get_tree+0x90/0x28c fs/super.c:1700
fc_mount+0x24/0xac fs/namespace.c:1198
do_new_mount_fc fs/namespace.c:3765 [inline]
do_new_mount+0x2a4/0x538 fs/namespace.c:3841
path_mount+0x5f0/0xa88 fs/namespace.c:4161
do_mount+0xe8/0x148 fs/namespace.c:4174
__do_sys_mount fs/namespace.c:4390 [inline]
__se_sys_mount fs/namespace.c:4367 [inline]
__arm64_sys_mount+0x334/0x380 fs/namespace.c:4367
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Freed by task 5331:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_free_info+0x58/0x70 mm/kasan/generic.c:584
poison_slab_object mm/kasan/common.c:253 [inline]
__kasan_slab_free+0x74/0xa4 mm/kasan/common.c:285
kasan_slab_free include/linux/kasan.h:235 [inline]
slab_free_hook mm/slub.c:2677 [inline]
slab_free mm/slub.c:6377 [inline]
kfree+0x188/0x690 mm/slub.c:6692
put_dev+0x8c/0xf8 drivers/usb/gadget/legacy/inode.c:169
dev_release+0x100/0x15c drivers/usb/gadget/legacy/inode.c:1215
__fput+0x338/0x74c fs/file_table.c:512
____fput+0x20/0x30 fs/file_table.c:540
task_work_run+0x1cc/0x25c kernel/task_work.c:233
resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]
__exit_to_user_mode_loop kernel/entry/common.c:70 [inline]
exit_to_user_mode_loop+0x10c/0x17c kernel/entry/common.c:101
__exit_to_user_mode_prepare include/linux/irq-entry-common.h:207 [inline]
syscall_exit_to_user_mode_prepare include/linux/irq-entry-common.h:230 [inline]
arm64_syscall_exit_to_user_mode arch/arm64/kernel/entry-common.c:88 [inline]
el0_svc+0x18c/0x260 arch/arm64/kernel/entry-common.c:737
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
The buggy address belongs to the object at ffff0000dbe16000
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 24 bytes inside of
freed 1024-byte region [ffff0000dbe16000, ffff0000dbe16400)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff0000dbe15000 pfn:0x11be10
head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
flags: 0x5ffc00000000240(workingset|head|node=0|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
raw: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
head: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000003 fffffdffc36f8401 00000000ffffffff 00000000ffffffff
head: ffffffffffffffff 0000000000000000 00000000ffffffff 0000000000000008
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff0000dbe15f00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff0000dbe15f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff0000dbe16000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff0000dbe16080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff0000dbe16100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
------------[ cut here ]------------
UBSAN: array-index-out-of-bounds in /app/workdir/cache/src/3735123449433f9e6f9fb5b55ddd9994cbcf15f0/kernel/locking/qspinlock.h:68:9
index 13031 is out of range for type 'unsigned long[8]'
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
ubsan_epilogue+0x14/0x48 lib/ubsan.c:233
__ubsan_handle_out_of_bounds+0xd0/0xf8 lib/ubsan.c:455
decode_tail kernel/locking/qspinlock.h:68 [inline]
queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
---[ end trace ]---
Unable to handle kernel paging request at virtual address ffff800088b48710
KASAN: probably user-memory-access in range [0x0000000445a43880-0x0000000445a43887]
Mem abort info:
ESR = 0x0000000096000047
EC = 0x25: DABT (current EL), IL = 32 bits
SET = 0, FnV = 0
EA = 0, S1PTW = 0
FSC = 0x07: level 3 translation fault
Data abort info:
ISV = 0, ISS = 0x00000047, ISS2 = 0x00000000
CM = 0, WnR = 1, TnD = 0, TagAccess = 0
GCS = 0, Overlay = 0, DirtyBit = 0
swapper pgtable: 4k pages, 48-bit VAs, pgdp=000000021aeb5000
[ffff800088b48710] pgd=0000000000000000, p4d=10000002211ac003, pud=10000002211ad003, pmd=10000002211b1003, pte=0000000000000000
Internal error: Oops: 0000000096000047 [#1] SMP
Modules linked in:
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
pstate: 834000c5 (Nzcv daIF +PAN -UAO +TCO +DIT -SSBS BTYPE=--)
pc : queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:288
lr : decode_tail kernel/locking/qspinlock.h:68 [inline]
lr : queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
sp : ffff800097c37560
x29: ffff800097c37600 x28: ffff800088b48710 x27: 1fffe00019980afa
x26: 1fffe0001b7c2c00 x25: ffff0001add9f708 x24: dfff800000000000
x23: ffff700012f86eb0 x22: ffff0001add9f700 x21: 1fffe00035bb3ee0
x20: ffff0000ccc057d0 x19: ffff0000dbe16000 x18: 0000000000000000
x17: 3d3d3d3d3d3d3d3d x16: 0000000000000001 x15: 0000000000000000
x14: 0000000000000000 x13: 0000000000000001 x12: 0000000000000004
x11: ffff700011474c6c x10: ffff800088b48700 x9 : ffff800088b48710
x8 : 0000000000000000 x7 : 0000000000000001 x6 : ffff80008048d694
x5 : 0000000000000000 x4 : 0000000000000000 x3 : ffff8000802f6c98
x2 : 0000000000000002 x1 : 0000000000000004 x0 : ffff0001add9f708
Call trace:
queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:291 (P)
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Code: aa1c03e0 968a785a 910022c0 52800081 (f9000396)
---[ end trace 0000000000000000 ]---
----------------
Code disassembly (best guess):
0: aa1c03e0 mov x0, x28
4: 968a785a bl 0xfffffffffa29e16c
8: 910022c0 add x0, x22, #0x8
c: 52800081 mov w1, #0x4 // #4
* 10: f9000396 str x22, [x28] <-- trapping instruction
The explanation of the root cause of the bug is:
The root cause of this KASAN slab-use-after-free is a reference counting bug in the error path of `gadgetfs_bind()` in `drivers/usb/gadget/legacy/inode.c`.
When the gadget driver is being bound, `gadgetfs_bind()` performs several initialization steps. If it succeeds, it takes a reference to the `dev` object by calling `get_dev(dev)` at the very end of the function. This reference is meant to be balanced by a call to `put_dev(dev)` inside `gadgetfs_unbind()` when the driver is eventually unbound.
However, if `gadgetfs_bind()` fails midway (e.g., due to the fault injection causing `activate_ep_files()` to fail), it jumps to the `enomem` label and calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**.
### Detailed Trace
1. **Initialization**: When the gadgetfs is mounted, `gadgetfs_fill_super()` calls `dev_new()`, which initializes the `dev` object with a refcount of `1`.
2. **First Open**: The reproducer opens the `ep0` file (`dummy_udc`). This calls `gadget_dev_open()`, which increments the refcount to `2` via `get_dev(dev)`.
3. **Configuration**: The reproducer writes to the `ep0` file descriptor, triggering `dev_config()`. This parses the descriptors and calls `usb_gadget_register_driver()`, which in turn calls `gadgetfs_bind()`.
4. **Fault Injection**: Inside `gadgetfs_bind()`, `activate_ep_files()` fails due to the injected memory allocation failure.
5. **The Bug**: `gadgetfs_bind()` jumps to the `enomem` label and calls `gadgetfs_unbind()`. `gadgetfs_unbind()` calls `put_dev(dev)`, dropping the refcount to `1`. (It should have remained `2` because `gadgetfs_bind()` never took its reference).
6. **File Close**: The `write()` syscall returns `-ENOMEM`. The reproducer process exits (or closes the file descriptor), triggering `dev_release()`. This calls `put_dev(dev)`, dropping the refcount to `0`. The `dev` object is freed.
7. **Use-After-Free**: The reproducer (or another thread) opens the `ep0` file again. `gadget_dev_open()` is called, which accesses the freed `dev` object via `inode->i_private` to acquire `dev->lock`, resulting in the KASAN slab-use-after-free crash.
### The Fix
Instead of calling `gadgetfs_unbind()` on failure, `gadgetfs_bind()` should manually undo the specific initialization steps it performed before the failure.
Note that `activate_ep_files()` already cleans up after itself if it fails (by calling `destroy_ep_files()`), so we only need to free `dev->req` (if it was allocated) and clear the gadget data pointers.
```c
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,12 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
```
By doing this manual cleanup, we avoid the unbalanced `put_dev(dev)`, prevent `dev->state` from being incorrectly set to `STATE_DEV_UNBOUND` (which would prevent the user from retrying the configuration write), and avoid redundant calls to `destroy_ep_files()`.
Historical context on how similar bugs were fixed in the past:
Based on a review of recent commits in the USB gadget subsystem, the root cause of this bug stems from a well-known anti-pattern: **calling a full `unbind` or `remove` function from within the error path of a `bind` or `probe` function.**
Full cleanup functions typically assume that the object was fully initialized (e.g., all references were taken, all memory was allocated). When invoked on a partially initialized object, they often drop references that were never acquired, free memory that was never allocated, or double-free resources.
Here are the historical patterns and idioms used to fix similar bugs in this subsystem:
### 1. Manual, Step-by-Step Cleanup via `goto` Labels
The standard kernel idiom for error paths is to manually undo exactly the steps that succeeded, in reverse order, rather than calling a monolithic cleanup function.
* **`62783c30d78a` ("USB: gadget: f_hid: Fix memory leak in hidg_bind error path")**: In `hidg_bind()`, an error path failed to free descriptors. The fix restructured the error handling by adding specific `goto` labels (`fail_free_all`, `fail_free_descs`) to manually clean up resources in reverse order of allocation.
* **`782be79e4551` ("usb: gadget: lpc32xx_udc: fix clock imbalance in error path")**: Fixed an issue where an error path disabled a clock that hadn't been enabled yet. The fix introduced proper granular `goto` labels to ensure only initialized resources were cleaned up.
### 2. Avoiding Monolithic Cleanup Functions in Error Paths
Calling a full teardown function on a partially initialized object frequently leads to refcount imbalances or double frees.
* **`c8547c74988e` ("usb: gadget: net2280: Fix double free in probe error path")**: The `net2280_probe()` error path called the full `net2280_remove()` function, which dropped a gadget reference, and then explicitly called `kfree(dev)`. This resulted in a double free. The fix involved removing the redundant cleanup and letting the lifecycle callbacks handle it correctly.
### 3. Refcounting and Pointer Clearing in Error Paths
There is a history of similar bugs in the exact same file (`drivers/usb/gadget/legacy/inode.c`) and subsystem where error paths failed to properly balance refcounts or clear stale pointers.
* **`501e38a5531e` ("usb: gadget: clear related members when goto fail")**: In `drivers/usb/gadget/legacy/inode.c`, the `dev_config()` error path left stale pointers in the `dev` struct, leading to a Use-After-Free. The fix was to manually clear `dev->config`, `dev->hs_config`, and `dev->dev` under the `fail:` label, which is identical to your proposed strategy of clearing `gadget->ep0->driver_data` and `dev->gadget`.
* **`30adce93d5c4` ("usb: gadget: f_printer: take kref only for successful open")**: Fixed a bug where `printer_open()` incremented a `kref` regardless of whether the open succeeded or failed. Because VFS doesn't call `->release()` on a failed open, the reference was leaked. The fix was to only take the reference on the successful path.
### Conclusion
Your proposed fix strategy—removing the call to `gadgetfs_unbind()` and replacing it with manual cleanup (freeing `dev->req` and clearing the gadget data pointers)—is exactly the right approach. It perfectly aligns with established kernel idioms for error path handling by ensuring that only the resources actually allocated by `gadgetfs_bind()` prior to the failure are cleaned up, thus preventing the unbalanced `put_dev()` that causes the Use-After-Free.
Reply: I have applied the fix to `drivers/usb/gadget/legacy/inode.c`.
### Explanation of the Fix
The root cause of the KASAN slab-use-after-free is an unbalanced reference count in the error path of `gadgetfs_bind()`.
When `gadgetfs_bind()` is called, it performs several initialization steps. If it succeeds, it takes a reference to the `dev` object by calling `get_dev(dev)` at the very end of the function. This reference is meant to be balanced by a call to `put_dev(dev)` inside `gadgetfs_unbind()` when the driver is eventually unbound.
However, if `gadgetfs_bind()` fails midway (e.g., due to a memory allocation failure in `usb_ep_alloc_request()` or `activate_ep_files()`), it jumps to the `enomem` label and calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**. This leads to the `dev` object being freed prematurely when the file descriptor is closed, resulting in a Use-After-Free when the file is opened again.
Furthermore, calling `gadgetfs_unbind()` on a partially initialized object is an anti-pattern. `gadgetfs_unbind()` sets `dev->state = STATE_DEV_UNBOUND`, which is incorrect because the device was never fully bound. This incorrect state prevents the user from retrying the configuration write.
To fix this, I replaced the monolithic `gadgetfs_unbind()` call in the `enomem` error path with manual, step-by-step cleanup of exactly the resources that were allocated prior to the failure:
1. If `dev->req` was allocated, it is freed and set to `NULL`.
2. The gadget data pointers (`gadget->ep0->driver_data`, `dev->gadget`, and `set_gadget_data`) are cleared.
Note that `activate_ep_files()` already cleans up after itself if it fails (by calling `destroy_ep_files()`), so we don't need to manually undo its effects in `gadgetfs_bind()`.
This manual cleanup perfectly aligns with established kernel idioms for error path handling. It ensures that only the resources actually allocated by `gadgetfs_bind()` are cleaned up, preventing the unbalanced `put_dev()` and incorrect state changes that caused the Use-After-Free.
|
| 204/4 |
2026/07/31 06:55 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 12565
output: 29
thoughts: 311
Thoughts: **Analyzing a KASAN Slab-Use-After-Free Bug in USB Gadget Driver**
Okay, so I'm looking at a KASAN slab-use-after-free bug, specifically within `__raw_spin_lock_irq` being called from `gadget_dev_open`. That's a pretty nasty one. It looks like the root cause is a reference counting problem, and it's happening during the error handling in `gadgetfs_bind()` within `drivers/usb/gadget/legacy/inode.c`. The problem, as I understand it, is this: `gadgetfs_bind()` has a bug where it calls `gadgetfs_unbind()` on failure. However, `gadgetfs_unbind()` is dropping a reference using `put_dev(dev)` that was *never* actually taken in the first place, because the `get_dev(dev)` call only happens on success. Basically, it's prematurely freeing something it shouldn't be.
The proposed solution seems straightforward enough. Instead of calling `gadgetfs_unbind()` entirely in the `enomem` error path, they're suggesting we manually clean up the allocated resources. Basically, we need to explicitly free the request and clear related pointers when `gadgetfs_bind()` fails due to an out-of-memory error. Specifically, the patch replaces the call to `gadgetfs_unbind(gadget)` with manual cleanup of `dev->req`, the ep0 driver data and sets `dev->gadget` to `NULL`. This looks like a solid fix. I'll need to check the code in `drivers/usb/gadget/legacy/inode.c`, focusing on `gadgetfs_bind()` and `gadgetfs_unbind()` to confirm the reasoning and that the proposed fix is sound. Let's see if this addresses the underlying issue completely or if any corner cases remain.
|
| 205/4 |
2026/07/31 06:55 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadgetfs_bind]
Results: map[SourceCode:1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 206/4 |
2026/07/31 06:55 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 13900
output: 29
thoughts: 13
Thoughts: Okay, here's my summary, considering my expertise:
**Checking the Unbind Operation within GadgetFS**
Right, I've just been digging into the `gadgetfs` implementation, and I need to make sure I've got a handle on everything related to resource cleanup when a device is unbound. I’ve already looked at the broader framework, but a critical function I haven't specifically dissected yet is `gadgetfs_unbind()`. I need to ensure that it correctly handles all the potential cleanup operations – freeing memory, releasing locks, signaling completion, and closing file descriptors – associated with detaching a `gadgetfs` device. There are several subtle points to consider for safe unbinding. The unbind may have to be performed at any time. I should check how it interacts with other concurrent operations and ensure there are no race conditions. It is easy to introduce a subtle bug here. I'll need to meticulously trace the control flow within `gadgetfs_unbind()` and cross-reference it with the broader device model to confirm all resources are properly released, in the correct order, and that there are no leaks or double-frees. This is particularly important with the dynamic nature of these devices and the possibility of unexpected detachments.
|
| 207/4 |
2026/07/31 06:55 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadgetfs_unbind]
Results: map[SourceCode:1639: static void
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
1643:
1644: DBG (dev, "%s\n", __func__);
1645:
1646: spin_lock_irq (&dev->lock);
1647: dev->state = STATE_DEV_UNBOUND;
1648: while (dev->udc_usage > 0) {
1649: spin_unlock_irq(&dev->lock);
1650: usleep_range(1000, 2000);
1651: spin_lock_irq(&dev->lock);
1652: }
1653: spin_unlock_irq (&dev->lock);
1654:
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 208/4 |
2026/07/31 06:55 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 14643
output: 29
thoughts: 190
Thoughts: **Unbinding GadgetFS - A Review of the Process**
Okay, so I'm thinking through the `gadgetfs_unbind` function. Let me quickly recap its steps, just to solidify my understanding. First, it updates the device state to `STATE_DEV_UNBOUND`. Then, crucially, it calls `destroy_ep_files(dev)`. After that, it clears the driver-specific data and gadget data related to endpoint 0. Finally, it frees the request associated with endpoint 0, if one exists, and decrements the device's reference count. Standard unbind logic, mostly.
Now, I'm trying to catch all the edge cases and potential failure scenarios. I know that if `gadgetfs_bind` fails during the `usb_ep_alloc_request` call, `dev->req` will be left as NULL. In that scenario, `activate_ep_files` never gets called, which affects the files that were never created.
This has me thinking. Because `destroy_ep_files(dev)` gets called in `gadgetfs_unbind` regardless of how bind fails, I should check the functions `activate_ep_files` and `destroy_ep_files` in more detail. I want to make sure the implementation there is robust to those scenarios. It is very important that the unbind process cleans up correctly, even if the bind sequence didn't completely finish. I'll get into those routines next.
|
| 209/4 |
2026/07/31 06:55 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:activate_ep_files]
Results: map[SourceCode:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
1610: data->dev = dev;
1611: get_dev (dev);
1612:
1613: data->ep = ep;
1614: ep->driver_data = data;
1615:
1616: data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1617: if (!data->req)
1618: goto enomem1;
1619:
1620: err = gadgetfs_create_file (dev->sb, data->name,
1621: data, &ep_io_operations);
1622: if (err)
1623: goto enomem2;
1624: list_add_tail (&data->epfiles, &dev->epfiles);
1625: }
1626: return 0;
1627:
1628: enomem2:
1629: usb_ep_free_request (ep, data->req);
1630: enomem1:
1631: put_dev (dev);
1632: kfree (data);
1633: enomem0:
1634: DBG (dev, "%s enomem\n", __func__);
1635: destroy_ep_files (dev);
1636: return -ENOMEM;
1637: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 210/4 |
2026/07/31 06:55 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 15831
output: 42
thoughts: 286
Thoughts: **Analyzing the Error Handling in `gadgetfs`**
Okay, so I'm digging into this `gadgetfs` code and trying to understand this `-ENOMEM` return. It looks like `activate_ep_files` is designed to be pretty robust; if it fails, it calls `destroy_ep_files(dev)` to clean up the `ep_data` structures it created, and then gracefully returns `-ENOMEM`. That's good defensive programming.
The problem, as I see it, is that `gadgetfs_bind` is where things start to get a little wonky. It jumps to `enomem:` upon receiving that error, and that leads to `gadgetfs_unbind` being called. Now, `gadgetfs_unbind` *also* calls `destroy_ep_files`, which should be fine (it's designed to handle a potentially partially initialized state). The real issue is the subsequent `put_dev(dev)` call. This is the crux of it. It seems to be dropping a reference to the `dev` structure that wasn't properly taken in the `gadgetfs_bind` function. And that's what's causing the problem.
The proposed fix, which involves clearing `dev->req`, `gadget->ep0->driver_data`, `dev->gadget` and setting the gadget data to NULL, looks like it's addressing the core issue: ensuring that all associated data structures are properly cleaned up *before* that reference is dropped. This seems reasonable, addressing the specific objects related to request failures.
Now, I need to expand my search. The solution appears to be directed to this exact error, but I want to verify if there are any other places where `gadgetfs_unbind` might be called and see if the same issue could be present. Let me make sure that there are no additional subtle issues that I'm overlooking.
|
| 211/4 |
2026/07/31 06:55 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile: IncludeSnippetLines:0 Name:gadgetfs_unbind SourceTreePrefix:]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:gadgetfs_bind SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1703] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:gadgetfs_driver SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1749]] TruncatedOutput:false]
|
| 212/4 |
2026/07/31 06:55 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 16702
output: 32
thoughts: 219
Thoughts: **Analyzing the GadgetFS Driver Unbind Function**
Okay, so I'm looking at the `gadgetfs_driver` structure here, specifically the `unbind` callback. It's clear that `gadgetfs_unbind` is designated as the function to handle the unbinding process. This makes sense; it's the expected function to clean up when the gadget is disconnected, right? It's supposed to be called after the device is fully bound.
Now, a crucial point to consider: if `gadgetfs_bind` encounters an error and fails to initialize properly, the USB gadget core won't invoke the `unbind` function. That's the expected behavior, but I just want to verify this.
I'd better double-check the `usb_gadget_register_driver` or `usb_gadget_probe_driver` code paths to be absolutely certain. Need to confirm how the USB core handles bind failures and unbinding in that scenario. Don't want any unexpected resource leaks or orphaned data structures in the event of an initialization problem.
|
| 213/4 |
2026/07/31 06:56 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile: Name:usb_gadget_probe_driver]
Results: map[SourceCode: SourceFile:]
|
| 214/4 |
2026/07/31 06:56 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 17201
output: 32
thoughts: 14
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience and written in the first person:
**Diving into USB Gadget Driver Registration**
Okay, time to dissect this `usb_gadget_register_driver` function. I'm already familiar with the broader USB gadget framework, so I know this is the crucial entry point for a device driver to announce itself to the system. My first thought is to quickly mentally reconstruct the typical flow. I'm picturing the driver structure being passed in – I'll need to verify the expected members and confirm my assumptions about the data it contains.
I'll be looking for sanity checks, error handling, and resource allocation within this registration routine. Specifically, I'm expecting to see checks for things like device ID matches or the presence of necessary callback functions. How does it handle conflicts? Does it allow for multiple drivers to claim the same device, or is there a more exclusive mechanism? I'm anticipating there's some locking involved to protect the gadget driver list from concurrent access, especially if it's operating within a multi-threaded or interrupt-driven kernel.
I need to confirm how the driver interacts with the underlying USB controller, particularly how it maps the driver's abstract device representation to the hardware's capabilities. Are there any configuration options I should be aware of, perhaps related to power management or speed negotiation? I'm also curious about any interaction with the UDC (USB Device Controller) layer, and how this registration impacts the overall device enumeration process. Finally, I'll pay close attention to the deregistration path; how gracefully does the framework handle a driver unregistering, and what cleanup steps are necessary to avoid resource leaks or conflicts? I'm hoping it's robust... Let's dig in.
|
| 215/4 |
2026/07/31 06:56 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile: Name:usb_gadget_register_driver]
Results: map[SourceCode: SourceFile:]
|
| 216/4 |
2026/07/31 06:56 |
llm |
patch-generator |
2m
Model:
Tokens:
input: 17641
output: 32
thoughts: 30
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into USB Gadget Driver Probing**
Okay, time to get to the heart of the matter. I need to understand how this USB gadget driver interaction is being handled. My immediate focus is the `usb_gadget_probe_driver` function. I'll head straight into `drivers/usb/gadget/udc/core.c` – that's the likely spot for the core UDC (USB Device Controller) implementation, so it's the natural place to start looking for probe function calls. I'm assuming that this is where the system attempts to match and load a suitable gadget driver for the attached hardware. I want to see how the driver matching is done, what criteria are used, and how the driver's interface is then integrated with the core UDC framework. I need to understand the control flow here to pinpoint the specific aspect I'm troubleshooting. Specifically, I need to understand the conditions under which a driver is correctly probed and activated, and the error paths that might be occurring.
|
| 217/4 |
2026/07/31 06:58 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile: Name:usb_gadget_probe_driver]
Results: map[SourceCode: SourceFile:]
|
| 218/4 |
2026/07/31 06:58 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 17955
output: 34
thoughts: 17
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience and written in the first person:
**Navigating the USB Gadget Driver Registration**
Okay, so I'm looking at this code, and it's hitting me right away: `usb_gadget_register_driver_owner`. Yep, there it is. The core function to register a USB gadget driver. From the naming alone, I already know this likely handles the setup of the driver with the USB subsystem. It almost certainly involves allocating and populating the internal gadget driver data structures.
This means it's responsible for things like handling driver ownership, making sure there are no conflicts with other drivers trying to control the same hardware, and ensuring proper initialization steps. I'm expecting checks for device configurations, endpoints, and potentially power management related functions being passed or initialized here. It probably also deals with the synchronization primitives to ensure thread-safety during concurrent access to the device. The "owner" part suggests there's a mechanism to manage driver exclusivity. I need to dig into the definition to see how it's done. I also want to check for error handling routines. I'm probably looking at a return code or a set of error conditions that are checked.
|
| 219/4 |
2026/07/31 06:59 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:usb_gadget_register_driver_owner]
Results: map[SourceCode:1740: int usb_gadget_register_driver_owner(struct usb_gadget_driver *driver,
1741: struct module *owner, const char *mod_name)
1742: {
1743: int ret;
1744:
1745: if (!driver || !driver->bind || !driver->setup)
1746: return -EINVAL;
1747:
1748: driver->driver.bus = &gadget_bus_type;
1749: driver->driver.owner = owner;
1750: driver->driver.mod_name = mod_name;
1751: driver->driver.probe_type = PROBE_FORCE_SYNCHRONOUS;
1752: ret = driver_register(&driver->driver);
1753: if (ret) {
1754: pr_warn("%s: driver registration failed: %d\n",
1755: driver->function, ret);
1756: return ret;
1757: }
1758:
1759: mutex_lock(&udc_lock);
1760: if (!driver->is_bound) {
1761: if (driver->match_existing_only) {
1762: pr_warn("%s: couldn't find an available UDC or it's busy\n",
1763: driver->function);
1764: ret = -EBUSY;
1765: } else {
1766: pr_info("%s: couldn't find an available UDC\n",
1767: driver->function);
1768: ret = 0;
1769: }
1770: }
1771: mutex_unlock(&udc_lock);
1772:
1773: if (ret)
1774: driver_unregister(&driver->driver);
1775: return ret;
1776: }
SourceFile:drivers/usb/gadget/udc/core.c]
|
| 220/4 |
2026/07/31 06:59 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 18827
output: 30
thoughts: 30
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Decoding the Binding Mechanism**
Right, so I'm thinking about the USB gadget driver binding process. Specifically, I'm tracing the function calls, and the core of the binding operation appears to be initiated by `gadget_bind_driver`. I know that function's located within `drivers/usb/gadget/udc/core.c`. So, I need to look closely at what `gadget_bind_driver` is actually doing. It's the starting point for establishing the association between the gadget driver and the USB device controller (UDC). I need to understand how it's setting up the communication channels, registering resources, and essentially making the driver active and operational. This line of thought now branches out into dissecting the associated data structures. I need to refresh my knowledge of the control flow through the various layers, from the core UDC code down to the specific gadget drivers, to ensure I have a complete picture of the interactions. I'm especially interested in how the driver handles device enumeration and configuration after the binding is established.
|
| 221/4 |
2026/07/31 06:59 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadget_bind_driver]
Results: map[SourceCode:1641: static int gadget_bind_driver(struct device *dev)
1642: {
1643: struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1644: struct usb_udc *udc = gadget->udc;
1645: struct usb_gadget_driver *driver = container_of(dev->driver,
1646: struct usb_gadget_driver, driver);
1647: int ret = 0;
1648:
1649: mutex_lock(&udc_lock);
1650: if (driver->is_bound) {
1651: mutex_unlock(&udc_lock);
1652: return -ENXIO; /* Driver binds to only one gadget */
1653: }
1654: driver->is_bound = true;
1655: udc->driver = driver;
1656: mutex_unlock(&udc_lock);
1657:
1658: dev_dbg(&udc->dev, "binding gadget driver [%s]\n", driver->function);
1659:
1660: usb_gadget_udc_set_speed(udc, driver->max_speed);
1661:
1662: ret = driver->bind(udc->gadget, driver);
1663: if (ret)
1664: goto err_bind;
1665:
1666: mutex_lock(&udc->connect_lock);
1667: ret = usb_gadget_udc_start_locked(udc);
1668: if (ret) {
1669: mutex_unlock(&udc->connect_lock);
1670: goto err_start;
1671: }
1672: usb_gadget_enable_async_callbacks(udc);
1673: udc->allow_connect = true;
1674: ret = usb_udc_connect_control_locked(udc);
1675: if (ret)
1676: goto err_connect_control;
1677:
1678: mutex_unlock(&udc->connect_lock);
1679:
1680: kobject_uevent(&udc->dev.kobj, KOBJ_CHANGE);
1681: return 0;
1682:
1683: err_connect_control:
1684: udc->allow_connect = false;
1685: usb_gadget_disable_async_callbacks(udc);
1686: if (gadget->irq)
1687: synchronize_irq(gadget->irq);
1688: usb_gadget_udc_stop_locked(udc);
1689: mutex_unlock(&udc->connect_lock);
1690:
1691: err_start:
1692: driver->unbind(udc->gadget);
1693:
1694: err_bind:
1695: if (ret != -EISNAM)
1696: dev_err(&udc->dev, "failed to start %s: %d\n",
1697: driver->function, ret);
1698:
1699: mutex_lock(&udc_lock);
1700: udc->driver = NULL;
1701: driver->is_bound = false;
1702: mutex_unlock(&udc_lock);
1703:
1704: return ret;
1705: }
SourceFile:drivers/usb/gadget/udc/core.c]
|
| 222/4 |
2026/07/31 06:59 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 20138
output: 29
thoughts: 174
Thoughts: **Analyzing the GadgetFS Bind/Unbind Logic**
Okay, here's what's running through my head. I'm looking at how this `gadget_bind_driver` function works. It seems to call `driver->bind(udc->gadget, driver)`, which is standard. The interesting part is what happens on failure. It jumps to `err_bind`, but crucially, *it doesn't* call `driver->unbind`. That immediately tells me that `gadgetfs_bind` itself has to be self-contained and clean up its own mess if binding fails.
Right now, it looks like `gadgetfs_bind` calls `gadgetfs_unbind(gadget)` in the failure path. The problem with *that* is that `gadgetfs_unbind` seems to assume that the device was fully bound, which means it calls `put_dev(dev)`. But, I'm pretty sure `gadgetfs_bind` only calls `get_dev(dev)` at the very end of a successful binding. So, if we call `gadgetfs_unbind` on a failed bind, we're dropping a reference count (via `put_dev(dev)`) that was never even incremented in the first place. That's a classic resource leak or double-free, depending on the implementation.
We've got a potential bug here. Let's dig back into the `gadgetfs_bind` code and see if we can identify the problem more precisely. This is where the real work begins.
|
| 223/4 |
2026/07/31 06:59 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadgetfs_bind]
Results: map[SourceCode:1668: static int gadgetfs_bind(struct usb_gadget *gadget,
1669: struct usb_gadget_driver *driver)
1670: {
1671: struct dev_data *dev = the_device;
1672:
1673: if (!dev)
1674: return -ESRCH;
1675: if (0 != strcmp (CHIP, gadget->name)) {
1676: pr_err("%s expected %s controller not %s\n",
1677: shortname, CHIP, gadget->name);
1678: return -ENODEV;
1679: }
1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 224/4 |
2026/07/31 06:59 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 21259
output: 27
thoughts: 329
Thoughts: **Manual Cleanup vs. `gadgetfs_unbind`**
Okay, so I'm digging into this code and trying to figure out what needs to happen if we ditch the standard `gadgetfs_unbind` call and instead handle the cleanup manually. The goal is clear: to ensure everything is properly released and reset after a device is unbound. I have a list of actions to consider, and I need to methodically work through them.
First, I need to look at the direct assignments. I see a few key places where pointers are set, which would need nulling. Specifically: `set_gadget_data(gadget, dev)` needs to become `set_gadget_data(gadget, NULL)`. Also, the reverse must happen; `dev->gadget = gadget` becomes `dev->gadget = NULL`, and `gadget->ep0->driver_data = dev` would be `gadget->ep0->driver_data = NULL`.
The next point concerns the request allocation. `dev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL)` must be replaced with a check and free: `if (dev->req) { usb_ep_free_request(gadget->ep0, dev->req); dev->req = NULL; }`. We need to make sure we only free if it was actually allocated.
Then, there's `activate_ep_files(dev)`. The comment says it cleans up on failure so I don't need to do anything there. That's one less thing to worry about.
Now, there's a little nagging thought about `dev->state`. It's crucial we don't leak any state information. `gadgetfs_unbind` explicitly sets `dev->state = STATE_DEV_UNBOUND;`. But, here's the kicker: `gadgetfs_bind` hasn't had a chance to update this `dev->state` when there's a failure. Before `gadgetfs_bind`, the state is probably either `STATE_DEV_OPENED` or `STATE_DEV_UNBOUND`. To make sure I understand this flow and ensure no states are missed, let's trace this back. Where is `gadgetfs_bind` being called from? Okay, it's called from `usb_gadget_register_driver`. Aha! And `usb_gadget_register_driver` is called from `dev_config`. So, now I can use this information for my implementation.
|
| 225/4 |
2026/07/31 06:59 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:dev_config]
Results: map[SourceCode:1800: static ssize_t
1801: dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1802: {
1803: struct dev_data *dev = fd->private_data;
1804: ssize_t value, length = len;
1805: unsigned total;
1806: u32 tag;
1807: char *kbuf;
1808:
1809: spin_lock_irq(&dev->lock);
1810: if (dev->state > STATE_DEV_OPENED) {
1811: value = ep0_write(fd, buf, len, ptr);
1812: spin_unlock_irq(&dev->lock);
1813: return value;
1814: }
1815: spin_unlock_irq(&dev->lock);
1816:
1817: if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||
1818: (len > PAGE_SIZE * 4))
1819: return -EINVAL;
1820:
1821: /* we might need to change message format someday */
1822: if (copy_from_user (&tag, buf, 4))
1823: return -EFAULT;
1824: if (tag != 0)
1825: return -EINVAL;
1826: buf += 4;
1827: length -= 4;
1828:
1829: kbuf = memdup_user(buf, length);
1830: if (IS_ERR(kbuf))
1831: return PTR_ERR(kbuf);
1832:
1833: spin_lock_irq (&dev->lock);
1834: value = -EINVAL;
1835: if (dev->buf) {
1836: spin_unlock_irq(&dev->lock);
1837: kfree(kbuf);
1838: return value;
1839: }
1840: dev->buf = kbuf;
1841:
1842: /* full or low speed config */
1843: dev->config = (void *) kbuf;
1844: total = le16_to_cpu(dev->config->wTotalLength);
1845: if (!is_valid_config(dev->config, total) ||
1846: total > length - USB_DT_DEVICE_SIZE)
1847: goto fail;
1848: kbuf += total;
1849: length -= total;
1850:
1851: /* optional high speed config */
1852: if (kbuf [1] == USB_DT_CONFIG) {
1853: dev->hs_config = (void *) kbuf;
1854: total = le16_to_cpu(dev->hs_config->wTotalLength);
1855: if (!is_valid_config(dev->hs_config, total) ||
1856: total > length - USB_DT_DEVICE_SIZE)
1857: goto fail;
1858: kbuf += total;
1859: length -= total;
1860: } else {
1861: dev->hs_config = NULL;
1862: }
1863:
1864: /* could support multiple configs, using another encoding! */
1865:
1866: /* device descriptor (tweaked for paranoia) */
1867: if (length != USB_DT_DEVICE_SIZE)
1868: goto fail;
1869: dev->dev = (void *)kbuf;
1870: if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1871: || dev->dev->bDescriptorType != USB_DT_DEVICE
1872: || dev->dev->bNumConfigurations != 1)
1873: goto fail;
1874: dev->dev->bcdUSB = cpu_to_le16 (0x0200);
1875:
1876: /* triggers gadgetfs_bind(); then we can enumerate. */
1877: spin_unlock_irq (&dev->lock);
1878: if (dev->hs_config)
1879: gadgetfs_driver.max_speed = USB_SPEED_HIGH;
1880: else
1881: gadgetfs_driver.max_speed = USB_SPEED_FULL;
1882:
1883: value = usb_gadget_register_driver(&gadgetfs_driver);
1884: if (value != 0) {
1885: spin_lock_irq(&dev->lock);
1886: goto fail;
1887: } else {
1888: /* at this point "good" hardware has for the first time
1889: * let the USB the host see us. alternatively, if users
1890: * unplug/replug that will clear all the error state.
1891: *
1892: * note: everything running before here was guaranteed
1893: * to choke driver model style diagnostics. from here
1894: * on, they can work ... except in cleanup paths that
1895: * kick in after the ep0 descriptor is closed.
1896: */
1897: value = len;
1898: dev->gadget_registered = true;
1899: }
1900: return value;
1901:
1902: fail:
1903: dev->config = NULL;
1904: dev->hs_config = NULL;
1905: dev->dev = NULL;
1906: spin_unlock_irq (&dev->lock);
1907: pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev);
1908: kfree (dev->buf);
1909: dev->buf = NULL;
1910: return value;
1911: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 226/4 |
2026/07/31 06:59 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 23873
output: 30
thoughts: 98
Thoughts: **My Analysis of the USB Gadget Driver Registration**
Okay, so I'm looking at this `dev_config` function, and it seems the core action here is the call to `usb_gadget_register_driver(&gadgetfs_driver);`. That's the crucial step, the one that makes the whole thing tick. I immediately want to see the error handling.
If that registration *fails*, it jumps right to the `fail:` label. Makes sense. From there, it's cleaning up. It's setting `dev->config`, `dev->hs_config`, and `dev->dev` to NULL, and crucially, it's freeing `dev->buf`. That seems like the expected cleanup procedure, releasing any allocated resources if registration fails.
But what about the state? Interesting. It doesn't modify `dev->state`. Looking back, I can see that `dev->state` is initialized to `STATE_DEV_OPENED` in `gadget_dev_open`. So, even after a registration failure, `dev->state` will remain in that initial "opened" state. I'll need to remember that. It's likely that it will require further code to reset or move that state to a "failed open" state, to allow for a retry or cleanup. I need to make sure I understand the code that consumes this state variable to ensure that failure is handled correctly.
|
| 227/4 |
2026/07/31 07:00 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadget_dev_open]
Results: map[SourceCode:1913: static int
1914: gadget_dev_open (struct inode *inode, struct file *fd)
1915: {
1916: struct dev_data *dev = inode->i_private;
1917: int value = -EBUSY;
1918:
1919: spin_lock_irq(&dev->lock);
1920: if (dev->state == STATE_DEV_DISABLED) {
1921: dev->ev_next = 0;
1922: dev->state = STATE_DEV_OPENED;
1923: fd->private_data = dev;
1924: get_dev (dev);
1925: value = 0;
1926: }
1927: spin_unlock_irq(&dev->lock);
1928: return value;
1929: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 228/4 |
2026/07/31 07:00 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 24577
output: 29
thoughts: 320
Thoughts: **Debugging Device State Transitions**
Okay, so I'm tracing this `dev->state` variable and how it's being handled. Right now, before we even get to `gadgetfs_bind`, it's supposed to be `STATE_DEV_OPENED`. Makes sense so far. The key issue is if `gadgetfs_bind` fails. The code *should* leave `dev->state` as `STATE_DEV_OPENED`, to indicate a failure to bind to the gadget. But, if `gadgetfs_unbind` *is* called, it sets `dev->state = STATE_DEV_UNBOUND`. That's where things get problematic. `STATE_DEV_UNBOUND` suggests the device *was* successfully bound and then unbound, but that's not the case here, and it's preventing the retry of a configuration write, which is vital.
The big problem? The `dev_config` function. I see that it checks `dev->state` and handles it differently: wait, the `dev_config` code says it *only* allows configuration writes if `dev->state <= STATE_DEV_OPENED`.
Looking at the code for `dev_config`, it says:
```c
if (dev->state > STATE_DEV_OPENED) {
value = ep0_write(fd, buf, len, ptr);
spin_unlock_irq(&dev->lock);
return value;
}
```
If `dev->state` is `STATE_DEV_UNBOUND` (which is `4`), then the `if` condition is true. The condition is `dev->state > STATE_DEV_OPENED` where `STATE_DEV_OPENED` is `1`. This means that `ep0_write` is called, which isn't a valid configuration write if the gadget hasn't been properly bound. So on a failed bind, setting `dev->state = STATE_DEV_UNBOUND` is *definitely* the wrong behavior. Let's dig deeper into the states and how they're intended to work.
|
| 229/4 |
2026/07/31 07:00 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile: Name:STATE_DEV_DISABLED]
Results: map[SourceCode: SourceFile:]
|
| 230/4 |
2026/07/31 07:00 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 25402
output: 37
thoughts: 27
Thoughts: Here's my thought process, as it just happened:
**Diving into the USB Gadget Driver**
Okay, I need to investigate something related to a disabled state in the USB gadget driver. My first instinct, given my experience with the Linux kernel USB subsystem, is to look for a specific define. I'm thinking the relevant define might be `STATE_DEV_DISABLED`. The core gadget code is usually in `drivers/usb/gadget/` so that's where I'll focus my search. Given the legacy nature of some of the driver code, I'll start with the `legacy` directory. I vaguely remember something about inode handling being important at the base level of this legacy code, so I'll go directly to `inode.c`. Let's see what's in there. I'm going to search for `STATE_DEV_DISABLED` within that specific file and see what results I get. That's the best way to get a quick overview of what's going on and to form a more complete picture.
|
| 231/4 |
2026/07/31 07:00 |
tool |
grepper |
0m
Args: map[Expression:STATE_DEV_DISABLED PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:drivers/usb/gadget/legacy/inode.c=91=enum ep0_state {
drivers/usb/gadget/legacy/inode.c-92- /* DISABLED is the initial state. */
drivers/usb/gadget/legacy/inode.c:93: STATE_DEV_DISABLED = 0,
drivers/usb/gadget/legacy/inode.c-94-
--
drivers/usb/gadget/legacy/inode.c=172=static struct dev_data *dev_new (void)
--
drivers/usb/gadget/legacy/inode.c-178- return NULL;
drivers/usb/gadget/legacy/inode.c:179: dev->state = STATE_DEV_DISABLED;
drivers/usb/gadget/legacy/inode.c-180- refcount_set (&dev->count, 1);
--
drivers/usb/gadget/legacy/inode.c=1191=dev_release (struct inode *inode, struct file *fd)
--
drivers/usb/gadget/legacy/inode.c-1211- spin_lock_irq(&dev->lock);
drivers/usb/gadget/legacy/inode.c:1212: dev->state = STATE_DEV_DISABLED;
drivers/usb/gadget/legacy/inode.c-1213- spin_unlock_irq(&dev->lock);
--
drivers/usb/gadget/legacy/inode.c=1914=gadget_dev_open (struct inode *inode, struct file *fd)
--
drivers/usb/gadget/legacy/inode.c-1919- spin_lock_irq(&dev->lock);
drivers/usb/gadget/legacy/inode.c:1920: if (dev->state == STATE_DEV_DISABLED) {
drivers/usb/gadget/legacy/inode.c-1921- dev->ev_next = 0;
]
|
| 232/4 |
2026/07/31 07:00 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 26170
output: 157
thoughts: 262
Thoughts: **My Analysis of the USB Endpoint 0 (EP0) State Machine**
Okay, let me break this down. My thought process is centered around these `enum ep0_state` values. I see it clearly; the states define the lifecycle of the USB EP0 endpoint. It starts in `STATE_DEV_DISABLED`. Makes sense. Then, the important part: it moves to `STATE_DEV_OPENED`. This is a crucial distinction: only one `open()` call is permitted on EP0 until the gadget is properly bound and configured. During this initial phase, EP0's duties are strictly limited to handling configuration writes.
Then, the state advances: `STATE_DEV_UNCONNECTED` when the gadget is bound, but not yet configured. The next logical step, `STATE_DEV_CONNECTED`, shows that the gadget is now both bound and configured. Of course, `STATE_DEV_SETUP` comes when a setup request needs to be handled. Finally, there is `STATE_DEV_UNBOUND`, which is, as the name makes clear, when the gadget is unbound.
Now, specifically regarding `STATE_DEV_UNBOUND`, this is explicitly the final state. It only applies *after* the gadget is unbound. Right? Yup.
Therefore, when `gadgetfs_bind` fails, I need to ensure it reverts to a safe state. Since `gadgetfs_bind` only changes the state to `STATE_DEV_UNCONNECTED` when it *succeeds*, a failure means it's still in `STATE_DEV_OPENED`. Perfect. No explicit state change is needed on failure. It's already there!
So, the code edit is straightforward. Now, let's get to it.
|
| 233/4 |
2026/07/31 07:00 |
tool |
codeeditor |
0m
Args: map[CurrentCode: enomem:
gadgetfs_unbind (gadget);
return -ENOMEM;
} NewCode: enomem:
if (dev->req) {
usb_ep_free_request (gadget->ep0, dev->req);
dev->req = NULL;
}
gadget->ep0->driver_data = NULL;
dev->gadget = NULL;
set_gadget_data (gadget, NULL);
return -ENOMEM;
} SourceFile:drivers/usb/gadget/legacy/inode.c]
Results:
|
| 234/4 |
2026/07/31 07:00 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 26963
output: 42
thoughts: 21
Thoughts: Okay, here's my summary, considering my expertise:
**Checking for Incorrect `gadgetfs_unbind` Calls**
Alright, time to get granular. We've identified *a* problem, but we can't assume it's the *only* problem. My initial focus was on this specific instance of `gadgetfs_unbind`, but now I need to broaden the scope. My gut feeling is telling me there could be other spots in the codebase, maybe subtle variations in how `gadgetfs_unbind` is used, where the same or a similar issue could be lurking. It's too easy to get tunnel vision. So, I need to methodically check the entire call graph, look for any other places where `gadgetfs_unbind` is invoked. I'm thinking variations in parameters passed, timing of calls relative to other operations – these are all potential avenues for introducing this subtle bug. Let's see what the code reveals. A comprehensive search and review is in order.
|
| 235/4 |
2026/07/31 07:00 |
tool |
codesearch-find-references |
0m
Args: map[ContextFile: IncludeSnippetLines:0 Name:gadgetfs_unbind SourceTreePrefix:]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:gadgetfs_bind SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1703] map[ReferenceKind:takes-address-of ReferencingEntityKind:global_variable ReferencingEntityName:gadgetfs_driver SourceFile:drivers/usb/gadget/legacy/inode.c SourceLine:1749]] TruncatedOutput:false]
|
| 236/4 |
2026/07/31 07:00 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 27372
output: 29
thoughts: 44
Thoughts: Okay, here's my interpretation of these thoughts, formatted as you requested:
**Navigating USB Gadget Driver Code**
Right, so where are we with this issue? My initial impression is that the problem, or at least the area affected, is limited. It seems the fix we just implemented in `gadgetfs_bind` is the first place this surfaced, which is good. We also might want to check the `gadgetfs_driver` structure for any related issues.
Now, let's circle back and meticulously examine the error handling in `activate_ep_files`. We need to be absolutely certain we've covered all the bases there, given the recent fix. Gotta make sure we didn't introduce any new regressions. Time to dig in!
|
| 237/4 |
2026/07/31 07:00 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:activate_ep_files]
Results: map[SourceCode:1593: static int activate_ep_files (struct dev_data *dev)
1594: {
1595: struct usb_ep *ep;
1596: struct ep_data *data;
1597: int err;
1598:
1599: gadget_for_each_ep (ep, dev->gadget) {
1600:
1601: data = kzalloc_obj(*data);
1602: if (!data)
1603: goto enomem0;
1604: data->state = STATE_EP_DISABLED;
1605: mutex_init(&data->lock);
1606: init_waitqueue_head (&data->wait);
1607:
1608: strscpy(data->name, ep->name);
1609: refcount_set (&data->count, 1);
1610: data->dev = dev;
1611: get_dev (dev);
1612:
1613: data->ep = ep;
1614: ep->driver_data = data;
1615:
1616: data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1617: if (!data->req)
1618: goto enomem1;
1619:
1620: err = gadgetfs_create_file (dev->sb, data->name,
1621: data, &ep_io_operations);
1622: if (err)
1623: goto enomem2;
1624: list_add_tail (&data->epfiles, &dev->epfiles);
1625: }
1626: return 0;
1627:
1628: enomem2:
1629: usb_ep_free_request (ep, data->req);
1630: enomem1:
1631: put_dev (dev);
1632: kfree (data);
1633: enomem0:
1634: DBG (dev, "%s enomem\n", __func__);
1635: destroy_ep_files (dev);
1636: return -ENOMEM;
1637: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 238/4 |
2026/07/31 07:00 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 28264
output: 29
thoughts: 73
Thoughts: Here's my summary, as the expert:
**Investigating a Potential Resource Leak**
Okay, so I'm looking at `activate_ep_files` here. The code seems pretty straightforward: if it hits a snag, it calls `destroy_ep_files(dev)`. That's standard error handling – clean up the mess and try to prevent further problems. `destroy_ep_files`, in turn, is supposed to iterate through the `dev->epfiles` structure and tidy things up. It sounds reasonable.
But wait a minute... I'm getting a nagging feeling. `destroy_ep_files` is calling `put_dev(dev)` for *each* ep file. That seems... excessive. Why are we releasing the entire device for each individual file cleanup? `put_dev` typically reduces the device's reference count and possibly frees it if the count hits zero. Doing that inside a loop that's supposed to handle individual file cleanup is highly suspect and likely incorrect. I need to dig deeper. This looks like a potential resource leak, or, at the very least, a serious design flaw. I need to understand why this pattern exists and whether it should be replaced with `put_ep_file(epfile)`, assuming such a function exists.
|
| 239/4 |
2026/07/31 07:00 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:destroy_ep_files]
Results: map[SourceCode:1554: static void destroy_ep_files (struct dev_data *dev)
1555: {
1556: DBG (dev, "%s %d\n", __func__, dev->state);
1557:
1558: /* dev->state must prevent interference */
1559: spin_lock_irq (&dev->lock);
1560: while (!list_empty(&dev->epfiles)) {
1561: struct ep_data *ep;
1562:
1563: /* break link to FS */
1564: ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles);
1565: list_del_init (&ep->epfiles);
1566: spin_unlock_irq (&dev->lock);
1567:
1568: /* break link to controller */
1569: mutex_lock(&ep->lock);
1570: if (ep->state == STATE_EP_ENABLED)
1571: (void) usb_ep_disable (ep->ep);
1572: ep->state = STATE_EP_UNBOUND;
1573: usb_ep_free_request (ep->ep, ep->req);
1574: ep->ep = NULL;
1575: mutex_unlock(&ep->lock);
1576:
1577: wake_up (&ep->wait);
1578:
1579: /* break link to dcache */
1580: simple_remove_by_name(dev->sb->s_root, ep->name, NULL);
1581:
1582: put_ep (ep);
1583:
1584: spin_lock_irq (&dev->lock);
1585: }
1586: spin_unlock_irq (&dev->lock);
1587: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 240/4 |
2026/07/31 07:00 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 29176
output: 27
thoughts: 16
Thoughts: Here's my understanding of the situation, tailored for an expert like yourself:
**Deconstructing `destroy_ep_files`**
Alright, so I see `destroy_ep_files` is the function in question. My immediate thought is, what's its primary responsibility? Obviously, from the name, it's about cleaning up or removing something related to "ep" files, which I'm inferring are endpoint files. Now, the key here is the very next line: it calls `put_ep(ep)`. That's the crux.
I'm interpreting that `put_ep(ep)` is the core action within this `destroy_ep_files` procedure. It's essentially the mechanism responsible for handling the endpoint data within the destruction phase. The "put" verb is vague but I am inferring that `put_ep` is responsible for storing, archiving, or otherwise processing the endpoint (ep) data before the files are destroyed. The fact that the function `put_ep` is called suggests that some data or state from the endpoint is persisted/stored elsewhere or used for auditing/logging prior to deletion.
|
| 241/4 |
2026/07/31 07:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:put_ep]
Results: map[SourceCode: 217: static void put_ep (struct ep_data *data)
218: {
219: if (likely (!refcount_dec_and_test (&data->count)))
220: return;
221: put_dev (data->dev);
222: /* needs no more cleanup */
223: BUG_ON (!list_empty (&data->epfiles));
224: BUG_ON (waitqueue_active (&data->wait));
225: kfree (data);
226: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 242/4 |
2026/07/31 07:01 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 29643
output: 27
thoughts: 1336
Thoughts: **Analyzing Resource Management in `gadgetfs_bind` and `activate_ep_files`**
Okay, let's break this down. My initial focus is on ensuring resource management is bulletproof in these functions. In `activate_ep_files`, the core problem is to ensure that allocations and deallocations are balanced, especially in error paths. I see that `put_ep` is called, which then triggers `put_dev(data->dev)` when the refcount hits zero.
My assessment of `activate_ep_files` is that it's clean. The function utilizes `kzalloc_obj`, `get_dev`, and `usb_ep_alloc_request` to manage resources. The various error paths (`enomem0`, `enomem1`, `enomem2`) properly deallocate resources in reverse order, ensuring a perfect balance. Specifically, `gadgetfs_create_file` failure leads to deallocation of the request, decrementing the device refcount, and freeing the data structure. If previous `ep`s have been successfully added, `destroy_ep_files` is called to clean them up, which calls `put_ep` on each `ep`, which then deallocates `data` via the device refcount.
Now I'm looking at `gadgetfs_bind`. The primary concern here is the proper cleanup in case of failure. The only points of failure in `gadgetfs_bind` appear to be `usb_ep_alloc_request` and `activate_ep_files`. If `usb_ep_alloc_request` fails, `dev->req` remains NULL, so `usb_ep_free_request` is skipped. If `activate_ep_files` fails, `dev->req` is freed and set to NULL. In either case, it ensures the initialization is completely undone via clearing `gadget->ep0->driver_data`, `dev->gadget`, and `set_gadget_data`. This deallocation is sound.
However, I need to check one more thing. What about `dev->state`? In the normal path, `gadgetfs_bind` sets `dev->state` to `STATE_DEV_UNCONNECTED`. But in the error path, I don't see that happening. Is this intentional? It looks like the state is not set during the error path. If `gadgetfs_bind` fails, `dev_config` will then fail, and the system returns `-ENOMEM`. The user can either retry `dev_config`, or close the file. If they close the file, `dev_release` gets called, which I'll need to check. Yes, because it is still in `STATE_DEV_OPENED`. `dev_release` should handle everything in that case.
|
| 243/4 |
2026/07/31 07:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:dev_release]
Results: map[SourceCode:1190: static int
1191: dev_release (struct inode *inode, struct file *fd)
1192: {
1193: struct dev_data *dev = fd->private_data;
1194:
1195: /* closing ep0 === shutdown all */
1196:
1197: if (dev->gadget_registered) {
1198: usb_gadget_unregister_driver (&gadgetfs_driver);
1199: dev->gadget_registered = false;
1200: }
1201:
1202: /* at this point "good" hardware has disconnected the
1203: * device from USB; the host won't see it any more.
1204: * alternatively, all host requests will time out.
1205: */
1206:
1207: kfree (dev->buf);
1208: dev->buf = NULL;
1209:
1210: /* other endpoints were all decoupled from this device */
1211: spin_lock_irq(&dev->lock);
1212: dev->state = STATE_DEV_DISABLED;
1213: spin_unlock_irq(&dev->lock);
1214:
1215: put_dev (dev);
1216: return 0;
1217: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 244/4 |
2026/07/31 07:01 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 32019
output: 29
thoughts: 173
Thoughts: **Analyzing the Device Release Procedure**
Okay, so in the `dev_release` function within the `dev_release` code, if my `dev->gadget_registered` flag is set to true, I know to unregister the driver. That makes sense, a clean disconnect. But, looking deeper, that flag only gets set to true in `dev_config` if the `usb_gadget_register_driver` call is successful. And if `gadgetfs_bind` fails, which would cause `usb_gadget_register_driver` to fail, that flag stays false.
Consequently, if `gadgetfs_bind` fails, `dev_release` gets called with `dev->gadget_registered` as false. In this scenario, all it does is free `dev->buf`, sets `dev->state` to `STATE_DEV_DISABLED`, and then calls `put_dev(dev)`. That `put_dev` call is critical; it releases the reference that was taken when `gadget_dev_open` was called. From a reference counting perspective, that seems perfectly sound. No leaks, no double frees, the state transitions correctly.
To be extra thorough, though, I need to check to see what `gadgetfs_unbind` does just to be absolutely certain I'm not missing any subtleties or potential side effects there. Just a good sanity check.
|
| 245/4 |
2026/07/31 07:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadgetfs_unbind]
Results: map[SourceCode:1639: static void
1640: gadgetfs_unbind (struct usb_gadget *gadget)
1641: {
1642: struct dev_data *dev = get_gadget_data (gadget);
1643:
1644: DBG (dev, "%s\n", __func__);
1645:
1646: spin_lock_irq (&dev->lock);
1647: dev->state = STATE_DEV_UNBOUND;
1648: while (dev->udc_usage > 0) {
1649: spin_unlock_irq(&dev->lock);
1650: usleep_range(1000, 2000);
1651: spin_lock_irq(&dev->lock);
1652: }
1653: spin_unlock_irq (&dev->lock);
1654:
1655: destroy_ep_files (dev);
1656: gadget->ep0->driver_data = NULL;
1657: set_gadget_data (gadget, NULL);
1658:
1659: /* we've already been disconnected ... no i/o is active */
1660: if (dev->req)
1661: usb_ep_free_request (gadget->ep0, dev->req);
1662: DBG (dev, "%s done\n", __func__);
1663: put_dev (dev);
1664: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 246/4 |
2026/07/31 07:01 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 32959
output: 28
thoughts: 164
Thoughts: **Analyzing the GadgetFS Unbind Process**
Okay, so I'm looking at how `gadgetfs_unbind` works. It's waiting on `dev->udc_usage` to go down to zero. That makes sense, right? It needs to ensure no active operations are underway before unbinding the device. Now, where is `dev->udc_usage` being incremented? Ah, right, in `ep0_read`, `ep0_write`, and `gadgetfs_setup`.
But wait a minute... since `gadgetfs_bind` hasn't completed, the gadget isn't fully bound yet. This means `gadgetfs_setup` *shouldn't* have been called by the UDC (USB Device Controller) yet. The whole point is to coordinate the binding process.
Okay, let's trace this further... `ep0_read` and `ep0_write` both check `dev->state`. Now, if the state is `STATE_DEV_OPENED`, then `ep0_write` is allowed. That makes sense, this allows for initial device configuration. But hold on... am I reading this right? `ep0_write` *doesn't* increment `udc_usage`? This could be a problem. This might explain why we're seeing this delay. I should double check that…
|
| 247/4 |
2026/07/31 07:01 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:ep0_write]
Results: map[SourceCode:1124: static ssize_t
1125: ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1126: {
1127: struct dev_data *dev = fd->private_data;
1128: ssize_t retval = -ESRCH;
1129:
1130: /* report fd mode change before acting on it */
1131: if (dev->setup_abort) {
1132: dev->setup_abort = 0;
1133: retval = -EIDRM;
1134:
1135: /* data and/or status stage for control request */
1136: } else if (dev->state == STATE_DEV_SETUP) {
1137:
1138: len = min_t(size_t, len, dev->setup_wLength);
1139: if (dev->setup_in) {
1140: retval = setup_req (dev->gadget->ep0, dev->req, len);
1141: if (retval == 0) {
1142: dev->state = STATE_DEV_CONNECTED;
1143: ++dev->udc_usage;
1144: spin_unlock_irq (&dev->lock);
1145: if (copy_from_user (dev->req->buf, buf, len))
1146: retval = -EFAULT;
1147: else {
1148: if (len < dev->setup_wLength)
1149: dev->req->zero = 1;
1150: retval = usb_ep_queue (
1151: dev->gadget->ep0, dev->req,
1152: GFP_KERNEL);
1153: }
1154: spin_lock_irq(&dev->lock);
1155: --dev->udc_usage;
1156: if (retval < 0) {
1157: clean_req (dev->gadget->ep0, dev->req);
1158: } else
1159: retval = len;
1160:
1161: return retval;
1162: }
1163:
1164: /* can stall some OUT transfers */
1165: } else if (dev->setup_can_stall) {
1166: VDEBUG(dev, "ep0out stall\n");
1167: (void) usb_ep_set_halt (dev->gadget->ep0);
1168: retval = -EL2HLT;
1169: dev->state = STATE_DEV_CONNECTED;
1170: } else {
1171: DBG(dev, "bogus ep0out stall!\n");
1172: }
1173: } else
1174: DBG (dev, "fail %s, state %d\n", __func__, dev->state);
1175:
1176: return retval;
1177: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 248/4 |
2026/07/31 07:01 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 34305
output: 15
thoughts: 359
Thoughts: **Analyzing Endpoint File Management in Gadgetfs**
Okay, so I'm digging into this `gadgetfs` code and trying to understand how endpoint files are managed, particularly focusing on the `udc_usage` counter and the `destroy_ep_files` function. It seems that `ep0_write` only increments `udc_usage` when the device is in the `STATE_DEV_SETUP` state. This means that during the `gadgetfs_bind` process, `udc_usage` is initially zero, which is important to consider.
My primary concern was around the cleanup process, especially in error scenarios. Specifically, I was wondering about `destroy_ep_files(dev)`. If `activate_ep_files` succeeds, then `gadgetfs_bind` subsequently fails, would the endpoint files be properly handled.
I see that `activate_ep_files` handles its own cleanup if it fails. That's good. Now, looking at the code for `gadgetfs_bind` directly, it appears that `activate_ep_files` is immediately followed by a check and a potential early exit, calling `destroy_ep_files(dev)` on the failure path. The thing is, if `activate_ep_files` succeeds, then the function proceeds to update the device state and ultimately, succeeds as well. It's designed so that failure after `activate_ep_files` isn't possible.
```c
if (activate_ep_files (dev) < 0)
goto enomem;
INFO (dev, "bound to %s driver\n", gadget->name);
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_UNCONNECTED;
spin_unlock_irq(&dev->lock);
get_dev (dev);
return 0;
```
So, if `activate_ep_files` fails, it *already* takes care of calling `destroy_ep_files(dev)`. If `activate_ep_files` succeeds, then there's no failure path to worry about. Therefore, the function cannot fail after `activate_ep_files`, and we don't need to call `destroy_ep_files(dev)` in the error path. This means that the existing logic seems sound here.
Alright, let's verify that `gadgetfs_bind` is the *only* place where `gadgetfs_unbind` *might* be used incorrectly. I believe we covered this in our previous review. Good, it's consistent.
Okay, I'm confident in my understanding now. Time to review the patch diff itself to be sure.
|
| 249/4 |
2026/07/31 07:02 |
tool |
patch-diff |
0m
Args:
Results: map[Output:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..ecea3d298 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1668,47 +1668,53 @@ static struct dev_data *the_device;
static int gadgetfs_bind(struct usb_gadget *gadget,
struct usb_gadget_driver *driver)
{
struct dev_data *dev = the_device;
if (!dev)
return -ESRCH;
if (0 != strcmp (CHIP, gadget->name)) {
pr_err("%s expected %s controller not %s\n",
shortname, CHIP, gadget->name);
return -ENODEV;
}
set_gadget_data (gadget, dev);
dev->gadget = gadget;
gadget->ep0->driver_data = dev;
/* preallocate control response and buffer */
dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
if (!dev->req)
goto enomem;
dev->req->context = NULL;
dev->req->complete = epio_complete;
if (activate_ep_files (dev) < 0)
goto enomem;
INFO (dev, "bound to %s driver\n", gadget->name);
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_UNCONNECTED;
spin_unlock_irq(&dev->lock);
get_dev (dev);
return 0;
-enomem:
- gadgetfs_unbind (gadget);
- return -ENOMEM;
+ enomem:
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
+ return -ENOMEM;
}
static void
gadgetfs_disconnect (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
unsigned long flags;
spin_lock_irqsave (&dev->lock, flags);
if (dev->state == STATE_DEV_UNCONNECTED)
]
|
| 250/4 |
2026/07/31 07:02 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 35965
output: 222
thoughts: 19
Thoughts: Okay, here's my attempt at summarizing the thought process, as requested, in the first person and assuming an expert audience:
**Minor Code Style Concern: Indentation**
Hmm, that `enomem:` label is bothering me a bit. I'm seeing it's not quite indented correctly within the surrounding code block. It's a small thing, but inconsistent indentation like that can become a distraction when reviewing the code later. It's not the end of the world, but it would improve readability to standardize it. Let's adjust it to match the rest of the block and keep things clean. Gotta maintain those high standards!
|
| 251/4 |
2026/07/31 07:02 |
tool |
codeeditor |
0m
Args: map[CurrentCode: enomem:
if (dev->req) {
usb_ep_free_request (gadget->ep0, dev->req);
dev->req = NULL;
}
gadget->ep0->driver_data = NULL;
dev->gadget = NULL;
set_gadget_data (gadget, NULL);
return -ENOMEM;
} NewCode:enomem:
if (dev->req) {
usb_ep_free_request (gadget->ep0, dev->req);
dev->req = NULL;
}
gadget->ep0->driver_data = NULL;
dev->gadget = NULL;
set_gadget_data (gadget, NULL);
return -ENOMEM;
} SourceFile:drivers/usb/gadget/legacy/inode.c]
Results:
|
| 252/4 |
2026/07/31 07:02 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 36347
output: 15
thoughts: 8
Thoughts: Okay, I'm ready to dive into that. Here's how I'd approach summarizing those "thoughts" in a way that resonates with an expert:
**Deep Dive Back into the Diff**
Alright, that's the trigger. "Let's check the diff again." That means we're in the middle of something complex. My immediate internal processing goes like this: We've been reviewing a code change, a data modification, a model update – something where version control is critical. "Checking the diff again" isn't a casual glance. It's a deliberate step, likely after an initial review, perhaps after some feedback, or maybe just a nagging feeling that something needs a closer look.
I'm thinking: What were the original concerns? Were there subtle nuances missed the first time? Is there a specific area of the change that needs focused attention? Am I second-guessing an assumption I made earlier? Is there a new tool I should use for the comparison? What kind of diff are we talking about, text, images, or code? What's the scale of the difference?
This isn't just about spotting differences. It's about *understanding* the impact of those differences. The 'diff' itself is just the data. The real work is interpreting it, assessing its implications within the larger context, and making sure it aligns with the overall goals and constraints. Depending on the scale, I may be looking at the context, the function that utilizes the element that was changed, or the downstream impact on other systems or functions. It's an iterative process. So, let me go check and see what's up.
|
| 253/4 |
2026/07/31 07:02 |
tool |
patch-diff |
0m
Args:
Results: map[Output:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..1a05819c0 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1668,46 +1668,52 @@ static struct dev_data *the_device;
static int gadgetfs_bind(struct usb_gadget *gadget,
struct usb_gadget_driver *driver)
{
struct dev_data *dev = the_device;
if (!dev)
return -ESRCH;
if (0 != strcmp (CHIP, gadget->name)) {
pr_err("%s expected %s controller not %s\n",
shortname, CHIP, gadget->name);
return -ENODEV;
}
set_gadget_data (gadget, dev);
dev->gadget = gadget;
gadget->ep0->driver_data = dev;
/* preallocate control response and buffer */
dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
if (!dev->req)
goto enomem;
dev->req->context = NULL;
dev->req->complete = epio_complete;
if (activate_ep_files (dev) < 0)
goto enomem;
INFO (dev, "bound to %s driver\n", gadget->name);
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_UNCONNECTED;
spin_unlock_irq(&dev->lock);
get_dev (dev);
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
static void
gadgetfs_disconnect (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
unsigned long flags;
spin_lock_irqsave (&dev->lock, flags);
]
|
| 254/4 |
2026/07/31 07:02 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 37387
output: 29
thoughts: 109
Thoughts: **Reviewing the Fix and Potential Similarities**
Okay, this fix looks solid. The implementation here aligns perfectly with the initial explanation of the root cause and the relevant historical context surrounding the issue. Specifically, it's addressing the problem by replacing that monolithic `gadgetfs_unbind` call. Instead, we're doing the cleanup manually for the resources allocated within `gadgetfs_bind`, which feels like the right approach. This approach neatly prevents that problematic reference drop where it wasn't acquired in the first place, and, crucially, avoids incorrectly setting `dev->state` to `STATE_DEV_UNBOUND`. So, from a functional perspective, I'm satisfied.
Now, a quick scan of the code feels warranted. Given the nature of the fix, I should take a look at `drivers/usb/gadget/legacy/inode.c` with a focus on identifying other potentially similar vulnerabilities. I'm thinking other error paths within this module are the prime candidates to check. A thorough review might uncover more of these sorts of subtle issues.
|
| 255/4 |
2026/07/31 07:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadgetfs_setup]
Results: map[SourceCode:1332: static int
1333: gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1334: {
1335: struct dev_data *dev = get_gadget_data (gadget);
1336: struct usb_request *req = dev->req;
1337: int value = -EOPNOTSUPP;
1338: struct usb_gadgetfs_event *event;
1339: u16 w_value = le16_to_cpu(ctrl->wValue);
1340: u16 w_length = le16_to_cpu(ctrl->wLength);
1341:
1342: if (w_length > RBUF_SIZE) {
1343: if (ctrl->bRequestType & USB_DIR_IN) {
1344: /* Cast away the const, we are going to overwrite on purpose. */
1345: __le16 *temp = (__le16 *)&ctrl->wLength;
1346:
1347: *temp = cpu_to_le16(RBUF_SIZE);
1348: w_length = RBUF_SIZE;
1349: } else {
1350: return value;
1351: }
1352: }
1353:
1354: spin_lock (&dev->lock);
1355: dev->setup_abort = 0;
1356: if (dev->state == STATE_DEV_UNCONNECTED) {
1357: if (gadget_is_dualspeed(gadget)
1358: && gadget->speed == USB_SPEED_HIGH
1359: && dev->hs_config == NULL) {
1360: spin_unlock(&dev->lock);
1361: ERROR (dev, "no high speed config??\n");
1362: return -EINVAL;
1363: }
1364:
1365: dev->state = STATE_DEV_CONNECTED;
1366:
1367: INFO (dev, "connected\n");
1368: event = next_event (dev, GADGETFS_CONNECT);
1369: event->u.speed = gadget->speed;
1370: ep0_readable (dev);
1371:
1372: /* host may have given up waiting for response. we can miss control
1373: * requests handled lower down (device/endpoint status and features);
1374: * then ep0_{read,write} will report the wrong status. controller
1375: * driver will have aborted pending i/o.
1376: */
1377: } else if (dev->state == STATE_DEV_SETUP)
1378: dev->setup_abort = 1;
1379:
1380: req->buf = dev->rbuf;
1381: req->context = NULL;
1382: switch (ctrl->bRequest) {
1383:
1384: case USB_REQ_GET_DESCRIPTOR:
1385: if (ctrl->bRequestType != USB_DIR_IN)
1386: goto unrecognized;
1387: switch (w_value >> 8) {
1388:
1389: case USB_DT_DEVICE:
1390: value = min (w_length, (u16) sizeof *dev->dev);
1391: dev->dev->bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
1392: req->buf = dev->dev;
1393: break;
1394: case USB_DT_DEVICE_QUALIFIER:
1395: if (!dev->hs_config)
1396: break;
1397: value = min (w_length, (u16)
1398: sizeof (struct usb_qualifier_descriptor));
1399: make_qualifier (dev);
1400: break;
1401: case USB_DT_OTHER_SPEED_CONFIG:
1402: case USB_DT_CONFIG:
1403: value = config_buf (dev,
1404: w_value >> 8,
1405: w_value & 0xff);
1406: if (value >= 0)
1407: value = min (w_length, (u16) value);
1408: break;
1409: case USB_DT_STRING:
1410: goto unrecognized;
1411:
1412: default: // all others are errors
1413: break;
1414: }
1415: break;
1416:
1417: /* currently one config, two speeds */
1418: case USB_REQ_SET_CONFIGURATION:
1419: if (ctrl->bRequestType != 0)
1420: goto unrecognized;
1421: if (0 == (u8) w_value) {
1422: value = 0;
1423: dev->current_config = 0;
1424: usb_gadget_vbus_draw(gadget, 8 /* mA */ );
1425: // user mode expected to disable endpoints
1426: } else {
1427: u8 config, power;
1428:
1429: if (gadget_is_dualspeed(gadget)
1430: && gadget->speed == USB_SPEED_HIGH) {
1431: config = dev->hs_config->bConfigurationValue;
1432: power = dev->hs_config->bMaxPower;
1433: } else {
1434: config = dev->config->bConfigurationValue;
1435: power = dev->config->bMaxPower;
1436: }
1437:
1438: if (config == (u8) w_value) {
1439: value = 0;
1440: dev->current_config = config;
1441: usb_gadget_vbus_draw(gadget, 2 * power);
1442: }
1443: }
1444:
1445: /* report SET_CONFIGURATION like any other control request,
1446: * except that usermode may not stall this. the next
1447: * request mustn't be allowed start until this finishes:
1448: * endpoints and threads set up, etc.
1449: *
1450: * NOTE: older PXA hardware (before PXA 255: without UDCCFR)
1451: * has bad/racey automagic that prevents synchronizing here.
1452: * even kernel mode drivers often miss them.
1453: */
1454: if (value == 0) {
1455: INFO (dev, "configuration #%d\n", dev->current_config);
1456: usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
1457: if (dev->usermode_setup) {
1458: dev->setup_can_stall = 0;
1459: goto delegate;
1460: }
1461: }
1462: break;
1463:
1464: #ifndef CONFIG_USB_PXA25X
1465: /* PXA automagically handles this request too */
1466: case USB_REQ_GET_CONFIGURATION:
1467: if (ctrl->bRequestType != 0x80)
1468: goto unrecognized;
1469: *(u8 *)req->buf = dev->current_config;
1470: value = min (w_length, (u16) 1);
1471: break;
1472: #endif
1473:
1474: default:
1475: unrecognized:
1476: VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n",
1477: dev->usermode_setup ? "delegate" : "fail",
1478: ctrl->bRequestType, ctrl->bRequest,
1479: w_value, le16_to_cpu(ctrl->wIndex), w_length);
1480:
1481: /* if there's an ep0 reader, don't stall */
1482: if (dev->usermode_setup) {
1483: dev->setup_can_stall = 1;
1484: delegate:
1485: dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
1486: ? 1 : 0;
1487: dev->setup_wLength = w_length;
1488: dev->setup_out_ready = 0;
1489: dev->setup_out_error = 0;
1490:
1491: /* read DATA stage for OUT right away */
1492: if (unlikely (!dev->setup_in && w_length)) {
1493: value = setup_req (gadget->ep0, dev->req,
1494: w_length);
1495: if (value < 0)
1496: break;
1497:
1498: ++dev->udc_usage;
1499: spin_unlock (&dev->lock);
1500: value = usb_ep_queue (gadget->ep0, dev->req,
1501: GFP_KERNEL);
1502: spin_lock (&dev->lock);
1503: --dev->udc_usage;
1504: if (value < 0) {
1505: clean_req (gadget->ep0, dev->req);
1506: break;
1507: }
1508:
1509: /* we can't currently stall these */
1510: dev->setup_can_stall = 0;
1511: }
1512:
1513: /* state changes when reader collects event */
1514: event = next_event (dev, GADGETFS_SETUP);
1515: event->u.setup = *ctrl;
1516: ep0_readable (dev);
1517: spin_unlock (&dev->lock);
1518: /*
1519: * Return USB_GADGET_DELAYED_STATUS as a workaround to
1520: * stop some UDC drivers (e.g. dwc3) from automatically
1521: * proceeding with the status stage for 0-length
1522: * transfers.
1523: * Should be removed once all UDC drivers are fixed to
1524: * always delay the status stage until a response is
1525: * queued to EP0.
1526: */
1527: return w_length == 0 ? USB_GADGET_DELAYED_STATUS : 0;
1528: }
1529: }
1530:
1531: /* proceed with data transfer and status phases? */
1532: if (value >= 0 && dev->state != STATE_DEV_SETUP) {
1533: req->length = value;
1534: req->zero = value < w_length;
1535:
1536: ++dev->udc_usage;
1537: spin_unlock (&dev->lock);
1538: value = usb_ep_queue (gadget->ep0, req, GFP_KERNEL);
1539: spin_lock(&dev->lock);
1540: --dev->udc_usage;
1541: spin_unlock(&dev->lock);
1542: if (value < 0) {
1543: DBG (dev, "ep_queue --> %d\n", value);
1544: req->status = 0;
1545: }
1546: return value;
1547: }
1548:
1549: /* device stalls when value < 0 */
1550: spin_unlock (&dev->lock);
1551: return value;
1552: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 256/4 |
2026/07/31 07:02 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 41125
output: 29
thoughts: 22
Thoughts: Here's my summary, as though I'm thinking through this myself:
**Reviewing gadgetfs Code: Disconnect Function**
Okay, `gadgetfs_setup` seems perfectly reasonable. No immediate red flags there. Now, let's turn our attention to the counterpart, `gadgetfs_disconnect`. This is where things can get interesting, particularly in managing resource cleanup and preventing race conditions. I'll need to pay close attention to how it handles removing the device, freeing any allocated structures, and ensuring the filesystem is properly unmounted. Let's see how they've handled potential issues with pending requests or active connections during the disconnect process. I'll be looking for robust error handling and proper synchronization mechanisms to avoid any data corruption or resource leaks.
|
| 257/4 |
2026/07/31 07:02 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:gadgetfs_disconnect]
Results: map[SourceCode:1707: static void
1708: gadgetfs_disconnect (struct usb_gadget *gadget)
1709: {
1710: struct dev_data *dev = get_gadget_data (gadget);
1711: unsigned long flags;
1712:
1713: spin_lock_irqsave (&dev->lock, flags);
1714: if (dev->state == STATE_DEV_UNCONNECTED)
1715: goto exit;
1716: dev->state = STATE_DEV_UNCONNECTED;
1717:
1718: INFO (dev, "disconnected\n");
1719: next_event (dev, GADGETFS_DISCONNECT);
1720: ep0_readable (dev);
1721: exit:
1722: spin_unlock_irqrestore (&dev->lock, flags);
1723: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 258/4 |
2026/07/31 07:02 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 41619
output: 27
thoughts: 22
Thoughts: Here's my summary, as though I'm thinking these thoughts:
**Quick GadgetFS Check & Configuration Review**
Alright, that `gadgetfs_disconnect` function seems to be behaving as expected, no red flags there. Now, let's circle back and give the `dev_config` structure another once-over. Need to ensure everything is set up correctly in that configuration. Gotta make sure everything lines up, especially since we just confirmed the disconnect routine seems good. Need to be thorough here.
|
| 259/4 |
2026/07/31 07:03 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile: Name:dev_config]
Results: map[SourceCode:1800: static ssize_t
1801: dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1802: {
1803: struct dev_data *dev = fd->private_data;
1804: ssize_t value, length = len;
1805: unsigned total;
1806: u32 tag;
1807: char *kbuf;
1808:
1809: spin_lock_irq(&dev->lock);
1810: if (dev->state > STATE_DEV_OPENED) {
1811: value = ep0_write(fd, buf, len, ptr);
1812: spin_unlock_irq(&dev->lock);
1813: return value;
1814: }
1815: spin_unlock_irq(&dev->lock);
1816:
1817: if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||
1818: (len > PAGE_SIZE * 4))
1819: return -EINVAL;
1820:
1821: /* we might need to change message format someday */
1822: if (copy_from_user (&tag, buf, 4))
1823: return -EFAULT;
1824: if (tag != 0)
1825: return -EINVAL;
1826: buf += 4;
1827: length -= 4;
1828:
1829: kbuf = memdup_user(buf, length);
1830: if (IS_ERR(kbuf))
1831: return PTR_ERR(kbuf);
1832:
1833: spin_lock_irq (&dev->lock);
1834: value = -EINVAL;
1835: if (dev->buf) {
1836: spin_unlock_irq(&dev->lock);
1837: kfree(kbuf);
1838: return value;
1839: }
1840: dev->buf = kbuf;
1841:
1842: /* full or low speed config */
1843: dev->config = (void *) kbuf;
1844: total = le16_to_cpu(dev->config->wTotalLength);
1845: if (!is_valid_config(dev->config, total) ||
1846: total > length - USB_DT_DEVICE_SIZE)
1847: goto fail;
1848: kbuf += total;
1849: length -= total;
1850:
1851: /* optional high speed config */
1852: if (kbuf [1] == USB_DT_CONFIG) {
1853: dev->hs_config = (void *) kbuf;
1854: total = le16_to_cpu(dev->hs_config->wTotalLength);
1855: if (!is_valid_config(dev->hs_config, total) ||
1856: total > length - USB_DT_DEVICE_SIZE)
1857: goto fail;
1858: kbuf += total;
1859: length -= total;
1860: } else {
1861: dev->hs_config = NULL;
1862: }
1863:
1864: /* could support multiple configs, using another encoding! */
1865:
1866: /* device descriptor (tweaked for paranoia) */
1867: if (length != USB_DT_DEVICE_SIZE)
1868: goto fail;
1869: dev->dev = (void *)kbuf;
1870: if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1871: || dev->dev->bDescriptorType != USB_DT_DEVICE
1872: || dev->dev->bNumConfigurations != 1)
1873: goto fail;
1874: dev->dev->bcdUSB = cpu_to_le16 (0x0200);
1875:
1876: /* triggers gadgetfs_bind(); then we can enumerate. */
1877: spin_unlock_irq (&dev->lock);
1878: if (dev->hs_config)
1879: gadgetfs_driver.max_speed = USB_SPEED_HIGH;
1880: else
1881: gadgetfs_driver.max_speed = USB_SPEED_FULL;
1882:
1883: value = usb_gadget_register_driver(&gadgetfs_driver);
1884: if (value != 0) {
1885: spin_lock_irq(&dev->lock);
1886: goto fail;
1887: } else {
1888: /* at this point "good" hardware has for the first time
1889: * let the USB the host see us. alternatively, if users
1890: * unplug/replug that will clear all the error state.
1891: *
1892: * note: everything running before here was guaranteed
1893: * to choke driver model style diagnostics. from here
1894: * on, they can work ... except in cleanup paths that
1895: * kick in after the ep0 descriptor is closed.
1896: */
1897: value = len;
1898: dev->gadget_registered = true;
1899: }
1900: return value;
1901:
1902: fail:
1903: dev->config = NULL;
1904: dev->hs_config = NULL;
1905: dev->dev = NULL;
1906: spin_unlock_irq (&dev->lock);
1907: pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev);
1908: kfree (dev->buf);
1909: dev->buf = NULL;
1910: return value;
1911: }
SourceFile:drivers/usb/gadget/legacy/inode.c]
|
| 260/4 |
2026/07/31 07:03 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 43491
output: 15
thoughts: 98
Thoughts: **Analysis of the 'fail' Path in `dev_config`**
Okay, so looking at this `fail` path in `dev_config`, it's doing precisely what I'd expect – clearing `dev->config`, `dev->hs_config`, `dev->dev`, and freeing `dev->buf`. This is textbook error handling. Now, let's see... ah, right. The historical context provided references this commit: `501e38a5531e ("usb: gadget: clear related members when goto fail")`. And that's the key. This confirms that the problem was identified and addressed previously. Based on this, it is pretty clear that this fix is already implemented correctly. Therefore, I can confidently say that the fix appears to be complete and correct. I'll get to the final response now.
|
| 261/4 |
2026/07/31 07:03 |
tool |
patch-diff |
0m
Args:
Results: map[Output:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..1a05819c0 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1668,46 +1668,52 @@ static struct dev_data *the_device;
static int gadgetfs_bind(struct usb_gadget *gadget,
struct usb_gadget_driver *driver)
{
struct dev_data *dev = the_device;
if (!dev)
return -ESRCH;
if (0 != strcmp (CHIP, gadget->name)) {
pr_err("%s expected %s controller not %s\n",
shortname, CHIP, gadget->name);
return -ENODEV;
}
set_gadget_data (gadget, dev);
dev->gadget = gadget;
gadget->ep0->driver_data = dev;
/* preallocate control response and buffer */
dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
if (!dev->req)
goto enomem;
dev->req->context = NULL;
dev->req->complete = epio_complete;
if (activate_ep_files (dev) < 0)
goto enomem;
INFO (dev, "bound to %s driver\n", gadget->name);
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_UNCONNECTED;
spin_unlock_irq(&dev->lock);
get_dev (dev);
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
static void
gadgetfs_disconnect (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
unsigned long flags;
spin_lock_irqsave (&dev->lock, flags);
]
|
| 262/4 |
2026/07/31 07:03 |
llm |
patch-generator |
0m
Model:
Tokens:
input: 44457
output: 545
thoughts: 13
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Finalizing the Analysis**
That patch is flawless – every test case passed, the code is clean, the documentation is spot-on. Now, it's time to craft the definitive explanation. I need to synthesize everything: the problem, the solution's elegance, the performance implications, and the potential edge cases I addressed. This isn't just a code dump; it's about conveying the "why" as clearly as the "what." I'll ensure the rationale behind the design choices is crystal clear, especially for the more subtle aspects that might not be immediately obvious. It needs to be a concise and compelling narrative that demonstrates the depth of understanding that went into this implementation. This final explanation is where this work truly earns its keep.
|
| 263/3 |
2026/07/31 07:03 |
action |
test-patch |
29m
Results: map[PatchDiff:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..1a05819c0 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,13 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
TestError:]
|
| 264/1 |
2026/07/31 07:33 |
action |
apply-patch |
0m
Results:
|
| 265/1 |
2026/07/31 07:33 |
action |
init-style-items |
0m
Results:
|
| 266/1 |
2026/07/31 07:33 |
loop |
|
15m
|
| 267/2 |
2026/07/31 07:33 |
iteration |
0 |
15m
|
| 268/3 |
2026/07/31 07:33 |
agent |
patch-formatter |
0m
Model:
Instruction:
You are an expert Linux kernel developer tasked with formatting a kernel patch.
Your objective is purely formatting: you must ensure the patch complies with the kernel's coding style,
conforms to the surrounding code rules, and passes checkpatch.pl, while preserving the code logic exactly as it is.
You should stop once the requested formatting changes are done and checkpatch.pl is happy.
Do not question the requested changes unless they are obviously wrong.
If the code already conforms to the requested changes, surrounding code rules,
and checkpatch.pl is happy, you should just finish your task.
WARNING: The clang-format tool may break the formatting of the surrounding code (like manual alignment).
Use it with caution. We want to make the change fit into the existing formatting as much as possible.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The current patch diff is:
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..1a05819c0 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,13 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
Use the provided tools to format the patch.
Reply: I have formatted the patch to comply with the Linux kernel's coding style guidelines. The spaces between the function names and the open parenthesis in the newly added function calls (`usb_ep_free_request` and `set_gadget_data`) have been removed.
The patch now successfully passes `checkpatch.pl` with 0 errors and 0 warnings.
|
| 269/4 |
2026/07/31 07:33 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 4551
output: 9
thoughts: 311
Thoughts: **Patch Formatting Analysis**
Okay, so the user wants me to format this patch. Before I dive in, let's take a look at it. First things first, I should probably run `checkpatch` on it. Actually, before I do that, let me just quickly glance at the diff itself to understand the changes.
Okay, I see the changes now. Let's see what `checkpatch` thinks of it.
|
| 270/4 |
2026/07/31 07:33 |
tool |
checkpatch |
0m
Results: map[Output:WARNING: space prohibited between function name and open parenthesis '('
#11: FILE: drivers/usb/gadget/legacy/inode.c:1704:
+ usb_ep_free_request (gadget->ep0, dev->req);
WARNING: space prohibited between function name and open parenthesis '('
#16: FILE: drivers/usb/gadget/legacy/inode.c:1709:
+ set_gadget_data (gadget, NULL);
total: 0 errors, 2 warnings, 14 lines checked
NOTE: For some of the reported defects, checkpatch may be able to
mechanically convert to the typical style using --fix or --fix-inplace.
Your patch has style problems, please review.
NOTE: If any of the errors are false positives, please report
them to the maintainer, see CHECKPATCH in MAINTAINERS.
]
|
| 271/4 |
2026/07/31 07:33 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 5175
output: 41
thoughts: 107
Thoughts: **Addressing a Style Warning in Kernel Code**
Okay, so `checkpatch` is flagging a style violation in my recent USB gadget code update. It seems I have some prohibited spaces – specifically, the warning is "space prohibited between function name and open parenthesis '('". This is happening in two places: `usb_ep_free_request (gadget->ep0, dev->req);` and `set_gadget_data (gadget, NULL);`.
Right, let's dive into this. I'll need to see the surrounding context to understand the best way to address this. I'll need to check the code in `drivers/usb/gadget/legacy/inode.c`, probably around line 1700, to see the calls in context and determine the best code style for this section. I need to make the correct edits.
|
| 272/4 |
2026/07/31 07:33 |
tool |
read-file |
0m
Args: map[File:drivers/usb/gadget/legacy/inode.c FirstLine:1680 LineCount:40]
Results: map[Contents:1680:
1681: set_gadget_data (gadget, dev);
1682: dev->gadget = gadget;
1683: gadget->ep0->driver_data = dev;
1684:
1685: /* preallocate control response and buffer */
1686: dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1687: if (!dev->req)
1688: goto enomem;
1689: dev->req->context = NULL;
1690: dev->req->complete = epio_complete;
1691:
1692: if (activate_ep_files (dev) < 0)
1693: goto enomem;
1694:
1695: INFO (dev, "bound to %s driver\n", gadget->name);
1696: spin_lock_irq(&dev->lock);
1697: dev->state = STATE_DEV_UNCONNECTED;
1698: spin_unlock_irq(&dev->lock);
1699: get_dev (dev);
1700: return 0;
1701:
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
1705: }
1706:
1707: static void
1708: gadgetfs_disconnect (struct usb_gadget *gadget)
1709: {
1710: struct dev_data *dev = get_gadget_data (gadget);
1711: unsigned long flags;
1712:
1713: spin_lock_irqsave (&dev->lock, flags);
1714: if (dev->state == STATE_DEV_UNCONNECTED)
1715: goto exit;
1716: dev->state = STATE_DEV_UNCONNECTED;
1717:
1718: INFO (dev, "disconnected\n");
1719: next_event (dev, GADGETFS_DISCONNECT);
]
|
| 273/4 |
2026/07/31 07:33 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 6092
output: 27
thoughts: 372
Thoughts: **Analyzing a USB Gadget Driver Patch**
Okay, here's what I'm thinking. I've got this patch diff for `drivers/usb/gadget/legacy/inode.c`, and I need to figure out what's going on. First, let's take a look at the diff itself. It looks like it's changing the `enomem` label in `gadgetfs_bind`. It appears to be removing the simple call to `gadgetfs_unbind(gadget)` and replacing it with a more involved cleanup procedure.
Now, a crucial question arises: *Is this patch already applied?* The repository could already have this fix, or this might be a new patch waiting to be merged. The current file contents look like:
```c
1702: enomem:
1703: gadgetfs_unbind (gadget);
1704: return -ENOMEM;
```
Aha! It seems the patch has *not* been applied yet. The original code has `gadgetfs_unbind (gadget);`, and the patch would remove that, and perform more granular cleanup. I need to be sure before I start to make changes or merge this.
So, the next step is crystal clear. I need to check the current state of the repository. I'll need to use `patch-diff` or some similar tool to compare the proposed change with what's actually in the repository to make a definitive determination.
|
| 274/4 |
2026/07/31 07:33 |
tool |
patch-diff |
0m
Args: map[File:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..1a05819c0 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1668,46 +1668,52 @@ static struct dev_data *the_device;
static int gadgetfs_bind(struct usb_gadget *gadget,
struct usb_gadget_driver *driver)
{
struct dev_data *dev = the_device;
if (!dev)
return -ESRCH;
if (0 != strcmp (CHIP, gadget->name)) {
pr_err("%s expected %s controller not %s\n",
shortname, CHIP, gadget->name);
return -ENODEV;
}
set_gadget_data (gadget, dev);
dev->gadget = gadget;
gadget->ep0->driver_data = dev;
/* preallocate control response and buffer */
dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
if (!dev->req)
goto enomem;
dev->req->context = NULL;
dev->req->complete = epio_complete;
if (activate_ep_files (dev) < 0)
goto enomem;
INFO (dev, "bound to %s driver\n", gadget->name);
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_UNCONNECTED;
spin_unlock_irq(&dev->lock);
get_dev (dev);
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
static void
gadgetfs_disconnect (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
unsigned long flags;
spin_lock_irqsave (&dev->lock, flags);
]
|
| 275/4 |
2026/07/31 07:33 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 7486
output: 217
thoughts: 555
Thoughts: **Addressing the Formatting Warnings**
Okay, so the patch is already integrated, which is a good starting point. However, `checkpatch` is flagging some formatting inconsistencies. Specifically, it's complaining about spaces before the open parenthesis in a couple of function calls within the added code in `drivers/usb/gadget/legacy/inode.c`: `usb_ep_free_request (gadget->ep0, dev->req)` and `set_gadget_data (gadget, NULL)`.
The irritating thing is that, after a quick scan, it appears that the existing code in this very file has *plenty* of instances where spaces *are* present before the parentheses in function calls! I see examples like `set_gadget_data (gadget, dev);`, `strcmp (CHIP, gadget->name)`, `usb_ep_alloc_request (gadget->ep0, GFP_KERNEL)`, and `activate_ep_files (dev)`. It's a bit hypocritical of `checkpatch`, but no matter. The instructions are clear: adhere to the kernel's style and make `checkpatch` happy.
The prompt specified that my objective is pure formatting, so that's where I'll focus. Given that this is a *new* addition, I'll assume `checkpatch` is right to demand the *absence* of the space.
Therefore, the fix is straightforward: I need to remove those spaces. I'll change:
* `usb_ep_free_request (gadget->ep0, dev->req);` to `usb_ep_free_request(gadget->ep0, dev->req);`
* `set_gadget_data (gadget, NULL);` to `set_gadget_data(gadget, NULL);`
I'll use the editor to apply these changes. Then, I'll re-run `checkpatch` and call it a day, job done.
|
| 276/4 |
2026/07/31 07:33 |
tool |
codeeditor |
0m
Args: map[CurrentCode:enomem:
if (dev->req) {
usb_ep_free_request (gadget->ep0, dev->req);
dev->req = NULL;
}
gadget->ep0->driver_data = NULL;
dev->gadget = NULL;
set_gadget_data (gadget, NULL);
return -ENOMEM; NewCode:enomem:
if (dev->req) {
usb_ep_free_request(gadget->ep0, dev->req);
dev->req = NULL;
}
gadget->ep0->driver_data = NULL;
dev->gadget = NULL;
set_gadget_data(gadget, NULL);
return -ENOMEM; SourceFile:drivers/usb/gadget/legacy/inode.c]
Results:
|
| 277/4 |
2026/07/31 07:33 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 8688
output: 9
thoughts: 16
Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:
**Assessing Code Quality: Time for `checkpatch`**
Alright, the code's at a point where I'm reasonably confident in the core functionality, and I've addressed the obvious issues. Now it's time to run a more rigorous sanity check. I need to make sure I haven't missed any glaring style violations, coding standard breaches, or subtle inconsistencies that could cause problems down the line. That means it's `checkpatch` time. It's not a silver bullet, of course; it won't catch logic errors or design flaws. But, it's a critical tool for quickly identifying those easily-avoidable issues that can waste time during review and merge. Let's see what it has to say and go from there.
|
| 278/4 |
2026/07/31 07:33 |
tool |
checkpatch |
0m
Results: map[Output:total: 0 errors, 0 warnings, 14 lines checked
Your patch has no obvious style problems and is ready for submission.
]
|
| 279/4 |
2026/07/31 07:33 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 8941
output: 27
thoughts: 23
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Kernel Patch Analysis: A Quick Win**
Alright, that's a relief! `checkpatch` is finally giving me the green light – no more nagging style issues or potential coding gotchas. The initial review seems clean. But, as we all know, a green check from `checkpatch` doesn't *guarantee* perfection, and I've been burned by that assumption before.
Best practice dictates I still need a second set of eyes, even if the tools say everything's rosy. Let's fire up `patch-diff` and give this diff a solid once-over. This will help verify I didn't miss something subtle during the first pass, especially with the more complex patches. I am looking for any last minute anomalies, such as formatting issues that the tool didn't pick up on, or any regressions that the patch might have introduced. It's time to confirm that the proposed changes are fully sound, before I push this forward. This double-check is a routine and necessary step in the process.
|
| 280/4 |
2026/07/31 07:33 |
tool |
patch-diff |
0m
Args: map[File:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..365f9ab4d 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1668,46 +1668,52 @@ static struct dev_data *the_device;
static int gadgetfs_bind(struct usb_gadget *gadget,
struct usb_gadget_driver *driver)
{
struct dev_data *dev = the_device;
if (!dev)
return -ESRCH;
if (0 != strcmp (CHIP, gadget->name)) {
pr_err("%s expected %s controller not %s\n",
shortname, CHIP, gadget->name);
return -ENODEV;
}
set_gadget_data (gadget, dev);
dev->gadget = gadget;
gadget->ep0->driver_data = dev;
/* preallocate control response and buffer */
dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
if (!dev->req)
goto enomem;
dev->req->context = NULL;
dev->req->complete = epio_complete;
if (activate_ep_files (dev) < 0)
goto enomem;
INFO (dev, "bound to %s driver\n", gadget->name);
spin_lock_irq(&dev->lock);
dev->state = STATE_DEV_UNCONNECTED;
spin_unlock_irq(&dev->lock);
get_dev (dev);
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request(gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data(gadget, NULL);
return -ENOMEM;
}
static void
gadgetfs_disconnect (struct usb_gadget *gadget)
{
struct dev_data *dev = get_gadget_data (gadget);
unsigned long flags;
spin_lock_irqsave (&dev->lock, flags);
]
|
| 281/4 |
2026/07/31 07:33 |
llm |
patch-formatter |
0m
Model:
Tokens:
input: 9897
output: 77
thoughts: 35
Thoughts: **Finalizing the Response**
Okay, the diff is looking pristine, absolutely squeaky clean. I ran `checkpatch.pl` just to be certain, and it's reporting zero errors and zero warnings. That's exactly what I needed to see. The task is clearly done, completed to the expected standard. Now I can move on to crafting the final response, knowing that the underlying work is solid. Time to assemble the output and present it.
|
| 282/3 |
2026/07/31 07:33 |
action |
test-patch-inplace |
14m
Results: map[PatchDiff:diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..365f9ab4d 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,13 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request(gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data(gadget, NULL);
return -ENOMEM;
}
TestError:]
|
| 283/3 |
2026/07/31 07:48 |
action |
run-checkpatch |
0m
Results: map[CheckpatchOutput:total: 0 errors, 0 warnings, 14 lines checked
Your patch has no obvious style problems and is ready for submission.
NeedRefinement:false]
|
| 284/1 |
2026/07/31 07:48 |
agent |
fixes-finder |
6m
Model:
Results: map[FixesHash:1da177e4c3f41524e886b7f1b8a0c1fc7321cac2]
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:
==================================================================
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Not tainted syzkaller #1 PREEMPT
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
print_address_description+0xb0/0x238 mm/kasan/report.c:378
print_report+0x68/0x84 mm/kasan/report.c:482
kasan_report+0x8c/0xc4 mm/kasan/report.c:595
__kasan_check_byte+0x3c/0x54 mm/kasan/common.c:574
kasan_check_byte include/linux/kasan.h:402 [inline]
lock_acquire+0xa4/0x364 kernel/locking/lockdep.c:5842
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Allocated by task 5241:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_alloc_info+0x44/0x54 mm/kasan/generic.c:570
poison_kmalloc_redzone mm/kasan/common.c:398 [inline]
__kasan_kmalloc+0x9c/0xb4 mm/kasan/common.c:415
kasan_kmalloc include/linux/kasan.h:263 [inline]
__kmalloc_cache_noprof+0x2e8/0x5ec mm/slub.c:5489
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
dev_new drivers/usb/gadget/legacy/inode.c:176 [inline]
gadgetfs_fill_super+0x19c/0x370 drivers/usb/gadget/legacy/inode.c:2054
vfs_get_super+0xb8/0x148 fs/super.c:1273
get_tree_single+0x30/0x40 fs/super.c:1300
gadgetfs_get_tree+0x28/0x38 drivers/usb/gadget/legacy/inode.c:2085
vfs_get_tree+0x90/0x28c fs/super.c:1700
fc_mount+0x24/0xac fs/namespace.c:1198
do_new_mount_fc fs/namespace.c:3765 [inline]
do_new_mount+0x2a4/0x538 fs/namespace.c:3841
path_mount+0x5f0/0xa88 fs/namespace.c:4161
do_mount+0xe8/0x148 fs/namespace.c:4174
__do_sys_mount fs/namespace.c:4390 [inline]
__se_sys_mount fs/namespace.c:4367 [inline]
__arm64_sys_mount+0x334/0x380 fs/namespace.c:4367
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Freed by task 5331:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_free_info+0x58/0x70 mm/kasan/generic.c:584
poison_slab_object mm/kasan/common.c:253 [inline]
__kasan_slab_free+0x74/0xa4 mm/kasan/common.c:285
kasan_slab_free include/linux/kasan.h:235 [inline]
slab_free_hook mm/slub.c:2677 [inline]
slab_free mm/slub.c:6377 [inline]
kfree+0x188/0x690 mm/slub.c:6692
put_dev+0x8c/0xf8 drivers/usb/gadget/legacy/inode.c:169
dev_release+0x100/0x15c drivers/usb/gadget/legacy/inode.c:1215
__fput+0x338/0x74c fs/file_table.c:512
____fput+0x20/0x30 fs/file_table.c:540
task_work_run+0x1cc/0x25c kernel/task_work.c:233
resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]
__exit_to_user_mode_loop kernel/entry/common.c:70 [inline]
exit_to_user_mode_loop+0x10c/0x17c kernel/entry/common.c:101
__exit_to_user_mode_prepare include/linux/irq-entry-common.h:207 [inline]
syscall_exit_to_user_mode_prepare include/linux/irq-entry-common.h:230 [inline]
arm64_syscall_exit_to_user_mode arch/arm64/kernel/entry-common.c:88 [inline]
el0_svc+0x18c/0x260 arch/arm64/kernel/entry-common.c:737
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
The buggy address belongs to the object at ffff0000dbe16000
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 24 bytes inside of
freed 1024-byte region [ffff0000dbe16000, ffff0000dbe16400)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff0000dbe15000 pfn:0x11be10
head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
flags: 0x5ffc00000000240(workingset|head|node=0|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
raw: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
head: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000003 fffffdffc36f8401 00000000ffffffff 00000000ffffffff
head: ffffffffffffffff 0000000000000000 00000000ffffffff 0000000000000008
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff0000dbe15f00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff0000dbe15f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff0000dbe16000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff0000dbe16080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff0000dbe16100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
------------[ cut here ]------------
UBSAN: array-index-out-of-bounds in /app/workdir/cache/src/3735123449433f9e6f9fb5b55ddd9994cbcf15f0/kernel/locking/qspinlock.h:68:9
index 13031 is out of range for type 'unsigned long[8]'
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
ubsan_epilogue+0x14/0x48 lib/ubsan.c:233
__ubsan_handle_out_of_bounds+0xd0/0xf8 lib/ubsan.c:455
decode_tail kernel/locking/qspinlock.h:68 [inline]
queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
---[ end trace ]---
Unable to handle kernel paging request at virtual address ffff800088b48710
KASAN: probably user-memory-access in range [0x0000000445a43880-0x0000000445a43887]
Mem abort info:
ESR = 0x0000000096000047
EC = 0x25: DABT (current EL), IL = 32 bits
SET = 0, FnV = 0
EA = 0, S1PTW = 0
FSC = 0x07: level 3 translation fault
Data abort info:
ISV = 0, ISS = 0x00000047, ISS2 = 0x00000000
CM = 0, WnR = 1, TnD = 0, TagAccess = 0
GCS = 0, Overlay = 0, DirtyBit = 0
swapper pgtable: 4k pages, 48-bit VAs, pgdp=000000021aeb5000
[ffff800088b48710] pgd=0000000000000000, p4d=10000002211ac003, pud=10000002211ad003, pmd=10000002211b1003, pte=0000000000000000
Internal error: Oops: 0000000096000047 [#1] SMP
Modules linked in:
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
pstate: 834000c5 (Nzcv daIF +PAN -UAO +TCO +DIT -SSBS BTYPE=--)
pc : queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:288
lr : decode_tail kernel/locking/qspinlock.h:68 [inline]
lr : queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
sp : ffff800097c37560
x29: ffff800097c37600 x28: ffff800088b48710 x27: 1fffe00019980afa
x26: 1fffe0001b7c2c00 x25: ffff0001add9f708 x24: dfff800000000000
x23: ffff700012f86eb0 x22: ffff0001add9f700 x21: 1fffe00035bb3ee0
x20: ffff0000ccc057d0 x19: ffff0000dbe16000 x18: 0000000000000000
x17: 3d3d3d3d3d3d3d3d x16: 0000000000000001 x15: 0000000000000000
x14: 0000000000000000 x13: 0000000000000001 x12: 0000000000000004
x11: ffff700011474c6c x10: ffff800088b48700 x9 : ffff800088b48710
x8 : 0000000000000000 x7 : 0000000000000001 x6 : ffff80008048d694
x5 : 0000000000000000 x4 : 0000000000000000 x3 : ffff8000802f6c98
x2 : 0000000000000002 x1 : 0000000000000004 x0 : ffff0001add9f708
Call trace:
queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:291 (P)
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Code: aa1c03e0 968a785a 910022c0 52800081 (f9000396)
---[ end trace 0000000000000000 ]---
----------------
Code disassembly (best guess):
0: aa1c03e0 mov x0, x28
4: 968a785a bl 0xfffffffffa29e16c
8: 910022c0 add x0, x22, #0x8
c: 52800081 mov w1, #0x4 // #4
* 10: f9000396 str x22, [x28] <-- trapping instruction
The explanation of the root cause is:
The root cause of this KASAN slab-use-after-free is a reference counting bug in the error path of `gadgetfs_bind()` in `drivers/usb/gadget/legacy/inode.c`.
When the gadget driver is being bound, `gadgetfs_bind()` performs several initialization steps. If it succeeds, it takes a reference to the `dev` object by calling `get_dev(dev)` at the very end of the function. This reference is meant to be balanced by a call to `put_dev(dev)` inside `gadgetfs_unbind()` when the driver is eventually unbound.
However, if `gadgetfs_bind()` fails midway (e.g., due to the fault injection causing `activate_ep_files()` to fail), it jumps to the `enomem` label and calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**.
### Detailed Trace
1. **Initialization**: When the gadgetfs is mounted, `gadgetfs_fill_super()` calls `dev_new()`, which initializes the `dev` object with a refcount of `1`.
2. **First Open**: The reproducer opens the `ep0` file (`dummy_udc`). This calls `gadget_dev_open()`, which increments the refcount to `2` via `get_dev(dev)`.
3. **Configuration**: The reproducer writes to the `ep0` file descriptor, triggering `dev_config()`. This parses the descriptors and calls `usb_gadget_register_driver()`, which in turn calls `gadgetfs_bind()`.
4. **Fault Injection**: Inside `gadgetfs_bind()`, `activate_ep_files()` fails due to the injected memory allocation failure.
5. **The Bug**: `gadgetfs_bind()` jumps to the `enomem` label and calls `gadgetfs_unbind()`. `gadgetfs_unbind()` calls `put_dev(dev)`, dropping the refcount to `1`. (It should have remained `2` because `gadgetfs_bind()` never took its reference).
6. **File Close**: The `write()` syscall returns `-ENOMEM`. The reproducer process exits (or closes the file descriptor), triggering `dev_release()`. This calls `put_dev(dev)`, dropping the refcount to `0`. The `dev` object is freed.
7. **Use-After-Free**: The reproducer (or another thread) opens the `ep0` file again. `gadget_dev_open()` is called, which accesses the freed `dev` object via `inode->i_private` to acquire `dev->lock`, resulting in the KASAN slab-use-after-free crash.
### The Fix
Instead of calling `gadgetfs_unbind()` on failure, `gadgetfs_bind()` should manually undo the specific initialization steps it performed before the failure.
Note that `activate_ep_files()` already cleans up after itself if it fails (by calling `destroy_ep_files()`), so we only need to free `dev->req` (if it was allocated) and clear the gadget data pointers.
```c
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,12 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
```
By doing this manual cleanup, we avoid the unbalanced `put_dev(dev)`, prevent `dev->state` from being incorrectly set to `STATE_DEV_UNBOUND` (which would prevent the user from retrying the configuration write), and avoid redundant calls to `destroy_ep_files()`.
The patch that fixes the bug is:
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..365f9ab4d 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,13 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request(gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data(gadget, NULL);
return -ENOMEM;
}
Search for the commit(s) that introduced this bug.
|
| 285/2 |
2026/07/31 07:48 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 11614
output: 56
thoughts: 270
Thoughts: **Analyzing a KASAN Slab-Use-After-Free in GadgetFS**
Okay, so I'm looking at a KASAN slab-use-after-free error, specifically within `__raw_spin_lock_irq` when `gadget_dev_open` is called. It looks like the root cause is a reference counting problem that's buried deep inside `gadgetfs_bind()` in `drivers/usb/gadget/legacy/inode.c` – or maybe the newer path if it was moved.
The way I see it, when `gadgetfs_bind()` fails, it jumps to the `enomem:` label, and from there, it calls `gadgetfs_unbind(gadget)`. The problem is that `gadgetfs_unbind()` calls `put_dev(dev)`. And it appears this drops a reference that wasn't properly acquired in the first place. You see, a `get_dev(dev)` is *only* called at the very end of a successful `gadgetfs_bind()`. The fix seems pretty straightforward: get rid of the `gadgetfs_unbind(gadget)` call and instead implement manual cleanup directly in the `gadgetfs_bind()` function.
To really nail this down and understand how this bug crept in, I'm going to delve into the history of `gadgetfs_bind()` in the kernel source. I'll need to use `git log` to trace when `gadgetfs_unbind()` was added to the `enomem` path. Was it there from the beginning, or did it get introduced later? That information will provide valuable context on how this bug was introduced and if it was present in upstream versions. Understanding the history here is crucial to assess the risk and prevent such errors from resurfacing in the future.
|
| 286/2 |
2026/07/31 07:48 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_unbind.*\(gadget\) SourcePath:drivers/usb/gadget/legacy/inode.c SymbolName:gadgetfs_bind]
Results:
|
| 287/2 |
2026/07/31 07:49 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 12344
output: 28
thoughts: 44
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Debugging a Potential `gadgetfs_bind` Issue**
Alright, so I'm hitting a snag here. That `gadgetfs_bind` symbol, or maybe the file containing it, doesn't seem to be where I expect it. Could be a simple typo, but it's more likely a refactoring or relocation in the code base. I'm going to quickly check the revision history of `drivers/usb/gadget/legacy/inode.c`. That's the most logical place to start looking for its definition or any recent changes that might have involved the symbol. I need to understand if the function signature or location has been modified. Seeing the commit history around this file will likely offer the quickest path to resolving this. This should tell me if the name has changed, if the function was moved, or if the relevant functionality was deprecated.
|
| 288/2 |
2026/07/31 07:49 |
tool |
git-log |
0m
Args: map[PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
69050f8d6d07 treewide: Replace kmalloc with kmalloc_obj for non-scalar types
57db9d428ba5 convert gadgetfs
b65e3b11e923 gadgetfs: switch to simple_remove_by_name()
f99b3917789d fs: rename generic_delete_inode() and generic_drop_inode()
bad356bb50e6 functionfs, gadgetfs: use simple_recursive_removal()
bd3cf1a9396e USB: gadget: Replace deprecated strncpy() with strscpy()
5b6dc50e9ed8 USB: gadget: Use str_enable_disable-like helpers
cb787f4ac0c2 [tree-wide] finally take no_llseek out
69f73ca33d6b legacy: convert to new timestamp accessors
]
|
| 289/2 |
2026/07/31 07:49 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 12869
output: 40
thoughts: 27
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating a USB Gadget File System Bind**
Right, let's dive into this. I need to understand how this gadget file system interface gets bound, specifically focusing on `gadgetfs_bind`. My immediate hunch is that it's likely handled within the legacy USB gadget driver code. So, I'll start by searching for that function, `gadgetfs_bind`, within the `drivers/usb/gadget/legacy/inode.c` file. That seems like the most logical place to begin digging. The inode-related files often contain the core logic for mounting and associating file system structures with USB gadget devices. Knowing this is a legacy driver, this particular file seems like a good starting point. Let's see what we can find. I anticipate finding information about how the file system structure is created and how it links with the USB gadget device's control mechanisms.
|
| 290/2 |
2026/07/31 07:49 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_unbind PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
]
|
| 291/2 |
2026/07/31 07:49 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 13180
output: 38
thoughts: 35
Thoughts: Okay, here's my interpretation of those thoughts, presented as a first-person expert summary:
**Digging into a USB Gadget Issue**
Right, so a file move happened in commit `8443f2d2b778`. That’s the first piece of the puzzle. Now, I need to understand what this move *means* in the broader context of the system. Given that context, my initial suspicion is that this move is relevant to the USB gadget implementation. Therefore, I need to check the relevant code for any implications of this move. My gut says to start with `drivers/usb/gadget/inode.c`. That file is a likely candidate, given its place in the gadget framework and that the description is vague. I’ll open that file and see what changed around that commit. Let's see if this move sheds light on a potential bug or change in functionality. I need to understand the impact of that relocation.
|
| 292/2 |
2026/07/31 07:49 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_unbind PathPrefix:drivers/usb/gadget/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 293/2 |
2026/07/31 07:49 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 13516
output: 37
thoughts: 60
Thoughts: Here's my summary, as though I'm thinking through this process:
**Diving into the Git History**
Okay, so I'm starting with this commit hash, `1da177e4c3f4`. That's a familiar pattern, looks like the very first commit to the repository. Now I want to understand how a specific function is implemented. In this case, `gadgetfs_bind`. My instinct is to zero in on the `drivers/usb/gadget/inode.c` file. Time to open that file up and have a look at where that function lives. Let's see what's changed and figure out what the original purpose of this commit was.
|
| 294/2 |
2026/07/31 07:49 |
tool |
git-show |
0m
Args: map[Commit:1da177e4c3f4:drivers/usb/gadget/inode.c]
Results: map[Output:
Full output is too long, showing 1000 out of 2110 lines.
[/*
* inode.c -- user mode filesystem api for usb gadget controllers
*
* Copyright (C) 2003-2004 David Brownell
* Copyright (C) 2003 Agilent Technologies
*
* 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
*/
// #define DEBUG /* data to help fault diagnosis */
// #define VERBOSE /* extra debug messages (success too) */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/uts.h>
#include <linux/wait.h>
#include <linux/compiler.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/moduleparam.h>
#include <linux/usb_gadgetfs.h>
#include <linux/usb_gadget.h>
/*
* The gadgetfs API maps each endpoint to a file descriptor so that you
* can use standard synchronous read/write calls for I/O. There's some
* O_NONBLOCK and O_ASYNC/FASYNC style i/o support. Example usermode
* drivers show how this works in practice. You can also use AIO to
* eliminate I/O gaps between requests, to help when streaming data.
*
* Key parts that must be USB-specific are protocols defining how the
* read/write operations relate to the hardware state machines. There
* are two types of files. One type is for the device, implementing ep0.
* The other type is for each IN or OUT endpoint. In both cases, the
* user mode driver must configure the hardware before using it.
*
* - First, dev_config() is called when /dev/gadget/$CHIP is configured
* (by writing configuration and device descriptors). Afterwards it
* may serve as a source of device events, used to handle all control
* requests other than basic enumeration.
*
* - Then either immediately, or after a SET_CONFIGURATION control request,
* ep_config() is called when each /dev/gadget/ep* file is configured
* (by writing endpoint descriptors). Afterwards these files are used
* to write() IN data or to read() OUT data. To halt the endpoint, a
* "wrong direction" request is issued (like reading an IN endpoint).
*
* Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
* not possible on all hardware. For example, precise fault handling with
* respect to data left in endpoint fifos after aborted operations; or
* selective clearing of endpoint halts, to implement SET_INTERFACE.
*/
#define DRIVER_DESC "USB Gadget filesystem"
#define DRIVER_VERSION "24 Aug 2004"
static const char driver_desc [] = DRIVER_DESC;
static const char shortname [] = "gadgetfs";
MODULE_DESCRIPTION (DRIVER_DESC);
MODULE_AUTHOR ("David Brownell");
MODULE_LICENSE ("GPL");
/*----------------------------------------------------------------------*/
#define GADGETFS_MAGIC 0xaee71ee7
#define DMA_ADDR_INVALID (~(dma_addr_t)0)
/* /dev/gadget/$CHIP represents ep0 and the whole device */
enum ep0_state {
/* DISBLED is the initial state.
*/
STATE_DEV_DISABLED = 0,
/* Only one open() of /dev/gadget/$CHIP; only one file tracks
* ep0/device i/o modes and binding to the controller. Driver
* must always write descriptors to initialize the device, then
* the device becomes UNCONNECTED until enumeration.
*/
STATE_OPENED,
/* From then on, ep0 fd is in either of two basic modes:
* - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
* - SETUP: read/write will transfer control data and succeed;
* or if "wrong direction", performs protocol stall
*/
STATE_UNCONNECTED,
STATE_CONNECTED,
STATE_SETUP,
/* UNBOUND means the driver closed ep0, so the device won't be
* accessible again (DEV_DISABLED) until all fds are closed.
*/
STATE_DEV_UNBOUND,
};
/* enough for the whole queue: most events invalidate others */
#define N_EVENT 5
struct dev_data {
spinlock_t lock;
atomic_t count;
enum ep0_state state;
struct usb_gadgetfs_event event [N_EVENT];
unsigned ev_next;
struct fasync_struct *fasync;
u8 current_config;
/* drivers reading ep0 MUST handle control requests (SETUP)
* reported that way; else the host will time out.
*/
unsigned usermode_setup : 1,
setup_in : 1,
setup_can_stall : 1,
setup_out_ready : 1,
setup_out_error : 1,
setup_abort : 1;
/* the rest is basically write-once */
struct usb_config_descriptor *config, *hs_config;
struct usb_device_descriptor *dev;
struct usb_request *req;
struct usb_gadget *gadget;
struct list_head epfiles;
void *buf;
wait_queue_head_t wait;
struct super_block *sb;
struct dentry *dentry;
/* except this scratch i/o buffer for ep0 */
u8 rbuf [256];
};
static inline void get_dev (struct dev_data *data)
{
atomic_inc (&data->count);
}
static void put_dev (struct dev_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
/* needs no more cleanup */
BUG_ON (waitqueue_active (&data->wait));
kfree (data);
}
static struct dev_data *dev_new (void)
{
struct dev_data *dev;
dev = kmalloc (sizeof *dev, GFP_KERNEL);
if (!dev)
return NULL;
memset (dev, 0, sizeof *dev);
dev->state = STATE_DEV_DISABLED;
atomic_set (&dev->count, 1);
spin_lock_init (&dev->lock);
INIT_LIST_HEAD (&dev->epfiles);
init_waitqueue_head (&dev->wait);
return dev;
}
/*----------------------------------------------------------------------*/
/* other /dev/gadget/$ENDPOINT files represent endpoints */
enum ep_state {
STATE_EP_DISABLED = 0,
STATE_EP_READY,
STATE_EP_DEFER_ENABLE,
STATE_EP_ENABLED,
STATE_EP_UNBOUND,
};
struct ep_data {
struct semaphore lock;
enum ep_state state;
atomic_t count;
struct dev_data *dev;
/* must hold dev->lock before accessing ep or req */
struct usb_ep *ep;
struct usb_request *req;
ssize_t status;
char name [16];
struct usb_endpoint_descriptor desc, hs_desc;
struct list_head epfiles;
wait_queue_head_t wait;
struct dentry *dentry;
struct inode *inode;
};
static inline void get_ep (struct ep_data *data)
{
atomic_inc (&data->count);
}
static void put_ep (struct ep_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
put_dev (data->dev);
/* needs no more cleanup */
BUG_ON (!list_empty (&data->epfiles));
BUG_ON (waitqueue_active (&data->wait));
BUG_ON (down_trylock (&data->lock) != 0);
kfree (data);
}
/*----------------------------------------------------------------------*/
/* most "how to use the hardware" policy choices are in userspace:
* mapping endpoint roles (which the driver needs) to the capabilities
* which the usb controller has. most of those capabilities are exposed
* implicitly, starting with the driver name and then endpoint names.
*/
static const char *CHIP;
/*----------------------------------------------------------------------*/
/* NOTE: don't use dev_printk calls before binding to the gadget
* at the end of ep0 configuration, or after unbind.
*/
/* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
#define xprintk(d,level,fmt,args...) \
printk(level "%s: " fmt , shortname , ## args)
#ifdef DEBUG
#define DBG(dev,fmt,args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE
#define VDEBUG DBG
#else
#define VDEBUG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev,fmt,args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define WARN(dev,fmt,args...) \
xprintk(dev , KERN_WARNING , fmt , ## args)
#define INFO(dev,fmt,args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*----------------------------------------------------------------------*/
/* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
*
* After opening, configure non-control endpoints. Then use normal
* stream read() and write() requests; and maybe ioctl() to get more
* precise FIFO status when recovering from cancelation.
*/
static void epio_complete (struct usb_ep *ep, struct usb_request *req)
{
struct ep_data *epdata = ep->driver_data;
if (!req->context)
return;
if (req->status)
epdata->status = req->status;
else
epdata->status = req->actual;
complete ((struct completion *)req->context);
}
/* tasklock endpoint, returning when it's connected.
* still need dev->lock to use epdata->ep.
*/
static int
get_ready_ep (unsigned f_flags, struct ep_data *epdata)
{
int val;
if (f_flags & O_NONBLOCK) {
if (down_trylock (&epdata->lock) != 0)
goto nonblock;
if (epdata->state != STATE_EP_ENABLED) {
up (&epdata->lock);
nonblock:
val = -EAGAIN;
} else
val = 0;
return val;
}
if ((val = down_interruptible (&epdata->lock)) < 0)
return val;
newstate:
switch (epdata->state) {
case STATE_EP_ENABLED:
break;
case STATE_EP_DEFER_ENABLE:
DBG (epdata->dev, "%s wait for host\n", epdata->name);
if ((val = wait_event_interruptible (epdata->wait,
epdata->state != STATE_EP_DEFER_ENABLE
|| epdata->dev->state == STATE_DEV_UNBOUND
)) < 0)
goto fail;
goto newstate;
// case STATE_EP_DISABLED: /* "can't happen" */
// case STATE_EP_READY: /* "can't happen" */
default: /* error! */
pr_debug ("%s: ep %p not available, state %d\n",
shortname, epdata, epdata->state);
// FALLTHROUGH
case STATE_EP_UNBOUND: /* clean disconnect */
val = -ENODEV;
fail:
up (&epdata->lock);
}
return val;
}
static ssize_t
ep_io (struct ep_data *epdata, void *buf, unsigned len)
{
DECLARE_COMPLETION (done);
int value;
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
struct usb_request *req = epdata->req;
req->context = &done;
req->complete = epio_complete;
req->buf = buf;
req->length = len;
value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
} else
value = -ENODEV;
spin_unlock_irq (&epdata->dev->lock);
if (likely (value == 0)) {
value = wait_event_interruptible (done.wait, done.done);
if (value != 0) {
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
DBG (epdata->dev, "%s i/o interrupted\n",
epdata->name);
usb_ep_dequeue (epdata->ep, epdata->req);
spin_unlock_irq (&epdata->dev->lock);
wait_event (done.wait, done.done);
if (epdata->status == -ECONNRESET)
epdata->status = -EINTR;
} else {
spin_unlock_irq (&epdata->dev->lock);
DBG (epdata->dev, "endpoint gone\n");
epdata->status = -ENODEV;
}
}
return epdata->status;
}
return value;
}
/* handle a synchronous OUT bulk/intr/iso transfer */
static ssize_t
ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (data->desc.bEndpointAddress & USB_DIR_IN) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (unlikely (!kbuf))
goto free1;
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s read %d OUT, status %d\n",
data->name, len, value);
if (value >= 0 && copy_to_user (buf, kbuf, value))
value = -EFAULT;
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
/* handle a synchronous IN bulk/intr/iso transfer */
static ssize_t
ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (!(data->desc.bEndpointAddress & USB_DIR_IN)) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (!kbuf)
goto free1;
if (copy_from_user (kbuf, buf, len)) {
value = -EFAULT;
goto free1;
}
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s write %d IN, status %d\n",
data->name, len, value);
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
static int
ep_release (struct inode *inode, struct file *fd)
{
struct ep_data *data = fd->private_data;
/* clean up if this can be reopened */
if (data->state != STATE_EP_UNBOUND) {
data->state = STATE_EP_DISABLED;
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
put_ep (data);
return 0;
}
static int ep_ioctl (struct inode *inode, struct file *fd,
unsigned code, unsigned long value)
{
struct ep_data *data = fd->private_data;
int status;
if ((status = get_ready_ep (fd->f_flags, data)) < 0)
return status;
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL)) {
switch (code) {
case GADGETFS_FIFO_STATUS:
status = usb_ep_fifo_status (data->ep);
break;
case GADGETFS_FIFO_FLUSH:
usb_ep_fifo_flush (data->ep);
break;
case GADGETFS_CLEAR_HALT:
status = usb_ep_clear_halt (data->ep);
break;
default:
status = -ENOTTY;
}
} else
status = -ENODEV;
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return status;
}
/*----------------------------------------------------------------------*/
/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
struct kiocb_priv {
struct usb_request *req;
struct ep_data *epdata;
void *buf;
char __user *ubuf;
unsigned actual;
};
static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e)
{
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata;
int value;
local_irq_disable();
epdata = priv->epdata;
// spin_lock(&epdata->dev->lock);
kiocbSetCancelled(iocb);
if (likely(epdata && epdata->ep && priv->req))
value = usb_ep_dequeue (epdata->ep, priv->req);
else
value = -EINVAL;
// spin_unlock(&epdata->dev->lock);
local_irq_enable();
aio_put_req(iocb);
return value;
}
static ssize_t ep_aio_read_retry(struct kiocb *iocb)
{
struct kiocb_priv *priv = iocb->private;
ssize_t status = priv->actual;
/* we "retry" to get the right mm context for this: */
status = copy_to_user(priv->ubuf, priv->buf, priv->actual);
if (unlikely(0 != status))
status = -EFAULT;
else
status = priv->actual;
kfree(priv->buf);
kfree(priv);
aio_put_req(iocb);
return status;
}
static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
{
struct kiocb *iocb = req->context;
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata = priv->epdata;
/* lock against disconnect (and ideally, cancel) */
spin_lock(&epdata->dev->lock);
priv->req = NULL;
priv->epdata = NULL;
if (NULL == iocb->ki_retry
|| unlikely(0 == req->actual)
|| unlikely(kiocbIsCancelled(iocb))) {
kfree(req->buf);
kfree(priv);
iocb->private = NULL;
/* aio_complete() reports bytes-transferred _and_ faults */
if (unlikely(kiocbIsCancelled(iocb)))
aio_put_req(iocb);
else
aio_complete(iocb,
req->actual ? req->actual : req->status,
req->status);
} else {
/* retry() won't report both; so we hide some faults */
if (unlikely(0 != req->status))
DBG(epdata->dev, "%s fault %d len %d\n",
ep->name, req->status, req->actual);
priv->buf = req->buf;
priv->actual = req->actual;
kick_iocb(iocb);
}
spin_unlock(&epdata->dev->lock);
usb_ep_free_request(ep, req);
put_ep(epdata);
}
static ssize_t
ep_aio_rwtail(
struct kiocb *iocb,
char *buf,
size_t len,
struct ep_data *epdata,
char __user *ubuf
)
{
struct kiocb_priv *priv = (void *) &iocb->private;
struct usb_request *req;
ssize_t value;
priv = kmalloc(sizeof *priv, GFP_KERNEL);
if (!priv) {
value = -ENOMEM;
fail:
kfree(buf);
return value;
}
iocb->private = priv;
priv->ubuf = ubuf;
value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
if (unlikely(value < 0)) {
kfree(priv);
goto fail;
}
iocb->ki_cancel = ep_aio_cancel;
get_ep(epdata);
priv->epdata = epdata;
priv->actual = 0;
/* each kiocb is coupled to one usb_request, but we can't
* allocate or submit those if the host disconnected.
*/
spin_lock_irq(&epdata->dev->lock);
if (likely(epdata->ep)) {
req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
if (likely(req)) {
priv->req = req;
req->buf = buf;
req->length = len;
req->complete = ep_aio_complete;
req->context = iocb;
value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
if (unlikely(0 != value))
usb_ep_free_request(epdata->ep, req);
} else
value = -EAGAIN;
} else
value = -ENODEV;
spin_unlock_irq(&epdata->dev->lock);
up(&epdata->lock);
if (unlikely(value)) {
kfree(priv);
put_ep(epdata);
} else
value = -EIOCBQUEUED;
return value;
}
static ssize_t
ep_aio_read(struct kiocb *iocb, char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(epdata->desc.bEndpointAddress & USB_DIR_IN))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
iocb->ki_retry = ep_aio_read_retry;
return ep_aio_rwtail(iocb, buf, len, epdata, ubuf);
}
static ssize_t
ep_aio_write(struct kiocb *iocb, const char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(!(epdata->desc.bEndpointAddress & USB_DIR_IN)))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
if (unlikely(copy_from_user(buf, ubuf, len) != 0)) {
kfree(buf);
return -EFAULT;
}
return ep_aio_rwtail(iocb, buf, len, epdata, NULL);
}
/*----------------------------------------------------------------------*/
/* used after endpoint configuration */
static struct file_operations ep_io_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = ep_read,
.write = ep_write,
.ioctl = ep_ioctl,
.release = ep_release,
.aio_read = ep_aio_read,
.aio_write = ep_aio_write,
};
/* ENDPOINT INITIALIZATION
*
* fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
* status = write (fd, descriptors, sizeof descriptors)
*
* That write establishes the endpoint configuration, configuring
* the controller to process bulk, interrupt, or isochronous transfers
* at the right maxpacket size, and so on.
*
* The descriptors are message type 1, identified by a host order u32
* at the beginning of what's written. Descriptor order is: full/low
* speed descriptor, then optional high speed descriptor.
*/
static ssize_t
ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
struct usb_ep *ep;
u32 tag;
int value;
if ((value = down_interruptible (&data->lock)) < 0)
return value;
if (data->state != STATE_EP_READY) {
value = -EL2HLT;
goto fail;
}
value = len;
if (len < USB_DT_ENDPOINT_SIZE + 4)
goto fail0;
/* we might need to change message format someday */
if (copy_from_user (&tag, buf, 4)) {
goto fail1;
}
if (tag != 1) {
DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
goto fail0;
}
buf += 4;
len -= 4;
/* NOTE: audio endpoint extensions not accepted here;
* just don't include the extra bytes.
*/
/* full/low speed descriptor, then high speed */
if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->desc.bDescriptorType != USB_DT_ENDPOINT)
goto fail0;
if (len != USB_DT_ENDPOINT_SIZE) {
if (len != 2 * USB_DT_ENDPOINT_SIZE)
goto fail0;
if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->hs_desc.bDescriptorType
!= USB_DT_ENDPOINT) {
DBG(data->dev, "config %s, bad hs length or type\n",
data->name);
goto fail0;
}
}
value = len;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND) {
value = -ENOENT;
goto gone;
} else if ((ep = data->ep) == NULL) {
value = -ENODEV;
goto gone;
}
switch (data->dev->gadget->speed) {
case USB_SPEED_LOW:
case USB_SPEED_FULL:
value = usb_ep_enable (ep, &data->desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#ifdef HIGHSPEED
case USB_SPEED_HIGH:
/* fails if caller didn't provide that descriptor... */
value = usb_ep_enable (ep, &data->hs_desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#endif
default:
DBG (data->dev, "unconnected, %s init deferred\n",
data->name);
data->state = STATE_EP_DEFER_ENABLE;
}
if (value == 0)
fd->f_op = &ep_io_operations;
gone:
spin_unlock_irq (&data->dev->lock);
if (value < 0) {
fail:
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
up (&data->lock);
return value;
fail0:
value = -EINVAL;
goto fail;
fail1:
value = -EFAULT;
goto fail;
}
static int
ep_open (struct inode *inode, struct file *fd)
{
struct ep_data *data = inode->u.generic_ip;
int value = -EBUSY;
if (down_interruptible (&data->lock) != 0)
return -EINTR;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND)
value = -ENOENT;
else if (data->state == STATE_EP_DISABLED) {
value = 0;
data->state = STATE_EP_READY;
get_ep (data);
fd->private_data = data;
VDEBUG (data->dev, "%s ready\n", data->name);
} else
DBG (data->dev, "%s state %d\n",
data->name, data->state);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return value;
}
/* used before endpoint configuration */
static struct file_operations ep_config_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = ep_open,
.write = ep_config,
.release = ep_release,
};
/*----------------------------------------------------------------------*/
/* EP0 IMPLEMENTATION can be partly in userspace.
*
* Drivers that use this facility receive various events, including
* control requests the kernel doesn't handle. Drivers that don't
* use this facility may be too simple-minded for real applications.
*/
static inline void ep0_readable (struct dev_data *dev)
{
wake_up (&dev->wait);
kill_fasync (&dev->fasync, SIGIO, POLL_IN);
}
static void clean_req (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
if (req->buf != dev->rbuf) {
usb_ep_free_buffer (ep, req->buf, req->dma, req->length);
req->buf = dev->rbuf;
req->dma = DMA_ADDR_INVALID;
}
req->complete = epio_complete;
dev->setup_out_ready = 0;
}
static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
int free = 1;
/* for control OUT, data must still get to userspace */
if (!dev->setup_in) {
dev->setup_out_error = (req->status != 0);
if (!dev->setup_out_error)
free = 0;
dev->setup_out_ready = 1;
ep0_readable (dev);
} else if (dev->state == STATE_SETUP)
dev->state = STATE_CONNECTED;
/* clean up as appropriate */
if (free && req->buf != &dev->rbuf)
clean_req (ep, req);
req->complete = epio_complete;
}
static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
{
struct dev_data *dev = ep->driver_data;
if (dev->setup_out_ready) {
DBG (dev, "ep0 request busy!\n");
return -EBUSY;
}
if (len > sizeof (dev->rbuf))
req->buf = usb_ep_alloc_buffer (ep, len, &req->dma, GFP_ATOMIC);
if (req->buf == 0) {
req->buf = dev->rbuf;
return -ENOMEM;
}
req->complete = ep0_complete;
req->length = len;
return 0;
}
static ssize_t
ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct dev_data *dev = fd->private_data;
ssize_t retval;
enum ep0_state state;
spin_lock_irq (&dev->lock);
/* report fd mode change before acting on it */
if (dev->setup_abort) {
dev->setup_abort = 0;
retval = -EIDRM;
goto done;
}
/* control DATA stage */
if ((state = dev->state) == STATE_SETUP) {
if (dev->setup_in) { /* stall IN */
VDEBUG(dev, "ep0in stall\n");
(void) usb_ep_set_halt (dev->gadget->ep0);
retval = -EL2HLT;
dev->state = STATE_CONNECTED;
} else if (len == 0) { /* ack SET_CONFIGURATION etc */
struct usb_ep *ep = dev->gadget->ep0;
struct usb_request *req = dev->req;
if ((retval = setup_req (ep, req, 0)) == 0)
retval = usb_ep_queue (ep, req, GFP_ATOMIC);
dev->state = STATE_CONNECTED;
/* assume that was SET_CONFIGURATION */
if (dev->current_config) {
unsigned power;
#ifdef HIGHSPEED
if (dev->gadget->speed == USB_SPEED_HIGH)
power = dev->hs_config->bMaxPower;
else
#endif
power = dev->config->bMaxPower;
usb_gadget_vbus_draw(dev->gadget, 2 * power);
}
} else { /* collect OUT data */
if ((fd->f_flags & O_NONBLOCK) != 0
&& !dev->setup_out_ready) {
retval = -EAGAIN;
goto done;
}
spin_unlock_irq (&dev->lock);
retval = wait_event_interruptible (dev->wait,
dev->setup_out_ready != 0);
]
]
|
| 295/2 |
2026/07/31 07:49 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 24054
output: 38
thoughts: 58
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing the `gadgetfs_bind` Function's Location**
Alright, the output's been cut off, but I can see that `gadgetfs_bind` is mentioned. The key here is pinpointing its exact location, and thankfully, it looks like it's in `drivers/usb/gadget/inode.c`. That narrows the search considerably. No need to waste time scanning the entire codebase. Now, I'm going to jump directly into examining that file: `drivers/usb/gadget/inode.c`. That should give me the context I need to understand what's going on with `gadgetfs_bind`.
|
| 296/2 |
2026/07/31 07:49 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_bind PathPrefix:drivers/usb/gadget/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
ffe0b3350625 usb: gadget: remove global variable composite in composite.c
93952956c707 usb: gadget: move bind() callback back to struct usb_gadget_driver
b0fca50f5a94 usb gadget: don't save bind callback in struct usb_gadget_driver
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 297/2 |
2026/07/31 07:49 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 24450
output: 37
thoughts: 26
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Analyzing `gadgetfs_bind` in commit `1da177e4c3f4`**
Okay, so I'm diving into `gadgetfs_bind`. This feels like it's going to be key to understanding the filesystem's initialization and attachment process within the USB gadget context. I'm assuming that the commit `1da177e4c3f4` is relatively recent, given the format, so it's probably relevant to the current kernel state.
My immediate thoughts are to consider what context `gadgetfs_bind` operates in. Is it called from the core USB subsystem? Is it device-specific or driver-specific? Is this the initial point of interaction when the gadget is plugged in or something else entirely? I need to quickly identify the calling structure. I'll need to check the call traces and cross-references.
Next, I'll need to check if there are any significant changes introduced by this commit related to the functionality of the `gadgetfs_bind` function. Are there any significant changes with the data structures involved, the way it interacts with the underlying USB hardware, or any new error handling?
I'll be specifically looking for potential race conditions, locking issues, or any optimizations related to the binding process. I'll probably start by looking at any mutexes or spinlocks in play. This is where the devil often resides when dealing with concurrent USB device operation.
Finally, I'm thinking of looking for the relation of this function to other related function calls. And this might give some insight on the architecture, which might show how `gadgetfs_bind` operates. Specifically how it interacts with the underlying USB hardware. I want to see if any new functionality was added.
Right, let's start digging into the code. Time to fire up the tools and get to work.
|
| 298/2 |
2026/07/31 07:50 |
tool |
git-show |
0m
Args: map[Commit:1da177e4c3f4:drivers/usb/gadget/inode.c]
Results: map[Output:
Full output is too long, showing 1000 out of 2110 lines.
[/*
* inode.c -- user mode filesystem api for usb gadget controllers
*
* Copyright (C) 2003-2004 David Brownell
* Copyright (C) 2003 Agilent Technologies
*
* 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
*/
// #define DEBUG /* data to help fault diagnosis */
// #define VERBOSE /* extra debug messages (success too) */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/uts.h>
#include <linux/wait.h>
#include <linux/compiler.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/moduleparam.h>
#include <linux/usb_gadgetfs.h>
#include <linux/usb_gadget.h>
/*
* The gadgetfs API maps each endpoint to a file descriptor so that you
* can use standard synchronous read/write calls for I/O. There's some
* O_NONBLOCK and O_ASYNC/FASYNC style i/o support. Example usermode
* drivers show how this works in practice. You can also use AIO to
* eliminate I/O gaps between requests, to help when streaming data.
*
* Key parts that must be USB-specific are protocols defining how the
* read/write operations relate to the hardware state machines. There
* are two types of files. One type is for the device, implementing ep0.
* The other type is for each IN or OUT endpoint. In both cases, the
* user mode driver must configure the hardware before using it.
*
* - First, dev_config() is called when /dev/gadget/$CHIP is configured
* (by writing configuration and device descriptors). Afterwards it
* may serve as a source of device events, used to handle all control
* requests other than basic enumeration.
*
* - Then either immediately, or after a SET_CONFIGURATION control request,
* ep_config() is called when each /dev/gadget/ep* file is configured
* (by writing endpoint descriptors). Afterwards these files are used
* to write() IN data or to read() OUT data. To halt the endpoint, a
* "wrong direction" request is issued (like reading an IN endpoint).
*
* Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
* not possible on all hardware. For example, precise fault handling with
* respect to data left in endpoint fifos after aborted operations; or
* selective clearing of endpoint halts, to implement SET_INTERFACE.
*/
#define DRIVER_DESC "USB Gadget filesystem"
#define DRIVER_VERSION "24 Aug 2004"
static const char driver_desc [] = DRIVER_DESC;
static const char shortname [] = "gadgetfs";
MODULE_DESCRIPTION (DRIVER_DESC);
MODULE_AUTHOR ("David Brownell");
MODULE_LICENSE ("GPL");
/*----------------------------------------------------------------------*/
#define GADGETFS_MAGIC 0xaee71ee7
#define DMA_ADDR_INVALID (~(dma_addr_t)0)
/* /dev/gadget/$CHIP represents ep0 and the whole device */
enum ep0_state {
/* DISBLED is the initial state.
*/
STATE_DEV_DISABLED = 0,
/* Only one open() of /dev/gadget/$CHIP; only one file tracks
* ep0/device i/o modes and binding to the controller. Driver
* must always write descriptors to initialize the device, then
* the device becomes UNCONNECTED until enumeration.
*/
STATE_OPENED,
/* From then on, ep0 fd is in either of two basic modes:
* - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
* - SETUP: read/write will transfer control data and succeed;
* or if "wrong direction", performs protocol stall
*/
STATE_UNCONNECTED,
STATE_CONNECTED,
STATE_SETUP,
/* UNBOUND means the driver closed ep0, so the device won't be
* accessible again (DEV_DISABLED) until all fds are closed.
*/
STATE_DEV_UNBOUND,
};
/* enough for the whole queue: most events invalidate others */
#define N_EVENT 5
struct dev_data {
spinlock_t lock;
atomic_t count;
enum ep0_state state;
struct usb_gadgetfs_event event [N_EVENT];
unsigned ev_next;
struct fasync_struct *fasync;
u8 current_config;
/* drivers reading ep0 MUST handle control requests (SETUP)
* reported that way; else the host will time out.
*/
unsigned usermode_setup : 1,
setup_in : 1,
setup_can_stall : 1,
setup_out_ready : 1,
setup_out_error : 1,
setup_abort : 1;
/* the rest is basically write-once */
struct usb_config_descriptor *config, *hs_config;
struct usb_device_descriptor *dev;
struct usb_request *req;
struct usb_gadget *gadget;
struct list_head epfiles;
void *buf;
wait_queue_head_t wait;
struct super_block *sb;
struct dentry *dentry;
/* except this scratch i/o buffer for ep0 */
u8 rbuf [256];
};
static inline void get_dev (struct dev_data *data)
{
atomic_inc (&data->count);
}
static void put_dev (struct dev_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
/* needs no more cleanup */
BUG_ON (waitqueue_active (&data->wait));
kfree (data);
}
static struct dev_data *dev_new (void)
{
struct dev_data *dev;
dev = kmalloc (sizeof *dev, GFP_KERNEL);
if (!dev)
return NULL;
memset (dev, 0, sizeof *dev);
dev->state = STATE_DEV_DISABLED;
atomic_set (&dev->count, 1);
spin_lock_init (&dev->lock);
INIT_LIST_HEAD (&dev->epfiles);
init_waitqueue_head (&dev->wait);
return dev;
}
/*----------------------------------------------------------------------*/
/* other /dev/gadget/$ENDPOINT files represent endpoints */
enum ep_state {
STATE_EP_DISABLED = 0,
STATE_EP_READY,
STATE_EP_DEFER_ENABLE,
STATE_EP_ENABLED,
STATE_EP_UNBOUND,
};
struct ep_data {
struct semaphore lock;
enum ep_state state;
atomic_t count;
struct dev_data *dev;
/* must hold dev->lock before accessing ep or req */
struct usb_ep *ep;
struct usb_request *req;
ssize_t status;
char name [16];
struct usb_endpoint_descriptor desc, hs_desc;
struct list_head epfiles;
wait_queue_head_t wait;
struct dentry *dentry;
struct inode *inode;
};
static inline void get_ep (struct ep_data *data)
{
atomic_inc (&data->count);
}
static void put_ep (struct ep_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
put_dev (data->dev);
/* needs no more cleanup */
BUG_ON (!list_empty (&data->epfiles));
BUG_ON (waitqueue_active (&data->wait));
BUG_ON (down_trylock (&data->lock) != 0);
kfree (data);
}
/*----------------------------------------------------------------------*/
/* most "how to use the hardware" policy choices are in userspace:
* mapping endpoint roles (which the driver needs) to the capabilities
* which the usb controller has. most of those capabilities are exposed
* implicitly, starting with the driver name and then endpoint names.
*/
static const char *CHIP;
/*----------------------------------------------------------------------*/
/* NOTE: don't use dev_printk calls before binding to the gadget
* at the end of ep0 configuration, or after unbind.
*/
/* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
#define xprintk(d,level,fmt,args...) \
printk(level "%s: " fmt , shortname , ## args)
#ifdef DEBUG
#define DBG(dev,fmt,args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE
#define VDEBUG DBG
#else
#define VDEBUG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev,fmt,args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define WARN(dev,fmt,args...) \
xprintk(dev , KERN_WARNING , fmt , ## args)
#define INFO(dev,fmt,args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*----------------------------------------------------------------------*/
/* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
*
* After opening, configure non-control endpoints. Then use normal
* stream read() and write() requests; and maybe ioctl() to get more
* precise FIFO status when recovering from cancelation.
*/
static void epio_complete (struct usb_ep *ep, struct usb_request *req)
{
struct ep_data *epdata = ep->driver_data;
if (!req->context)
return;
if (req->status)
epdata->status = req->status;
else
epdata->status = req->actual;
complete ((struct completion *)req->context);
}
/* tasklock endpoint, returning when it's connected.
* still need dev->lock to use epdata->ep.
*/
static int
get_ready_ep (unsigned f_flags, struct ep_data *epdata)
{
int val;
if (f_flags & O_NONBLOCK) {
if (down_trylock (&epdata->lock) != 0)
goto nonblock;
if (epdata->state != STATE_EP_ENABLED) {
up (&epdata->lock);
nonblock:
val = -EAGAIN;
} else
val = 0;
return val;
}
if ((val = down_interruptible (&epdata->lock)) < 0)
return val;
newstate:
switch (epdata->state) {
case STATE_EP_ENABLED:
break;
case STATE_EP_DEFER_ENABLE:
DBG (epdata->dev, "%s wait for host\n", epdata->name);
if ((val = wait_event_interruptible (epdata->wait,
epdata->state != STATE_EP_DEFER_ENABLE
|| epdata->dev->state == STATE_DEV_UNBOUND
)) < 0)
goto fail;
goto newstate;
// case STATE_EP_DISABLED: /* "can't happen" */
// case STATE_EP_READY: /* "can't happen" */
default: /* error! */
pr_debug ("%s: ep %p not available, state %d\n",
shortname, epdata, epdata->state);
// FALLTHROUGH
case STATE_EP_UNBOUND: /* clean disconnect */
val = -ENODEV;
fail:
up (&epdata->lock);
}
return val;
}
static ssize_t
ep_io (struct ep_data *epdata, void *buf, unsigned len)
{
DECLARE_COMPLETION (done);
int value;
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
struct usb_request *req = epdata->req;
req->context = &done;
req->complete = epio_complete;
req->buf = buf;
req->length = len;
value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
} else
value = -ENODEV;
spin_unlock_irq (&epdata->dev->lock);
if (likely (value == 0)) {
value = wait_event_interruptible (done.wait, done.done);
if (value != 0) {
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
DBG (epdata->dev, "%s i/o interrupted\n",
epdata->name);
usb_ep_dequeue (epdata->ep, epdata->req);
spin_unlock_irq (&epdata->dev->lock);
wait_event (done.wait, done.done);
if (epdata->status == -ECONNRESET)
epdata->status = -EINTR;
} else {
spin_unlock_irq (&epdata->dev->lock);
DBG (epdata->dev, "endpoint gone\n");
epdata->status = -ENODEV;
}
}
return epdata->status;
}
return value;
}
/* handle a synchronous OUT bulk/intr/iso transfer */
static ssize_t
ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (data->desc.bEndpointAddress & USB_DIR_IN) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (unlikely (!kbuf))
goto free1;
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s read %d OUT, status %d\n",
data->name, len, value);
if (value >= 0 && copy_to_user (buf, kbuf, value))
value = -EFAULT;
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
/* handle a synchronous IN bulk/intr/iso transfer */
static ssize_t
ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (!(data->desc.bEndpointAddress & USB_DIR_IN)) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (!kbuf)
goto free1;
if (copy_from_user (kbuf, buf, len)) {
value = -EFAULT;
goto free1;
}
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s write %d IN, status %d\n",
data->name, len, value);
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
static int
ep_release (struct inode *inode, struct file *fd)
{
struct ep_data *data = fd->private_data;
/* clean up if this can be reopened */
if (data->state != STATE_EP_UNBOUND) {
data->state = STATE_EP_DISABLED;
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
put_ep (data);
return 0;
}
static int ep_ioctl (struct inode *inode, struct file *fd,
unsigned code, unsigned long value)
{
struct ep_data *data = fd->private_data;
int status;
if ((status = get_ready_ep (fd->f_flags, data)) < 0)
return status;
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL)) {
switch (code) {
case GADGETFS_FIFO_STATUS:
status = usb_ep_fifo_status (data->ep);
break;
case GADGETFS_FIFO_FLUSH:
usb_ep_fifo_flush (data->ep);
break;
case GADGETFS_CLEAR_HALT:
status = usb_ep_clear_halt (data->ep);
break;
default:
status = -ENOTTY;
}
} else
status = -ENODEV;
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return status;
}
/*----------------------------------------------------------------------*/
/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
struct kiocb_priv {
struct usb_request *req;
struct ep_data *epdata;
void *buf;
char __user *ubuf;
unsigned actual;
};
static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e)
{
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata;
int value;
local_irq_disable();
epdata = priv->epdata;
// spin_lock(&epdata->dev->lock);
kiocbSetCancelled(iocb);
if (likely(epdata && epdata->ep && priv->req))
value = usb_ep_dequeue (epdata->ep, priv->req);
else
value = -EINVAL;
// spin_unlock(&epdata->dev->lock);
local_irq_enable();
aio_put_req(iocb);
return value;
}
static ssize_t ep_aio_read_retry(struct kiocb *iocb)
{
struct kiocb_priv *priv = iocb->private;
ssize_t status = priv->actual;
/* we "retry" to get the right mm context for this: */
status = copy_to_user(priv->ubuf, priv->buf, priv->actual);
if (unlikely(0 != status))
status = -EFAULT;
else
status = priv->actual;
kfree(priv->buf);
kfree(priv);
aio_put_req(iocb);
return status;
}
static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
{
struct kiocb *iocb = req->context;
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata = priv->epdata;
/* lock against disconnect (and ideally, cancel) */
spin_lock(&epdata->dev->lock);
priv->req = NULL;
priv->epdata = NULL;
if (NULL == iocb->ki_retry
|| unlikely(0 == req->actual)
|| unlikely(kiocbIsCancelled(iocb))) {
kfree(req->buf);
kfree(priv);
iocb->private = NULL;
/* aio_complete() reports bytes-transferred _and_ faults */
if (unlikely(kiocbIsCancelled(iocb)))
aio_put_req(iocb);
else
aio_complete(iocb,
req->actual ? req->actual : req->status,
req->status);
} else {
/* retry() won't report both; so we hide some faults */
if (unlikely(0 != req->status))
DBG(epdata->dev, "%s fault %d len %d\n",
ep->name, req->status, req->actual);
priv->buf = req->buf;
priv->actual = req->actual;
kick_iocb(iocb);
}
spin_unlock(&epdata->dev->lock);
usb_ep_free_request(ep, req);
put_ep(epdata);
}
static ssize_t
ep_aio_rwtail(
struct kiocb *iocb,
char *buf,
size_t len,
struct ep_data *epdata,
char __user *ubuf
)
{
struct kiocb_priv *priv = (void *) &iocb->private;
struct usb_request *req;
ssize_t value;
priv = kmalloc(sizeof *priv, GFP_KERNEL);
if (!priv) {
value = -ENOMEM;
fail:
kfree(buf);
return value;
}
iocb->private = priv;
priv->ubuf = ubuf;
value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
if (unlikely(value < 0)) {
kfree(priv);
goto fail;
}
iocb->ki_cancel = ep_aio_cancel;
get_ep(epdata);
priv->epdata = epdata;
priv->actual = 0;
/* each kiocb is coupled to one usb_request, but we can't
* allocate or submit those if the host disconnected.
*/
spin_lock_irq(&epdata->dev->lock);
if (likely(epdata->ep)) {
req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
if (likely(req)) {
priv->req = req;
req->buf = buf;
req->length = len;
req->complete = ep_aio_complete;
req->context = iocb;
value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
if (unlikely(0 != value))
usb_ep_free_request(epdata->ep, req);
} else
value = -EAGAIN;
} else
value = -ENODEV;
spin_unlock_irq(&epdata->dev->lock);
up(&epdata->lock);
if (unlikely(value)) {
kfree(priv);
put_ep(epdata);
} else
value = -EIOCBQUEUED;
return value;
}
static ssize_t
ep_aio_read(struct kiocb *iocb, char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(epdata->desc.bEndpointAddress & USB_DIR_IN))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
iocb->ki_retry = ep_aio_read_retry;
return ep_aio_rwtail(iocb, buf, len, epdata, ubuf);
}
static ssize_t
ep_aio_write(struct kiocb *iocb, const char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(!(epdata->desc.bEndpointAddress & USB_DIR_IN)))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
if (unlikely(copy_from_user(buf, ubuf, len) != 0)) {
kfree(buf);
return -EFAULT;
}
return ep_aio_rwtail(iocb, buf, len, epdata, NULL);
}
/*----------------------------------------------------------------------*/
/* used after endpoint configuration */
static struct file_operations ep_io_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = ep_read,
.write = ep_write,
.ioctl = ep_ioctl,
.release = ep_release,
.aio_read = ep_aio_read,
.aio_write = ep_aio_write,
};
/* ENDPOINT INITIALIZATION
*
* fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
* status = write (fd, descriptors, sizeof descriptors)
*
* That write establishes the endpoint configuration, configuring
* the controller to process bulk, interrupt, or isochronous transfers
* at the right maxpacket size, and so on.
*
* The descriptors are message type 1, identified by a host order u32
* at the beginning of what's written. Descriptor order is: full/low
* speed descriptor, then optional high speed descriptor.
*/
static ssize_t
ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
struct usb_ep *ep;
u32 tag;
int value;
if ((value = down_interruptible (&data->lock)) < 0)
return value;
if (data->state != STATE_EP_READY) {
value = -EL2HLT;
goto fail;
}
value = len;
if (len < USB_DT_ENDPOINT_SIZE + 4)
goto fail0;
/* we might need to change message format someday */
if (copy_from_user (&tag, buf, 4)) {
goto fail1;
}
if (tag != 1) {
DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
goto fail0;
}
buf += 4;
len -= 4;
/* NOTE: audio endpoint extensions not accepted here;
* just don't include the extra bytes.
*/
/* full/low speed descriptor, then high speed */
if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->desc.bDescriptorType != USB_DT_ENDPOINT)
goto fail0;
if (len != USB_DT_ENDPOINT_SIZE) {
if (len != 2 * USB_DT_ENDPOINT_SIZE)
goto fail0;
if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->hs_desc.bDescriptorType
!= USB_DT_ENDPOINT) {
DBG(data->dev, "config %s, bad hs length or type\n",
data->name);
goto fail0;
}
}
value = len;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND) {
value = -ENOENT;
goto gone;
} else if ((ep = data->ep) == NULL) {
value = -ENODEV;
goto gone;
}
switch (data->dev->gadget->speed) {
case USB_SPEED_LOW:
case USB_SPEED_FULL:
value = usb_ep_enable (ep, &data->desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#ifdef HIGHSPEED
case USB_SPEED_HIGH:
/* fails if caller didn't provide that descriptor... */
value = usb_ep_enable (ep, &data->hs_desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#endif
default:
DBG (data->dev, "unconnected, %s init deferred\n",
data->name);
data->state = STATE_EP_DEFER_ENABLE;
}
if (value == 0)
fd->f_op = &ep_io_operations;
gone:
spin_unlock_irq (&data->dev->lock);
if (value < 0) {
fail:
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
up (&data->lock);
return value;
fail0:
value = -EINVAL;
goto fail;
fail1:
value = -EFAULT;
goto fail;
}
static int
ep_open (struct inode *inode, struct file *fd)
{
struct ep_data *data = inode->u.generic_ip;
int value = -EBUSY;
if (down_interruptible (&data->lock) != 0)
return -EINTR;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND)
value = -ENOENT;
else if (data->state == STATE_EP_DISABLED) {
value = 0;
data->state = STATE_EP_READY;
get_ep (data);
fd->private_data = data;
VDEBUG (data->dev, "%s ready\n", data->name);
} else
DBG (data->dev, "%s state %d\n",
data->name, data->state);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return value;
}
/* used before endpoint configuration */
static struct file_operations ep_config_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = ep_open,
.write = ep_config,
.release = ep_release,
};
/*----------------------------------------------------------------------*/
/* EP0 IMPLEMENTATION can be partly in userspace.
*
* Drivers that use this facility receive various events, including
* control requests the kernel doesn't handle. Drivers that don't
* use this facility may be too simple-minded for real applications.
*/
static inline void ep0_readable (struct dev_data *dev)
{
wake_up (&dev->wait);
kill_fasync (&dev->fasync, SIGIO, POLL_IN);
}
static void clean_req (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
if (req->buf != dev->rbuf) {
usb_ep_free_buffer (ep, req->buf, req->dma, req->length);
req->buf = dev->rbuf;
req->dma = DMA_ADDR_INVALID;
}
req->complete = epio_complete;
dev->setup_out_ready = 0;
}
static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
int free = 1;
/* for control OUT, data must still get to userspace */
if (!dev->setup_in) {
dev->setup_out_error = (req->status != 0);
if (!dev->setup_out_error)
free = 0;
dev->setup_out_ready = 1;
ep0_readable (dev);
} else if (dev->state == STATE_SETUP)
dev->state = STATE_CONNECTED;
/* clean up as appropriate */
if (free && req->buf != &dev->rbuf)
clean_req (ep, req);
req->complete = epio_complete;
}
static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
{
struct dev_data *dev = ep->driver_data;
if (dev->setup_out_ready) {
DBG (dev, "ep0 request busy!\n");
return -EBUSY;
}
if (len > sizeof (dev->rbuf))
req->buf = usb_ep_alloc_buffer (ep, len, &req->dma, GFP_ATOMIC);
if (req->buf == 0) {
req->buf = dev->rbuf;
return -ENOMEM;
}
req->complete = ep0_complete;
req->length = len;
return 0;
}
static ssize_t
ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct dev_data *dev = fd->private_data;
ssize_t retval;
enum ep0_state state;
spin_lock_irq (&dev->lock);
/* report fd mode change before acting on it */
if (dev->setup_abort) {
dev->setup_abort = 0;
retval = -EIDRM;
goto done;
}
/* control DATA stage */
if ((state = dev->state) == STATE_SETUP) {
if (dev->setup_in) { /* stall IN */
VDEBUG(dev, "ep0in stall\n");
(void) usb_ep_set_halt (dev->gadget->ep0);
retval = -EL2HLT;
dev->state = STATE_CONNECTED;
} else if (len == 0) { /* ack SET_CONFIGURATION etc */
struct usb_ep *ep = dev->gadget->ep0;
struct usb_request *req = dev->req;
if ((retval = setup_req (ep, req, 0)) == 0)
retval = usb_ep_queue (ep, req, GFP_ATOMIC);
dev->state = STATE_CONNECTED;
/* assume that was SET_CONFIGURATION */
if (dev->current_config) {
unsigned power;
#ifdef HIGHSPEED
if (dev->gadget->speed == USB_SPEED_HIGH)
power = dev->hs_config->bMaxPower;
else
#endif
power = dev->config->bMaxPower;
usb_gadget_vbus_draw(dev->gadget, 2 * power);
}
} else { /* collect OUT data */
if ((fd->f_flags & O_NONBLOCK) != 0
&& !dev->setup_out_ready) {
retval = -EAGAIN;
goto done;
}
spin_unlock_irq (&dev->lock);
retval = wait_event_interruptible (dev->wait,
dev->setup_out_ready != 0);
]
]
|
| 299/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 35214
output: 32
thoughts: 42
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Quick USB Gadgetfs Lookup**
Alright, let me see... I need to find the specific implementation details for how the gadgetfs filesystem binds. Instead of wading through documentation (which is often incomplete anyway), I'm just going to cut right to the chase. No need to overthink it; the code's the truth. I'll just reach for my old friend, `grep`. Now, let's target the likely files... I'd wager it's in either `drivers/usb/gadget/inode.c` or, if we're dealing with older compatibility code, maybe even `drivers/usb/gadget/legacy/inode.c`. That `gadgetfs_bind` function is probably the key function I'm after. This should give me the precise information I need regarding the binding procedure, directly from the source. This is far more reliable and efficient than any cursory search or API document. I'm going to get the definitive answer in a matter of seconds.
|
| 300/2 |
2026/07/31 07:50 |
tool |
grepper |
0m
Args: map[Expression:gadgetfs_bind PathPrefix:drivers/usb/gadget/]
Results: map[Output:drivers/usb/gadget/legacy/inode.c=1666=static struct dev_data *the_device;
drivers/usb/gadget/legacy/inode.c-1667-
drivers/usb/gadget/legacy/inode.c:1668:static int gadgetfs_bind(struct usb_gadget *gadget,
drivers/usb/gadget/legacy/inode.c-1669- struct usb_gadget_driver *driver)
--
drivers/usb/gadget/legacy/inode.c=1746=static struct usb_gadget_driver gadgetfs_driver = {
drivers/usb/gadget/legacy/inode.c-1747- .function = (char *) driver_desc,
drivers/usb/gadget/legacy/inode.c:1748: .bind = gadgetfs_bind,
drivers/usb/gadget/legacy/inode.c-1749- .unbind = gadgetfs_unbind,
--
drivers/usb/gadget/legacy/inode.c=1801=dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
--
drivers/usb/gadget/legacy/inode.c-1875-
drivers/usb/gadget/legacy/inode.c:1876: /* triggers gadgetfs_bind(); then we can enumerate. */
drivers/usb/gadget/legacy/inode.c-1877- spin_unlock_irq (&dev->lock);
]
|
| 301/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 35903
output: 45
thoughts: 29
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Diving into the `gadgetfs_bind` History**
Alright, let's trace the lineage of `gadgetfs_bind` within the legacy `inode.c` framework of the USB gadget driver. I need to understand its evolution, any potential regressions or improvements, and how it aligns with the broader changes in the USB gadget subsystem. I'm thinking I'll start by checking the git history for that specific function. I want to see how the binding process itself has evolved over time - are there any notable shifts in how it interacts with the underlying USB controller, resource allocation, error handling, or the overall security model?
I'll be looking for specific commits: when it was initially introduced, any major refactorings, security fixes, performance optimizations, and perhaps even its eventual deprecation or replacement. Are there any specific commit messages that highlight design decisions or address particularly nasty bugs related to device enumeration or file system interactions? Has it had any compatibility issues with different USB controllers or kernel versions? I want to pay attention to any dependencies on other functions or structures, and how those have changed in relation to `gadgetfs_bind`. This might give me a hint as to the reason a specific bug is occurring or how a new feature can be added with little or no changes. I might uncover some gems of historical context that aren't immediately apparent.
|
| 302/2 |
2026/07/31 07:50 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_unbind.*\(gadget\) PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
]
|
| 303/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 36315
output: 43
thoughts: 23
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Debugging a Moved File**
Right, so the trace is leading me down a rabbit hole, and the file I was expecting to find is no longer where I anticipated. A quick sanity check reveals the file's been relocated. Alright, no big deal, that happens. Time to dust off the mental map and adjust course. The path of least resistance is to check the `drivers/usb/gadget/inode.c` file. Chances are, whatever functionality I was targeting has been moved or refactored within that directory structure. It’s the obvious place to start given the context, and it's likely to contain the crucial pieces of logic I need to understand, regardless of the relocation. Let's see what's changed there, and where things have ended up. Hopefully, there's a simple `#include` change, or maybe I'll need to chase a function call. Either way, `inode.c` is the new point of attack.
|
| 304/2 |
2026/07/31 07:50 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_unbind.*\(gadget\) PathPrefix:drivers/usb/gadget/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 305/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 36661
output: 37
thoughts: 61
Thoughts: Okay, here's my take on those thoughts, framed as my own internal monologue, with a **bolded header** and rendered as requested:
**Delving into the GadgetFS Code History**
Alright, let's see. My mind is immediately drawn to `gadgetfs_unbind(gadget)`. That function's been around since *the very beginning* of git history, with that initial commit `1da177e4c3f4`. That's significant. It tells me this unbind function is absolutely foundational. Its presence in the genesis of this code base suggests it was a core concept from the start.
Now, since I'm already digging around the foundational commit, it's logical to examine `gadgetfs_bind` in that same commit `1da177e4c3f4`. Understanding how things were set up from day one will give me an important lens through which to view current issues or refactoring choices. I need to understand the initial assumptions the developers were making. Looking at `gadgetfs_bind` in the historical context will reveal how they intended the gadget to attach in the first place, and that’s critical in the context of the unbind process. I want to see how the binding was envisioned, which is the starting point for understanding how it is un-bound. This is good starting point.
|
| 306/2 |
2026/07/31 07:50 |
tool |
git-show |
0m
Args: map[Commit:1da177e4c3f4:drivers/usb/gadget/inode.c]
Results: map[Output:
Full output is too long, showing 1000 out of 2110 lines.
[/*
* inode.c -- user mode filesystem api for usb gadget controllers
*
* Copyright (C) 2003-2004 David Brownell
* Copyright (C) 2003 Agilent Technologies
*
* 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
*/
// #define DEBUG /* data to help fault diagnosis */
// #define VERBOSE /* extra debug messages (success too) */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/uts.h>
#include <linux/wait.h>
#include <linux/compiler.h>
#include <asm/uaccess.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/moduleparam.h>
#include <linux/usb_gadgetfs.h>
#include <linux/usb_gadget.h>
/*
* The gadgetfs API maps each endpoint to a file descriptor so that you
* can use standard synchronous read/write calls for I/O. There's some
* O_NONBLOCK and O_ASYNC/FASYNC style i/o support. Example usermode
* drivers show how this works in practice. You can also use AIO to
* eliminate I/O gaps between requests, to help when streaming data.
*
* Key parts that must be USB-specific are protocols defining how the
* read/write operations relate to the hardware state machines. There
* are two types of files. One type is for the device, implementing ep0.
* The other type is for each IN or OUT endpoint. In both cases, the
* user mode driver must configure the hardware before using it.
*
* - First, dev_config() is called when /dev/gadget/$CHIP is configured
* (by writing configuration and device descriptors). Afterwards it
* may serve as a source of device events, used to handle all control
* requests other than basic enumeration.
*
* - Then either immediately, or after a SET_CONFIGURATION control request,
* ep_config() is called when each /dev/gadget/ep* file is configured
* (by writing endpoint descriptors). Afterwards these files are used
* to write() IN data or to read() OUT data. To halt the endpoint, a
* "wrong direction" request is issued (like reading an IN endpoint).
*
* Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
* not possible on all hardware. For example, precise fault handling with
* respect to data left in endpoint fifos after aborted operations; or
* selective clearing of endpoint halts, to implement SET_INTERFACE.
*/
#define DRIVER_DESC "USB Gadget filesystem"
#define DRIVER_VERSION "24 Aug 2004"
static const char driver_desc [] = DRIVER_DESC;
static const char shortname [] = "gadgetfs";
MODULE_DESCRIPTION (DRIVER_DESC);
MODULE_AUTHOR ("David Brownell");
MODULE_LICENSE ("GPL");
/*----------------------------------------------------------------------*/
#define GADGETFS_MAGIC 0xaee71ee7
#define DMA_ADDR_INVALID (~(dma_addr_t)0)
/* /dev/gadget/$CHIP represents ep0 and the whole device */
enum ep0_state {
/* DISBLED is the initial state.
*/
STATE_DEV_DISABLED = 0,
/* Only one open() of /dev/gadget/$CHIP; only one file tracks
* ep0/device i/o modes and binding to the controller. Driver
* must always write descriptors to initialize the device, then
* the device becomes UNCONNECTED until enumeration.
*/
STATE_OPENED,
/* From then on, ep0 fd is in either of two basic modes:
* - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
* - SETUP: read/write will transfer control data and succeed;
* or if "wrong direction", performs protocol stall
*/
STATE_UNCONNECTED,
STATE_CONNECTED,
STATE_SETUP,
/* UNBOUND means the driver closed ep0, so the device won't be
* accessible again (DEV_DISABLED) until all fds are closed.
*/
STATE_DEV_UNBOUND,
};
/* enough for the whole queue: most events invalidate others */
#define N_EVENT 5
struct dev_data {
spinlock_t lock;
atomic_t count;
enum ep0_state state;
struct usb_gadgetfs_event event [N_EVENT];
unsigned ev_next;
struct fasync_struct *fasync;
u8 current_config;
/* drivers reading ep0 MUST handle control requests (SETUP)
* reported that way; else the host will time out.
*/
unsigned usermode_setup : 1,
setup_in : 1,
setup_can_stall : 1,
setup_out_ready : 1,
setup_out_error : 1,
setup_abort : 1;
/* the rest is basically write-once */
struct usb_config_descriptor *config, *hs_config;
struct usb_device_descriptor *dev;
struct usb_request *req;
struct usb_gadget *gadget;
struct list_head epfiles;
void *buf;
wait_queue_head_t wait;
struct super_block *sb;
struct dentry *dentry;
/* except this scratch i/o buffer for ep0 */
u8 rbuf [256];
};
static inline void get_dev (struct dev_data *data)
{
atomic_inc (&data->count);
}
static void put_dev (struct dev_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
/* needs no more cleanup */
BUG_ON (waitqueue_active (&data->wait));
kfree (data);
}
static struct dev_data *dev_new (void)
{
struct dev_data *dev;
dev = kmalloc (sizeof *dev, GFP_KERNEL);
if (!dev)
return NULL;
memset (dev, 0, sizeof *dev);
dev->state = STATE_DEV_DISABLED;
atomic_set (&dev->count, 1);
spin_lock_init (&dev->lock);
INIT_LIST_HEAD (&dev->epfiles);
init_waitqueue_head (&dev->wait);
return dev;
}
/*----------------------------------------------------------------------*/
/* other /dev/gadget/$ENDPOINT files represent endpoints */
enum ep_state {
STATE_EP_DISABLED = 0,
STATE_EP_READY,
STATE_EP_DEFER_ENABLE,
STATE_EP_ENABLED,
STATE_EP_UNBOUND,
};
struct ep_data {
struct semaphore lock;
enum ep_state state;
atomic_t count;
struct dev_data *dev;
/* must hold dev->lock before accessing ep or req */
struct usb_ep *ep;
struct usb_request *req;
ssize_t status;
char name [16];
struct usb_endpoint_descriptor desc, hs_desc;
struct list_head epfiles;
wait_queue_head_t wait;
struct dentry *dentry;
struct inode *inode;
};
static inline void get_ep (struct ep_data *data)
{
atomic_inc (&data->count);
}
static void put_ep (struct ep_data *data)
{
if (likely (!atomic_dec_and_test (&data->count)))
return;
put_dev (data->dev);
/* needs no more cleanup */
BUG_ON (!list_empty (&data->epfiles));
BUG_ON (waitqueue_active (&data->wait));
BUG_ON (down_trylock (&data->lock) != 0);
kfree (data);
}
/*----------------------------------------------------------------------*/
/* most "how to use the hardware" policy choices are in userspace:
* mapping endpoint roles (which the driver needs) to the capabilities
* which the usb controller has. most of those capabilities are exposed
* implicitly, starting with the driver name and then endpoint names.
*/
static const char *CHIP;
/*----------------------------------------------------------------------*/
/* NOTE: don't use dev_printk calls before binding to the gadget
* at the end of ep0 configuration, or after unbind.
*/
/* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
#define xprintk(d,level,fmt,args...) \
printk(level "%s: " fmt , shortname , ## args)
#ifdef DEBUG
#define DBG(dev,fmt,args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE
#define VDEBUG DBG
#else
#define VDEBUG(dev,fmt,args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev,fmt,args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define WARN(dev,fmt,args...) \
xprintk(dev , KERN_WARNING , fmt , ## args)
#define INFO(dev,fmt,args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*----------------------------------------------------------------------*/
/* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
*
* After opening, configure non-control endpoints. Then use normal
* stream read() and write() requests; and maybe ioctl() to get more
* precise FIFO status when recovering from cancelation.
*/
static void epio_complete (struct usb_ep *ep, struct usb_request *req)
{
struct ep_data *epdata = ep->driver_data;
if (!req->context)
return;
if (req->status)
epdata->status = req->status;
else
epdata->status = req->actual;
complete ((struct completion *)req->context);
}
/* tasklock endpoint, returning when it's connected.
* still need dev->lock to use epdata->ep.
*/
static int
get_ready_ep (unsigned f_flags, struct ep_data *epdata)
{
int val;
if (f_flags & O_NONBLOCK) {
if (down_trylock (&epdata->lock) != 0)
goto nonblock;
if (epdata->state != STATE_EP_ENABLED) {
up (&epdata->lock);
nonblock:
val = -EAGAIN;
} else
val = 0;
return val;
}
if ((val = down_interruptible (&epdata->lock)) < 0)
return val;
newstate:
switch (epdata->state) {
case STATE_EP_ENABLED:
break;
case STATE_EP_DEFER_ENABLE:
DBG (epdata->dev, "%s wait for host\n", epdata->name);
if ((val = wait_event_interruptible (epdata->wait,
epdata->state != STATE_EP_DEFER_ENABLE
|| epdata->dev->state == STATE_DEV_UNBOUND
)) < 0)
goto fail;
goto newstate;
// case STATE_EP_DISABLED: /* "can't happen" */
// case STATE_EP_READY: /* "can't happen" */
default: /* error! */
pr_debug ("%s: ep %p not available, state %d\n",
shortname, epdata, epdata->state);
// FALLTHROUGH
case STATE_EP_UNBOUND: /* clean disconnect */
val = -ENODEV;
fail:
up (&epdata->lock);
}
return val;
}
static ssize_t
ep_io (struct ep_data *epdata, void *buf, unsigned len)
{
DECLARE_COMPLETION (done);
int value;
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
struct usb_request *req = epdata->req;
req->context = &done;
req->complete = epio_complete;
req->buf = buf;
req->length = len;
value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
} else
value = -ENODEV;
spin_unlock_irq (&epdata->dev->lock);
if (likely (value == 0)) {
value = wait_event_interruptible (done.wait, done.done);
if (value != 0) {
spin_lock_irq (&epdata->dev->lock);
if (likely (epdata->ep != NULL)) {
DBG (epdata->dev, "%s i/o interrupted\n",
epdata->name);
usb_ep_dequeue (epdata->ep, epdata->req);
spin_unlock_irq (&epdata->dev->lock);
wait_event (done.wait, done.done);
if (epdata->status == -ECONNRESET)
epdata->status = -EINTR;
} else {
spin_unlock_irq (&epdata->dev->lock);
DBG (epdata->dev, "endpoint gone\n");
epdata->status = -ENODEV;
}
}
return epdata->status;
}
return value;
}
/* handle a synchronous OUT bulk/intr/iso transfer */
static ssize_t
ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (data->desc.bEndpointAddress & USB_DIR_IN) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (unlikely (!kbuf))
goto free1;
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s read %d OUT, status %d\n",
data->name, len, value);
if (value >= 0 && copy_to_user (buf, kbuf, value))
value = -EFAULT;
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
/* handle a synchronous IN bulk/intr/iso transfer */
static ssize_t
ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
void *kbuf;
ssize_t value;
if ((value = get_ready_ep (fd->f_flags, data)) < 0)
return value;
/* halt any endpoint by doing a "wrong direction" i/o call */
if (!(data->desc.bEndpointAddress & USB_DIR_IN)) {
if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
== USB_ENDPOINT_XFER_ISOC)
return -EINVAL;
DBG (data->dev, "%s halt\n", data->name);
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL))
usb_ep_set_halt (data->ep);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return -EBADMSG;
}
/* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
value = -ENOMEM;
kbuf = kmalloc (len, SLAB_KERNEL);
if (!kbuf)
goto free1;
if (copy_from_user (kbuf, buf, len)) {
value = -EFAULT;
goto free1;
}
value = ep_io (data, kbuf, len);
VDEBUG (data->dev, "%s write %d IN, status %d\n",
data->name, len, value);
free1:
up (&data->lock);
kfree (kbuf);
return value;
}
static int
ep_release (struct inode *inode, struct file *fd)
{
struct ep_data *data = fd->private_data;
/* clean up if this can be reopened */
if (data->state != STATE_EP_UNBOUND) {
data->state = STATE_EP_DISABLED;
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
put_ep (data);
return 0;
}
static int ep_ioctl (struct inode *inode, struct file *fd,
unsigned code, unsigned long value)
{
struct ep_data *data = fd->private_data;
int status;
if ((status = get_ready_ep (fd->f_flags, data)) < 0)
return status;
spin_lock_irq (&data->dev->lock);
if (likely (data->ep != NULL)) {
switch (code) {
case GADGETFS_FIFO_STATUS:
status = usb_ep_fifo_status (data->ep);
break;
case GADGETFS_FIFO_FLUSH:
usb_ep_fifo_flush (data->ep);
break;
case GADGETFS_CLEAR_HALT:
status = usb_ep_clear_halt (data->ep);
break;
default:
status = -ENOTTY;
}
} else
status = -ENODEV;
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return status;
}
/*----------------------------------------------------------------------*/
/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
struct kiocb_priv {
struct usb_request *req;
struct ep_data *epdata;
void *buf;
char __user *ubuf;
unsigned actual;
};
static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e)
{
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata;
int value;
local_irq_disable();
epdata = priv->epdata;
// spin_lock(&epdata->dev->lock);
kiocbSetCancelled(iocb);
if (likely(epdata && epdata->ep && priv->req))
value = usb_ep_dequeue (epdata->ep, priv->req);
else
value = -EINVAL;
// spin_unlock(&epdata->dev->lock);
local_irq_enable();
aio_put_req(iocb);
return value;
}
static ssize_t ep_aio_read_retry(struct kiocb *iocb)
{
struct kiocb_priv *priv = iocb->private;
ssize_t status = priv->actual;
/* we "retry" to get the right mm context for this: */
status = copy_to_user(priv->ubuf, priv->buf, priv->actual);
if (unlikely(0 != status))
status = -EFAULT;
else
status = priv->actual;
kfree(priv->buf);
kfree(priv);
aio_put_req(iocb);
return status;
}
static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
{
struct kiocb *iocb = req->context;
struct kiocb_priv *priv = iocb->private;
struct ep_data *epdata = priv->epdata;
/* lock against disconnect (and ideally, cancel) */
spin_lock(&epdata->dev->lock);
priv->req = NULL;
priv->epdata = NULL;
if (NULL == iocb->ki_retry
|| unlikely(0 == req->actual)
|| unlikely(kiocbIsCancelled(iocb))) {
kfree(req->buf);
kfree(priv);
iocb->private = NULL;
/* aio_complete() reports bytes-transferred _and_ faults */
if (unlikely(kiocbIsCancelled(iocb)))
aio_put_req(iocb);
else
aio_complete(iocb,
req->actual ? req->actual : req->status,
req->status);
} else {
/* retry() won't report both; so we hide some faults */
if (unlikely(0 != req->status))
DBG(epdata->dev, "%s fault %d len %d\n",
ep->name, req->status, req->actual);
priv->buf = req->buf;
priv->actual = req->actual;
kick_iocb(iocb);
}
spin_unlock(&epdata->dev->lock);
usb_ep_free_request(ep, req);
put_ep(epdata);
}
static ssize_t
ep_aio_rwtail(
struct kiocb *iocb,
char *buf,
size_t len,
struct ep_data *epdata,
char __user *ubuf
)
{
struct kiocb_priv *priv = (void *) &iocb->private;
struct usb_request *req;
ssize_t value;
priv = kmalloc(sizeof *priv, GFP_KERNEL);
if (!priv) {
value = -ENOMEM;
fail:
kfree(buf);
return value;
}
iocb->private = priv;
priv->ubuf = ubuf;
value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
if (unlikely(value < 0)) {
kfree(priv);
goto fail;
}
iocb->ki_cancel = ep_aio_cancel;
get_ep(epdata);
priv->epdata = epdata;
priv->actual = 0;
/* each kiocb is coupled to one usb_request, but we can't
* allocate or submit those if the host disconnected.
*/
spin_lock_irq(&epdata->dev->lock);
if (likely(epdata->ep)) {
req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
if (likely(req)) {
priv->req = req;
req->buf = buf;
req->length = len;
req->complete = ep_aio_complete;
req->context = iocb;
value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
if (unlikely(0 != value))
usb_ep_free_request(epdata->ep, req);
} else
value = -EAGAIN;
} else
value = -ENODEV;
spin_unlock_irq(&epdata->dev->lock);
up(&epdata->lock);
if (unlikely(value)) {
kfree(priv);
put_ep(epdata);
} else
value = -EIOCBQUEUED;
return value;
}
static ssize_t
ep_aio_read(struct kiocb *iocb, char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(epdata->desc.bEndpointAddress & USB_DIR_IN))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
iocb->ki_retry = ep_aio_read_retry;
return ep_aio_rwtail(iocb, buf, len, epdata, ubuf);
}
static ssize_t
ep_aio_write(struct kiocb *iocb, const char __user *ubuf, size_t len, loff_t o)
{
struct ep_data *epdata = iocb->ki_filp->private_data;
char *buf;
if (unlikely(!(epdata->desc.bEndpointAddress & USB_DIR_IN)))
return -EINVAL;
buf = kmalloc(len, GFP_KERNEL);
if (unlikely(!buf))
return -ENOMEM;
if (unlikely(copy_from_user(buf, ubuf, len) != 0)) {
kfree(buf);
return -EFAULT;
}
return ep_aio_rwtail(iocb, buf, len, epdata, NULL);
}
/*----------------------------------------------------------------------*/
/* used after endpoint configuration */
static struct file_operations ep_io_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = ep_read,
.write = ep_write,
.ioctl = ep_ioctl,
.release = ep_release,
.aio_read = ep_aio_read,
.aio_write = ep_aio_write,
};
/* ENDPOINT INITIALIZATION
*
* fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
* status = write (fd, descriptors, sizeof descriptors)
*
* That write establishes the endpoint configuration, configuring
* the controller to process bulk, interrupt, or isochronous transfers
* at the right maxpacket size, and so on.
*
* The descriptors are message type 1, identified by a host order u32
* at the beginning of what's written. Descriptor order is: full/low
* speed descriptor, then optional high speed descriptor.
*/
static ssize_t
ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
{
struct ep_data *data = fd->private_data;
struct usb_ep *ep;
u32 tag;
int value;
if ((value = down_interruptible (&data->lock)) < 0)
return value;
if (data->state != STATE_EP_READY) {
value = -EL2HLT;
goto fail;
}
value = len;
if (len < USB_DT_ENDPOINT_SIZE + 4)
goto fail0;
/* we might need to change message format someday */
if (copy_from_user (&tag, buf, 4)) {
goto fail1;
}
if (tag != 1) {
DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
goto fail0;
}
buf += 4;
len -= 4;
/* NOTE: audio endpoint extensions not accepted here;
* just don't include the extra bytes.
*/
/* full/low speed descriptor, then high speed */
if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->desc.bDescriptorType != USB_DT_ENDPOINT)
goto fail0;
if (len != USB_DT_ENDPOINT_SIZE) {
if (len != 2 * USB_DT_ENDPOINT_SIZE)
goto fail0;
if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
USB_DT_ENDPOINT_SIZE)) {
goto fail1;
}
if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
|| data->hs_desc.bDescriptorType
!= USB_DT_ENDPOINT) {
DBG(data->dev, "config %s, bad hs length or type\n",
data->name);
goto fail0;
}
}
value = len;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND) {
value = -ENOENT;
goto gone;
} else if ((ep = data->ep) == NULL) {
value = -ENODEV;
goto gone;
}
switch (data->dev->gadget->speed) {
case USB_SPEED_LOW:
case USB_SPEED_FULL:
value = usb_ep_enable (ep, &data->desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#ifdef HIGHSPEED
case USB_SPEED_HIGH:
/* fails if caller didn't provide that descriptor... */
value = usb_ep_enable (ep, &data->hs_desc);
if (value == 0)
data->state = STATE_EP_ENABLED;
break;
#endif
default:
DBG (data->dev, "unconnected, %s init deferred\n",
data->name);
data->state = STATE_EP_DEFER_ENABLE;
}
if (value == 0)
fd->f_op = &ep_io_operations;
gone:
spin_unlock_irq (&data->dev->lock);
if (value < 0) {
fail:
data->desc.bDescriptorType = 0;
data->hs_desc.bDescriptorType = 0;
}
up (&data->lock);
return value;
fail0:
value = -EINVAL;
goto fail;
fail1:
value = -EFAULT;
goto fail;
}
static int
ep_open (struct inode *inode, struct file *fd)
{
struct ep_data *data = inode->u.generic_ip;
int value = -EBUSY;
if (down_interruptible (&data->lock) != 0)
return -EINTR;
spin_lock_irq (&data->dev->lock);
if (data->dev->state == STATE_DEV_UNBOUND)
value = -ENOENT;
else if (data->state == STATE_EP_DISABLED) {
value = 0;
data->state = STATE_EP_READY;
get_ep (data);
fd->private_data = data;
VDEBUG (data->dev, "%s ready\n", data->name);
} else
DBG (data->dev, "%s state %d\n",
data->name, data->state);
spin_unlock_irq (&data->dev->lock);
up (&data->lock);
return value;
}
/* used before endpoint configuration */
static struct file_operations ep_config_operations = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = ep_open,
.write = ep_config,
.release = ep_release,
};
/*----------------------------------------------------------------------*/
/* EP0 IMPLEMENTATION can be partly in userspace.
*
* Drivers that use this facility receive various events, including
* control requests the kernel doesn't handle. Drivers that don't
* use this facility may be too simple-minded for real applications.
*/
static inline void ep0_readable (struct dev_data *dev)
{
wake_up (&dev->wait);
kill_fasync (&dev->fasync, SIGIO, POLL_IN);
}
static void clean_req (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
if (req->buf != dev->rbuf) {
usb_ep_free_buffer (ep, req->buf, req->dma, req->length);
req->buf = dev->rbuf;
req->dma = DMA_ADDR_INVALID;
}
req->complete = epio_complete;
dev->setup_out_ready = 0;
}
static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
{
struct dev_data *dev = ep->driver_data;
int free = 1;
/* for control OUT, data must still get to userspace */
if (!dev->setup_in) {
dev->setup_out_error = (req->status != 0);
if (!dev->setup_out_error)
free = 0;
dev->setup_out_ready = 1;
ep0_readable (dev);
} else if (dev->state == STATE_SETUP)
dev->state = STATE_CONNECTED;
/* clean up as appropriate */
if (free && req->buf != &dev->rbuf)
clean_req (ep, req);
req->complete = epio_complete;
}
static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
{
struct dev_data *dev = ep->driver_data;
if (dev->setup_out_ready) {
DBG (dev, "ep0 request busy!\n");
return -EBUSY;
}
if (len > sizeof (dev->rbuf))
req->buf = usb_ep_alloc_buffer (ep, len, &req->dma, GFP_ATOMIC);
if (req->buf == 0) {
req->buf = dev->rbuf;
return -ENOMEM;
}
req->complete = ep0_complete;
req->length = len;
return 0;
}
static ssize_t
ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
{
struct dev_data *dev = fd->private_data;
ssize_t retval;
enum ep0_state state;
spin_lock_irq (&dev->lock);
/* report fd mode change before acting on it */
if (dev->setup_abort) {
dev->setup_abort = 0;
retval = -EIDRM;
goto done;
}
/* control DATA stage */
if ((state = dev->state) == STATE_SETUP) {
if (dev->setup_in) { /* stall IN */
VDEBUG(dev, "ep0in stall\n");
(void) usb_ep_set_halt (dev->gadget->ep0);
retval = -EL2HLT;
dev->state = STATE_CONNECTED;
} else if (len == 0) { /* ack SET_CONFIGURATION etc */
struct usb_ep *ep = dev->gadget->ep0;
struct usb_request *req = dev->req;
if ((retval = setup_req (ep, req, 0)) == 0)
retval = usb_ep_queue (ep, req, GFP_ATOMIC);
dev->state = STATE_CONNECTED;
/* assume that was SET_CONFIGURATION */
if (dev->current_config) {
unsigned power;
#ifdef HIGHSPEED
if (dev->gadget->speed == USB_SPEED_HIGH)
power = dev->hs_config->bMaxPower;
else
#endif
power = dev->config->bMaxPower;
usb_gadget_vbus_draw(dev->gadget, 2 * power);
}
} else { /* collect OUT data */
if ((fd->f_flags & O_NONBLOCK) != 0
&& !dev->setup_out_ready) {
retval = -EAGAIN;
goto done;
}
spin_unlock_irq (&dev->lock);
retval = wait_event_interruptible (dev->wait,
dev->setup_out_ready != 0);
]
]
|
| 307/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 47339
output: 34
thoughts: 109
Thoughts: **Debugging a Persistent Memory Issue**
Alright, the output's truncated *again*. This is getting frustrating. Time to dig deeper. I need to figure out when `gadgetfs_unbind` was introduced into the `enomem:` error handling in `gadgetfs_bind`. My instinct is telling me this is a long-standing issue. Okay, I'll use `git log -G` to find the exact commit that added it. Wait a minute... if this change has been there since `1da177e4c3f4`, that’s... that's the very beginning of the git history for this! This could be a latent bug lurking in the code from day one!
I need to verify this immediately. Let's pull up the code at that commit and confirm whether or not `gadgetfs_unbind` was indeed included in the `enomem:` block back then. Let's see...
|
| 308/2 |
2026/07/31 07:50 |
tool |
grepper |
0m
Error:
Args: map[Expression:enomem: PathPrefix:drivers/usb/gadget/inode.c]
Results:
|
| 309/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 47695
output: 37
thoughts: 56
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Navigating the USB Gadget Inode Landscape**
Right, so I'm digging into some USB gadget code, and my initial hunch is confirmed: `drivers/usb/gadget/inode.c` is a ghost. That's a classic refactoring; I immediately jumped to the legacy directory, and sure enough, `drivers/usb/gadget/legacy/inode.c` seems to be the new home. This isn't surprising given the evolution of the gadget subsystem. Now, to get to the heart of the matter, let's nail down that specific commit, `1da177e4c3f4`. That's where the architectural shift likely happened, and where I'll find the most relevant context for this particular investigation. I'm expecting this commit to shed light on precisely *why* the inode structure was moved, what dependencies were affected, and if there are any subtle behavioural changes I should be aware of. This is just the starting point, but knowing the precise commit should get me to the right code faster.
|
| 310/2 |
2026/07/31 07:50 |
tool |
git-show |
0m
Error:
Args: map[Commit:1da177e4c3f4:drivers/usb/gadget/inode.c]
|
| 311/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 48161
output: 39
thoughts: 93
Thoughts: **Analyzing ENOMEM Errors in USB Gadget Driver Code**
Okay, so I need to track down the history of `ENOMEM` errors within the USB gadget driver code. My first instinct was to just grab the relevant section using `git show 1da177e4c3f4:drivers/usb/gadget/inode.c | grep -A 10 enomem:` and pipe it to `grepper`. But that's not going to give me the history, just the current state, and `grepper` is only going to work on what's in the current tree.
What I really need is the commit history related to changes introducing or altering that error. The best approach now is to utilize `git log -G` on the string "enomem:" specifically within the file `drivers/usb/gadget/legacy/inode.c`. That'll give me a granular view of the relevant commits. That should do the trick.
|
| 312/2 |
2026/07/31 07:50 |
tool |
git-log |
0m
Args: map[CodeRegexp:enomem: PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
]
|
| 313/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 48538
output: 37
thoughts: 16
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Diving into USB Gadget inode.c**
Alright, time to dig into the `drivers/usb/gadget/inode.c` file. I'm focusing on this area because it’s where the virtual filesystem interactions for USB gadgets are handled. I need to understand how the driver creates, manages, and interacts with the inodes representing the various USB gadget interfaces, configurations, and endpoints. This is key to figuring out how user-space interacts with the hardware, especially under different conditions. I need to refresh my understanding of how this particular implementation handles character devices versus other file types within the gadget context. I'll need to pay close attention to the lock management; inode.c is notoriously tricky. Specifically, I should look at how the file operations are hooked up, the allocation and deallocation of inodes, and the synchronization primitives used to avoid race conditions when multiple users or processes access the gadget. This will inform an investigation of a specific error I've been tracing.
|
| 314/2 |
2026/07/31 07:50 |
tool |
git-log |
0m
Args: map[CodeRegexp:enomem: PathPrefix:drivers/usb/gadget/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
0ae4ea8092e1 [PATCH] gadgetfs: fix memory leaks
1da177e4c3f4 Linux-2.6.12-rc2
]
|
| 315/2 |
2026/07/31 07:50 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 48892
output: 25
thoughts: 45
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**On the Trail of the Memory Monster**
Right, let me see... "Ah! `0ae4ea8092e1`" – that's a likely candidate, isn't it? Based on experience, a commit hash like that often pinpoints the source of a recent issue, especially one that's shown up on the radar. It's the kind of hash that leaps out when you're tracking down a troublesome introduction or modification. Given the context, my money's on that commit being the one that brought in the `enomem:` error, or at least significantly touched the relevant code. Time to dig in and give `0ae4ea8092e1` a proper inspection. Let's see what that changeset reveals.
|
| 316/2 |
2026/07/31 07:51 |
tool |
git-show |
0m
Args:
Results: map[Output:commit 0ae4ea8092e1277cfca07cade7eaba5f594076c1
Author: Alan Stern <stern@rowland.harvard.edu>
Date: Mon May 22 12:27:38 2006 -0400
[PATCH] gadgetfs: fix memory leaks
This patch (as692) fixes a few memory leaks in some unimportant error
pathways of the gadgetfs driver.
Signed-off-by: Alan Stern <stern@rowland.harvard.edu>
Acked-by: David Brownell <david-b@pacbell.net>
Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>
diff --git a/drivers/usb/gadget/inode.c b/drivers/usb/gadget/inode.c
index 57bf24810f9b..aef0722b8f17 100644
--- a/drivers/usb/gadget/inode.c
+++ b/drivers/usb/gadget/inode.c
@@ -1038,7 +1038,7 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
/* ep0 can't deliver events when STATE_SETUP */
for (i = 0; i < n; i++) {
if (dev->event [i].type == GADGETFS_SETUP) {
- len = n = i + 1;
+ len = i + 1;
len *= sizeof (struct usb_gadgetfs_event);
n = 0;
break;
@@ -1586,13 +1586,13 @@ gadgetfs_create_file (struct super_block *sb, char const *name,
static int activate_ep_files (struct dev_data *dev)
{
struct usb_ep *ep;
+ struct ep_data *data;
gadget_for_each_ep (ep, dev->gadget) {
- struct ep_data *data;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
- goto enomem;
+ goto enomem0;
data->state = STATE_EP_DISABLED;
init_MUTEX (&data->lock);
init_waitqueue_head (&data->wait);
@@ -1607,21 +1607,23 @@ static int activate_ep_files (struct dev_data *dev)
data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
if (!data->req)
- goto enomem;
+ goto enomem1;
data->inode = gadgetfs_create_file (dev->sb, data->name,
data, &ep_config_operations,
&data->dentry);
- if (!data->inode) {
- usb_ep_free_request(ep, data->req);
- kfree (data);
- goto enomem;
- }
+ if (!data->inode)
+ goto enomem2;
list_add_tail (&data->epfiles, &dev->epfiles);
}
return 0;
-enomem:
+enomem2:
+ usb_ep_free_request (ep, data->req);
+enomem1:
+ put_dev (dev);
+ kfree (data);
+enomem0:
DBG (dev, "%s enomem\n", __FUNCTION__);
destroy_ep_files (dev);
return -ENOMEM;
@@ -1792,7 +1794,7 @@ static struct usb_gadget_driver probe_driver = {
*
* After initialization, the device stays active for as long as that
* $CHIP file is open. Events may then be read from that descriptor,
- * such configuration notifications. More complex drivers will handle
+ * such as configuration notifications. More complex drivers will handle
* some control requests in user space.
*/
@@ -2032,12 +2034,10 @@ gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
NULL, &simple_dir_operations,
S_IFDIR | S_IRUGO | S_IXUGO);
if (!inode)
- return -ENOMEM;
+ goto enomem0;
inode->i_op = &simple_dir_inode_operations;
- if (!(d = d_alloc_root (inode))) {
- iput (inode);
- return -ENOMEM;
- }
+ if (!(d = d_alloc_root (inode)))
+ goto enomem1;
sb->s_root = d;
/* the ep0 file is named after the controller we expect;
@@ -2045,21 +2045,28 @@ gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
*/
dev = dev_new ();
if (!dev)
- return -ENOMEM;
+ goto enomem2;
dev->sb = sb;
- if (!(inode = gadgetfs_create_file (sb, CHIP,
+ if (!gadgetfs_create_file (sb, CHIP,
dev, &dev_init_operations,
- &dev->dentry))) {
- put_dev(dev);
- return -ENOMEM;
- }
+ &dev->dentry))
+ goto enomem3;
/* other endpoint files are available after hardware setup,
* from binding to a controller.
*/
the_device = dev;
return 0;
+
+enomem3:
+ put_dev (dev);
+enomem2:
+ dput (d);
+enomem1:
+ iput (inode);
+enomem0:
+ return -ENOMEM;
}
/* "mount -t gadgetfs path /dev/gadget" ends up here */
]
|
| 317/2 |
2026/07/31 07:51 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 50732
output: 35
thoughts: 68
Thoughts: Here's my summary, as though I'm thinking through this process:
**Diving into the Kernel Module Interactions**
Okay, so I'm looking at this patch `0ae4ea8092e1`. It seems I've misread something initially. It's not actually touching `gadgetfs_bind`, which I was initially focusing on. Instead, it's modifying the `activate_ep_files` and `gadgetfs_fill_super` functions. Right, that makes more sense in the overall context. Now, I should probably double-check my understanding of the interactions. Let me see what `gadgetfs_bind` is doing in relation to these functions, so I will now check commit `1da177e4c3f4` for the information. That'll give me a clearer picture of how everything fits together and where the real impact of this change lies.
|
| 318/2 |
2026/07/31 07:51 |
tool |
grepper |
0m
Error:
Args: map[Expression:gadgetfs_bind PathPrefix:drivers/usb/gadget/inode.c]
Results:
|
| 319/2 |
2026/07/31 07:51 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 51045
output: 40
thoughts: 64
Thoughts: **Investigating the Missing File**
Okay, so I'm looking for `drivers/usb/gadget/inode.c`, but it's not showing up in the current directory tree. That's a bit odd. I know there's related code in this area, but maybe this specific file has been moved or renamed. Let's see... I think I'll use `git log -p -G gadgetfs_bind drivers/usb/gadget/inode.c` to search the Git history. The `-G` flag is the key here; it'll look for changes where the diff introduces or removes lines containing the string "gadgetfs_bind". I'll also try this against `drivers/usb/gadget/legacy/inode.c` just in case it ended up there! I need to trace its history and figure out what happened to it, and how the current code structure handles similar functionality.
|
| 320/2 |
2026/07/31 07:51 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_bind PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:8443f2d2b778 usb: gadget: Gadget directory cleanup - group legacy gadgets
]
|
| 321/2 |
2026/07/31 07:51 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 51384
output: 38
thoughts: 21
Thoughts: Here's my take on those thoughts, tailored for an expert audience:
**Investigating a Potential Issue within the Codebase**
Okay, so I'm thinking we need to dive deep into a specific area, likely related to a recent change or perhaps a recurring problem: `gadgetfs_bind`. This sounds like something important to track down. To do this, I'm thinking of using a very targeted approach with `git log`. Given the nature of the problem, I will use `git log -p -S gadgetfs_bind`. This command is perfect for pinpointing when and where the text "gadgetfs\_bind" was introduced or removed and will show the diffs associated with these changes. This gives me the most effective way to track any behavior of interest and to find out what might have gone wrong, or caused a recent regression. That will be a great starting point for understanding its history and identifying the root cause.
|
| 322/2 |
2026/07/31 07:51 |
tool |
git-log |
0m
Error:
Args: map[CodeRegexp:gadgetfs_unbind.*\(gadget\) SymbolName:gadgetfs_bind]
Results:
|
| 323/2 |
2026/07/31 07:51 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 51660
output: 56
thoughts: 10
Thoughts: Okay, here's the summary, formatted as requested:
**Navigating the Parameter Landscape**
Right, so the system is prompting me for `SourcePath`. Ah, yes, that crucial piece of information. This isn't just a detail; it's fundamental. Without it, the entire process grinds to a halt. It’s the entry point, the origin of everything that’s to come. I need to ensure it's provided, and provided correctly. This is the first, necessary step; no source, no analysis. Let's make certain it's supplied, or the system can't even get off the ground.
|
| 324/2 |
2026/07/31 07:51 |
tool |
git-log |
0m
Args: map[CodeRegexp:gadgetfs_unbind.*\(gadget\) SourcePath:drivers/usb/gadget/legacy/inode.c SymbolName:gadgetfs_bind]
Results:
|
| 325/2 |
2026/07/31 07:52 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 51875
output: 54
thoughts: 21
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Analyzing the USB Gadget Inode Source**
Alright, let's zero in on `drivers/usb/gadget/inode.c`. That's going to be my starting point, my `SourcePath`, as I begin to dig into this. I'm focusing there because it likely handles the filesystem interface for the USB gadget framework. This suggests it's the bridge between user-space interactions with a USB gadget (like file transfers or control operations via `/dev/usb`) and the underlying USB device driver.
My initial hypothesis is that I'll find critical functions related to inode operations: creation, lookup, permission checks, data transfers, and probably event handling related to the filesystem. I expect to see structures and functions that interact with the USB device controller (like registers or data buffers) through some lower-level abstraction, but the focus *here* will be how the filesystem views the gadget. I'm anticipating interactions with the core USB gadget framework, potentially calling into functions within `gadget_core.c` or similar core infrastructure. I'll be looking for references to `struct inode`, `struct file`, and `struct usb_request` for the data transfers. The goal is to fully understand how the file system API is implemented for a USB Gadget. This particular file has a very specific role, and with that information I will be able to start.
|
| 326/2 |
2026/07/31 07:52 |
tool |
git-log |
0m
Error:
Args: map[CodeRegexp:gadgetfs_unbind.*\(gadget\) SourcePath:drivers/usb/gadget/inode.c SymbolName:gadgetfs_bind]
Results:
|
| 327/2 |
2026/07/31 07:52 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 52289
output: 42
thoughts: 42
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Debugging Git History: Navigating File Availability**
Right, so I was hitting a snag with `git log -L`. It just wasn't behaving as expected when trying to analyze the history of a particular code section. It struck me that `git log -L` is fundamentally dependent on the file actually *existing* in the specific commit I'm querying, which is a common gotcha. That's a good mental note to keep in mind, and something I've tripped over a few times.
To bypass that constraint, and dig into the evolution of this section of `inode.c` specifically, I immediately thought, "Let's bring in the heavy artillery: `git blame`." That should give me the line-by-line history, regardless of whether the file was named the same or present in any intermediate commits, which is precisely what I need. Starting with `drivers/usb/gadget/legacy/inode.c`, I'm pretty sure I can get the information I need to understand that code's modification history.
|
| 328/2 |
2026/07/31 07:52 |
tool |
git-blame |
0m
Args: map[End:1715 File:drivers/usb/gadget/legacy/inode.c Start:1690]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1690) dev->req->complete = epio_complete;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1691)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1692) if (activate_ep_files (dev) < 0)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1693) goto enomem;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1694)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1695) INFO (dev, "bound to %s driver\n", gadget->name);
7489d14943181 drivers/usb/gadget/inode.c 1696) spin_lock_irq(&dev->lock);
7489d14943181 drivers/usb/gadget/inode.c 1697) dev->state = STATE_DEV_UNCONNECTED;
7489d14943181 drivers/usb/gadget/inode.c 1698) spin_unlock_irq(&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1699) get_dev (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1700) return 0;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1701)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1702) enomem:
^1da177e4c3f4 drivers/usb/gadget/inode.c 1703) gadgetfs_unbind (gadget);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1704) return -ENOMEM;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1705) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1706)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1707) static void
^1da177e4c3f4 drivers/usb/gadget/inode.c 1708) gadgetfs_disconnect (struct usb_gadget *gadget)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1709) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1710) struct dev_data *dev = get_gadget_data (gadget);
001428e4871d6 drivers/usb/gadget/inode.c 1711) unsigned long flags;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1712)
001428e4871d6 drivers/usb/gadget/inode.c 1713) spin_lock_irqsave (&dev->lock, flags);
7489d14943181 drivers/usb/gadget/inode.c 1714) if (dev->state == STATE_DEV_UNCONNECTED)
07cb7f23d07aa drivers/usb/gadget/inode.c 1715) goto exit;
]
|
| 329/2 |
2026/07/31 07:52 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 53600
output: 42
thoughts: 60
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**GadgetFS Unbind: A Deep Dive**
Wow, *`gadgetfs_unbind (gadget);`* in the *`enomem:`* path. Seriously? That line's been in the code since the very beginning, all the way back to *`1da177e4c3f4`*, the initial commit. That's... significant. It's almost baked into the DNA of this thing. Given the age and importance of that location, and assuming the function has remained unchanged, it is worth exploring the logic surrounding this.
My immediate question is: does `gadgetfs_unbind` correctly drop the reference count on the `gadget` structure? The placement there in an `enomem:` path is what has me curious. Generally, you’d want to be *extremely* careful in error paths to ensure proper cleanup, especially of resources potentially being held. Depending on where else that `gadget` is referenced, or depending on how it's handled in the upper stack, a subtle reference count imbalance here could lead to some nasty long-term problems. I'd want to audit that function with an eye on memory management and reference counting.
|
| 330/2 |
2026/07/31 07:52 |
tool |
git-blame |
0m
Args: map[End:1665 File:drivers/usb/gadget/legacy/inode.c Start:1635]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1635) destroy_ep_files (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1636) return -ENOMEM;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1637) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1638)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1639) static void
^1da177e4c3f4 drivers/usb/gadget/inode.c 1640) gadgetfs_unbind (struct usb_gadget *gadget)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1641) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1642) struct dev_data *dev = get_gadget_data (gadget);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1643)
441b62c1edb98 drivers/usb/gadget/inode.c 1644) DBG (dev, "%s\n", __func__);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1645)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1646) spin_lock_irq (&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1647) dev->state = STATE_DEV_UNBOUND;
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1648) while (dev->udc_usage > 0) {
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1649) spin_unlock_irq(&dev->lock);
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1650) usleep_range(1000, 2000);
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1651) spin_lock_irq(&dev->lock);
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1652) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1653) spin_unlock_irq (&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1654)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1655) destroy_ep_files (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1656) gadget->ep0->driver_data = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1657) set_gadget_data (gadget, NULL);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1658)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1659) /* we've already been disconnected ... no i/o is active */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1660) if (dev->req)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1661) usb_ep_free_request (gadget->ep0, dev->req);
441b62c1edb98 drivers/usb/gadget/inode.c 1662) DBG (dev, "%s done\n", __func__);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1663) put_dev (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1664) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1665)
]
|
| 331/2 |
2026/07/31 07:52 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 55169
output: 42
thoughts: 155
Thoughts: **Analyzing the `gadgetfs` Device Binding and Unbinding**
Okay, so I'm looking at this `gadgetfs` code. I see that `gadgetfs_unbind` calls `put_dev(dev)`. That's expected, makes sense. Now, `gadgetfs_bind` calls `get_dev(dev)` at the very end, but if it fails, it jumps to `enomem:` and calls `gadgetfs_unbind(gadget)`, which, as we just established, *also* calls `put_dev(dev)`. This strongly suggests the `put_dev(dev)` is called on failure of the `get_dev(dev)`. This means it calls `put_dev` regardless of failure.
Given this, I have a pretty strong suspicion that the bug, whatever it is, has been present since commit `1da177e4c3f4`. It looks like there's a reference counting error due to calling `put_dev(dev)` on failure in the bind routine.
However, just to be sure, I need to check if any other commits have touched `gadgetfs_bind` or `gadgetfs_unbind` that might have introduced this subtly. I need to go back and double-check how `gadgetfs_bind` was implemented back in `1da177e4c3f4` again. Let's see if there were any relevant changes in that initial commit that were missed.
|
| 332/2 |
2026/07/31 07:52 |
tool |
git-blame |
0m
Args: map[End:1690 File:drivers/usb/gadget/legacy/inode.c Start:1666]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1666) static struct dev_data *the_device;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1667)
ffe0b33506250 drivers/usb/gadget/inode.c 1668) static int gadgetfs_bind(struct usb_gadget *gadget,
ffe0b33506250 drivers/usb/gadget/inode.c 1669) struct usb_gadget_driver *driver)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1670) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1671) struct dev_data *dev = the_device;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1672)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1673) if (!dev)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1674) return -ESRCH;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1675) if (0 != strcmp (CHIP, gadget->name)) {
00274921a052d drivers/usb/gadget/inode.c 1676) pr_err("%s expected %s controller not %s\n",
^1da177e4c3f4 drivers/usb/gadget/inode.c 1677) shortname, CHIP, gadget->name);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1678) return -ENODEV;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1679) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1680)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1681) set_gadget_data (gadget, dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1682) dev->gadget = gadget;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1683) gadget->ep0->driver_data = dev;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1684)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1685) /* preallocate control response and buffer */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1686) dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1687) if (!dev->req)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1688) goto enomem;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1689) dev->req->context = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1690) dev->req->complete = epio_complete;
]
|
| 333/2 |
2026/07/31 07:52 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 56661
output: 42
thoughts: 560
Thoughts: **Debugging a Use-After-Free in GadgetFS**
Okay, so `1da177e4c3f4` seems to be the culprit. Let's see if I'm understanding this correctly. I need to make sure `gadgetfs_unbind` wasn't always the problem.
Alright, in that commit, `gadgetfs_unbind` calls `put_dev(dev)`. And `gadgetfs_bind` has a corresponding `get_dev(dev)` at the end. Seems normal. Now, if `gadgetfs_bind` fails, it calls `gadgetfs_unbind(gadget)`, which, again, calls `put_dev(dev)`. That's where the problem arises. If `gadgetfs_bind` fails, `get_dev(dev)` never gets called in the first place, but `gadgetfs_unbind` will *still* call `put_dev(dev)`. Uh oh, that's an unbalanced reference count.
Okay, let me trace where `dev` is initially referenced. Back in `gadgetfs_fill_super`, `dev = dev_new();` creates it, and importantly, `atomic_set (&dev->count, 1);`. Then we have `the_device = dev;`.
So, when `gadgetfs_bind` is called, it uses `the_device`. If `gadgetfs_bind` *succeeds*, it does a `get_dev(dev)`, making `count` 2. Then, a successful `gadgetfs_unbind` will `put_dev(dev)`, back to 1. And when the file is closed, `dev_release` calls `put_dev(dev)`, and then `count` hits 0 and `dev` is freed, all good.
The issue arises when `gadgetfs_bind` *fails*. It calls `gadgetfs_unbind(gadget)`, which does `put_dev(dev)`, reducing the count to 0 and freeing `dev`. But, wait a minute! If `dev` is freed in the failure path, then when the user tries to close the file, `dev_release` will *still* call `put_dev(dev)`. That's a classic use-after-free!
Hang on, does a failed `gadgetfs_bind` lead to the file being closed? Yes, `dev_config` calls `usb_gadget_register_driver`. If that registration fails, `dev_config` returns an error. The user will then close the file, and `dev_release` gets called, which calls `put_dev(dev)`. That's the crux of it. If `gadgetfs_bind` already freed `dev`, then `dev_release` will be operating on freed memory. Need to confirm that `dev_config` looks correct in that commit.
|
| 334/2 |
2026/07/31 07:52 |
tool |
git-blame |
0m
Args: map[End:1850 File:drivers/usb/gadget/legacy/inode.c Start:1800]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1800) static ssize_t
^1da177e4c3f4 drivers/usb/gadget/inode.c 1801) dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1802) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1803) struct dev_data *dev = fd->private_data;
d13cce757954f drivers/usb/gadget/legacy/inode.c 1804) ssize_t value, length = len;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1805) unsigned total;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1806) u32 tag;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1807) char *kbuf;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1808)
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1809) spin_lock_irq(&dev->lock);
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1810) if (dev->state > STATE_DEV_OPENED) {
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1811) value = ep0_write(fd, buf, len, ptr);
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1812) spin_unlock_irq(&dev->lock);
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1813) return value;
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1814) }
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1815) spin_unlock_irq(&dev->lock);
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1816)
0994b0a257557 drivers/usb/gadget/legacy/inode.c 1817) if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||
0994b0a257557 drivers/usb/gadget/legacy/inode.c 1818) (len > PAGE_SIZE * 4))
^1da177e4c3f4 drivers/usb/gadget/inode.c 1819) return -EINVAL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1820)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1821) /* we might need to change message format someday */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1822) if (copy_from_user (&tag, buf, 4))
^1da177e4c3f4 drivers/usb/gadget/inode.c 1823) return -EFAULT;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1824) if (tag != 0)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1825) return -EINVAL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1826) buf += 4;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1827) length -= 4;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1828)
be8a058b50a90 drivers/usb/gadget/inode.c 1829) kbuf = memdup_user(buf, length);
be8a058b50a90 drivers/usb/gadget/inode.c 1830) if (IS_ERR(kbuf))
be8a058b50a90 drivers/usb/gadget/inode.c 1831) return PTR_ERR(kbuf);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1832)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1833) spin_lock_irq (&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1834) value = -EINVAL;
b6e7aeeaf2359 drivers/usb/gadget/legacy/inode.c 1835) if (dev->buf) {
89f3594d0de58 drivers/usb/gadget/legacy/inode.c 1836) spin_unlock_irq(&dev->lock);
b6e7aeeaf2359 drivers/usb/gadget/legacy/inode.c 1837) kfree(kbuf);
89f3594d0de58 drivers/usb/gadget/legacy/inode.c 1838) return value;
b6e7aeeaf2359 drivers/usb/gadget/legacy/inode.c 1839) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1840) dev->buf = kbuf;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1841)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1842) /* full or low speed config */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1843) dev->config = (void *) kbuf;
01ee7d7032204 drivers/usb/gadget/inode.c 1844) total = le16_to_cpu(dev->config->wTotalLength);
1c069b057dcf6 drivers/usb/gadget/legacy/inode.c 1845) if (!is_valid_config(dev->config, total) ||
1c069b057dcf6 drivers/usb/gadget/legacy/inode.c 1846) total > length - USB_DT_DEVICE_SIZE)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1847) goto fail;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1848) kbuf += total;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1849) length -= total;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1850)
]
|
| 335/2 |
2026/07/31 07:52 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 59903
output: 42
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 Configuration Structure**
Alright, let's break this down. My initial focus, naturally, is on the structure and intent of `dev_config`. I need to immediately understand its role in the overall system. Is it for local development overrides? Feature toggles? Environment-specific parameters? Knowing its purpose dictates how I interpret everything else. I'm looking for the defining key-value pairs; the ones that unlock the design patterns it's built upon, and expose how it plays into the overall architecture.
Then, I'll dive into the specifics. I'm mentally parsing the data types of each key. Booleans, strings, integers, lists, and more complex nested structures all have different implications. I'm searching for edge cases, potential areas of concern, and opportunities for optimization. Thinking through common pitfalls, like whether any configurations have any hidden dependencies.
Finally, I'm trying to see if there are any obvious anti-patterns at work. This includes bad practices like storing secrets in plain text, over-engineered configuration, or hard-coding. And then I will check to see if there are any well-established practices present.
|
| 336/2 |
2026/07/31 07:53 |
tool |
git-blame |
0m
Args: map[End:1900 File:drivers/usb/gadget/legacy/inode.c Start:1851]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1851) /* optional high speed config */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1852) if (kbuf [1] == USB_DT_CONFIG) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1853) dev->hs_config = (void *) kbuf;
01ee7d7032204 drivers/usb/gadget/inode.c 1854) total = le16_to_cpu(dev->hs_config->wTotalLength);
1c069b057dcf6 drivers/usb/gadget/legacy/inode.c 1855) if (!is_valid_config(dev->hs_config, total) ||
1c069b057dcf6 drivers/usb/gadget/legacy/inode.c 1856) total > length - USB_DT_DEVICE_SIZE)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1857) goto fail;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1858) kbuf += total;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1859) length -= total;
add333a81a16a drivers/usb/gadget/legacy/inode.c 1860) } else {
add333a81a16a drivers/usb/gadget/legacy/inode.c 1861) dev->hs_config = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1862) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1863)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1864) /* could support multiple configs, using another encoding! */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1865)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1866) /* device descriptor (tweaked for paranoia) */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1867) if (length != USB_DT_DEVICE_SIZE)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1868) goto fail;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1869) dev->dev = (void *)kbuf;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1870) if (dev->dev->bLength != USB_DT_DEVICE_SIZE
^1da177e4c3f4 drivers/usb/gadget/inode.c 1871) || dev->dev->bDescriptorType != USB_DT_DEVICE
^1da177e4c3f4 drivers/usb/gadget/inode.c 1872) || dev->dev->bNumConfigurations != 1)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1873) goto fail;
551509d267905 drivers/usb/gadget/inode.c 1874) dev->dev->bcdUSB = cpu_to_le16 (0x0200);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1875)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1876) /* triggers gadgetfs_bind(); then we can enumerate. */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1877) spin_unlock_irq (&dev->lock);
85b8614d72238 drivers/usb/gadget/inode.c 1878) if (dev->hs_config)
85b8614d72238 drivers/usb/gadget/inode.c 1879) gadgetfs_driver.max_speed = USB_SPEED_HIGH;
85b8614d72238 drivers/usb/gadget/inode.c 1880) else
85b8614d72238 drivers/usb/gadget/inode.c 1881) gadgetfs_driver.max_speed = USB_SPEED_FULL;
93952956c7078 drivers/usb/gadget/inode.c 1882)
af1969a2d734d drivers/usb/gadget/legacy/inode.c 1883) value = usb_gadget_register_driver(&gadgetfs_driver);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1884) if (value != 0) {
501e38a5531ef drivers/usb/gadget/legacy/inode.c 1885) spin_lock_irq(&dev->lock);
501e38a5531ef drivers/usb/gadget/legacy/inode.c 1886) goto fail;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1887) } else {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1888) /* at this point "good" hardware has for the first time
^1da177e4c3f4 drivers/usb/gadget/inode.c 1889) * let the USB the host see us. alternatively, if users
^1da177e4c3f4 drivers/usb/gadget/inode.c 1890) * unplug/replug that will clear all the error state.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1891) *
^1da177e4c3f4 drivers/usb/gadget/inode.c 1892) * note: everything running before here was guaranteed
^1da177e4c3f4 drivers/usb/gadget/inode.c 1893) * to choke driver model style diagnostics. from here
^1da177e4c3f4 drivers/usb/gadget/inode.c 1894) * on, they can work ... except in cleanup paths that
^1da177e4c3f4 drivers/usb/gadget/inode.c 1895) * kick in after the ep0 descriptor is closed.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1896) */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1897) value = len;
7b0a271d5cadf drivers/usb/gadget/legacy/inode.c 1898) dev->gadget_registered = true;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1899) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1900) return value;
]
|
| 337/2 |
2026/07/31 07:53 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 62229
output: 42
thoughts: 10
Thoughts: Okay, here's my interpretation of that.
**Analyzing the Configuration Failure**
Alright, let's break this down. Seeing "And `fail:` in `dev_config`" immediately raises a red flag. As a seasoned expert in [User's Field, e.g., software deployment, system administration, data engineering], that phrasing suggests a specific and critical error encountered within the development configuration, likely related to deployment, environment setup, or a configuration validation step. My mind jumps to possibilities: is it a syntax error in a configuration file? A failed dependency resolution? A permissions issue preventing access to a critical resource? The fact that it's in `dev_config` tells me it’s happening in a development context which is good, as it means this will hopefully not impact production. I need to know *what* failed, not just that it failed. That means I need to dig deeper into the logs for this environment, look for error messages that follow this statement, and understand the specific context where this failure occurs. Without more context, this is just a starting point for investigation. My first instinct would be to check for broken dependencies or missing files, that’s where my attention needs to focus. I'm going to have to analyze the build logs and the development configuration files to uncover the root cause.
|
| 338/2 |
2026/07/31 07:53 |
tool |
git-blame |
0m
Args: map[End:1920 File:drivers/usb/gadget/legacy/inode.c Start:1901]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1901)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1902) fail:
501e38a5531ef drivers/usb/gadget/legacy/inode.c 1903) dev->config = NULL;
501e38a5531ef drivers/usb/gadget/legacy/inode.c 1904) dev->hs_config = NULL;
501e38a5531ef drivers/usb/gadget/legacy/inode.c 1905) dev->dev = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1906) spin_unlock_irq (&dev->lock);
5b5e0928f742c drivers/usb/gadget/legacy/inode.c 1907) pr_debug ("%s: %s fail %zd, %p\n", shortname, __func__, value, dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1908) kfree (dev->buf);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1909) dev->buf = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1910) return value;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1911) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1912)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1913) static int
452785d0400aa drivers/usb/gadget/legacy/inode.c 1914) gadget_dev_open (struct inode *inode, struct file *fd)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1915) {
8e18e2941c534 drivers/usb/gadget/inode.c 1916) struct dev_data *dev = inode->i_private;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1917) int value = -EBUSY;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1918)
7489d14943181 drivers/usb/gadget/inode.c 1919) spin_lock_irq(&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1920) if (dev->state == STATE_DEV_DISABLED) {
]
|
| 339/2 |
2026/07/31 07:53 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 63332
output: 42
thoughts: 38
Thoughts: Okay, here's my interpretation of that sequence of events, formatted for a technically proficient user like myself:
**Understanding USB Gadget Driver Registration and Resource Management**
Alright, so the core logic here seems pretty straightforward, but I need to make sure I'm following the edge cases properly. My first thought is: If `usb_gadget_register_driver` throws an error during the driver registration process, that failure is then reflected by `dev_config` also returning an error. That makes sense; it's the expected propagation of a failure condition up the call stack. The whole setup depends on that initial registration succeeding, so any problem there *has* to be reported.
Now, where it gets interesting is the resource management aspect. If the user encounters the error, they'll close the file (or whatever resource is associated with this operation). And *that* is when `dev_release` comes into play. I'm assuming `dev_release` is the cleanup function or method associated with the `dev_config` structure, and it's there to handle any resources that were partially or conditionally allocated before the error. It is responsible for deallocating any resources that could have been allocated before the error. This is a critical point; otherwise, we'll see a resource leak. This is the part that would be critical if I were dealing with this implementation. Making sure I have a solid understanding of what `dev_release` *does* is going to be important to prevent any issues. I need to know *what* resources it releases and in *what* order to ensure the system remains stable and clean.
|
| 340/2 |
2026/07/31 07:53 |
tool |
git-blame |
0m
Args: map[End:1230 File:drivers/usb/gadget/legacy/inode.c Start:1200]
Results: map[Output:f50b878fed33e drivers/usb/gadget/legacy/inode.c 1200) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1201)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1202) /* at this point "good" hardware has disconnected the
^1da177e4c3f4 drivers/usb/gadget/inode.c 1203) * device from USB; the host won't see it any more.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1204) * alternatively, all host requests will time out.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1205) */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1206)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1207) kfree (dev->buf);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1208) dev->buf = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1209)
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1210) /* other endpoints were all decoupled from this device */
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1211) spin_lock_irq(&dev->lock);
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1212) dev->state = STATE_DEV_DISABLED;
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1213) spin_unlock_irq(&dev->lock);
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1214)
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1215) put_dev (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1216) return 0;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1217) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1218)
afc9a42b7464f drivers/usb/gadget/legacy/inode.c 1219) static __poll_t
e22fc27c87b41 drivers/usb/gadget/inode.c 1220) ep0_poll (struct file *fd, poll_table *wait)
e22fc27c87b41 drivers/usb/gadget/inode.c 1221) {
9311a531064be drivers/usb/gadget/legacy/inode.c 1222) struct dev_data *dev = fd->private_data;
9311a531064be drivers/usb/gadget/legacy/inode.c 1223) __poll_t mask = 0;
e22fc27c87b41 drivers/usb/gadget/inode.c 1224)
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1225) if (dev->state <= STATE_DEV_OPENED)
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1226) return DEFAULT_POLLMASK;
96b62a5719349 drivers/usb/gadget/legacy/inode.c 1227)
1ff767bfa54a9 drivers/usb/gadget/legacy/inode.c 1228) poll_wait(fd, &dev->wait, wait);
1ff767bfa54a9 drivers/usb/gadget/legacy/inode.c 1229)
1ff767bfa54a9 drivers/usb/gadget/legacy/inode.c 1230) spin_lock_irq(&dev->lock);
]
|
| 341/2 |
2026/07/31 07:53 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 64924
output: 42
thoughts: 153
Thoughts: **Double Free Detection and Analysis**
Okay, so I'm looking at this code and it's pretty clear: `dev_release` calls `put_dev(dev)`. That's normal. Now, if `gadgetfs_bind` fails, it *also* calls `gadgetfs_unbind(gadget)`, which, you guessed it, calls `put_dev(dev)`. So we've got a double `put_dev(dev)` happening, either directly by `dev_release`, or indirectly via the unbind path. This is screaming double-free or use-after-free, classic.
But hold on, the bug report... "Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**." Aha! Now we're talking. So the real problem isn't that we are double decrementing the refcount, but that we are decrementing a refcount *that was never incremented*.
This changes things. Was there a commit that inadvertently changed this code path? Let's verify that `get_dev(dev)` was always called at the end of the `gadgetfs_bind` function. That will tell us if it's a regression or if it's always been flawed.
|
| 342/2 |
2026/07/31 07:53 |
tool |
git-blame |
0m
Args: map[End:1705 File:drivers/usb/gadget/legacy/inode.c Start:1690]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1690) dev->req->complete = epio_complete;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1691)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1692) if (activate_ep_files (dev) < 0)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1693) goto enomem;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1694)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1695) INFO (dev, "bound to %s driver\n", gadget->name);
7489d14943181 drivers/usb/gadget/inode.c 1696) spin_lock_irq(&dev->lock);
7489d14943181 drivers/usb/gadget/inode.c 1697) dev->state = STATE_DEV_UNCONNECTED;
7489d14943181 drivers/usb/gadget/inode.c 1698) spin_unlock_irq(&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1699) get_dev (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1700) return 0;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1701)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1702) enomem:
^1da177e4c3f4 drivers/usb/gadget/inode.c 1703) gadgetfs_unbind (gadget);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1704) return -ENOMEM;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1705) }
]
|
| 343/2 |
2026/07/31 07:53 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 66014
output: 42
thoughts: 110
Thoughts: **Debugging a Persistent Kernel Bug**
Okay, so I'm tracking down this nasty kernel bug, and it looks like the issue stems from `get_dev(dev)` consistently being placed at the end of the `gadgetfs_bind` function and, conversely, the corresponding `gadgetfs_unbind` function always having been called in the `enomem:` error handling path. Therefore, the problem very likely dates back to the initial commit, `1da177e4c3f4`.
But, as any seasoned kernel developer knows, you can't be *too* confident without a thorough check. Time to really dig in and make sure no other commit might have subtly introduced the flaw. I'll have to meticulously comb through the commit history. Specifically, I'm going to look closely at the `gadgetfs_unbind` function to ensure that it has always, without fail, called `put_dev(dev)`. This seems like the most obvious candidate for an inadvertent regression, so I'll start there.
|
| 344/2 |
2026/07/31 07:53 |
tool |
git-blame |
0m
Args: map[End:1665 File:drivers/usb/gadget/legacy/inode.c Start:1635]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1635) destroy_ep_files (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1636) return -ENOMEM;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1637) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1638)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1639) static void
^1da177e4c3f4 drivers/usb/gadget/inode.c 1640) gadgetfs_unbind (struct usb_gadget *gadget)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1641) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1642) struct dev_data *dev = get_gadget_data (gadget);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1643)
441b62c1edb98 drivers/usb/gadget/inode.c 1644) DBG (dev, "%s\n", __func__);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1645)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1646) spin_lock_irq (&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1647) dev->state = STATE_DEV_UNBOUND;
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1648) while (dev->udc_usage > 0) {
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1649) spin_unlock_irq(&dev->lock);
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1650) usleep_range(1000, 2000);
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1651) spin_lock_irq(&dev->lock);
520b72fc64deb drivers/usb/gadget/legacy/inode.c 1652) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1653) spin_unlock_irq (&dev->lock);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1654)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1655) destroy_ep_files (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1656) gadget->ep0->driver_data = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1657) set_gadget_data (gadget, NULL);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1658)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1659) /* we've already been disconnected ... no i/o is active */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1660) if (dev->req)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1661) usb_ep_free_request (gadget->ep0, dev->req);
441b62c1edb98 drivers/usb/gadget/inode.c 1662) DBG (dev, "%s done\n", __func__);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1663) put_dev (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1664) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1665)
]
|
| 345/2 |
2026/07/31 07:53 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 67585
output: 42
thoughts: 43
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Investigating Device Release in GadgetFS**
Right, `put_dev(dev)` was *always* part of the `gadgetfs_unbind` function. That's etched in my memory. Now, let me just quickly double-check something that's been nagging at me. What about the lifecycle, specifically `dev_release`? I'm trying to recall if `dev_release` *also* consistently called `put_dev(dev)`. That's the crucial link I need to clarify in my head. I have a feeling something important is connected here...I just need to trace this control flow through this code.
|
| 346/2 |
2026/07/31 07:53 |
tool |
git-blame |
0m
Args: map[End:1220 File:drivers/usb/gadget/legacy/inode.c Start:1190]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1190) static int
^1da177e4c3f4 drivers/usb/gadget/inode.c 1191) dev_release (struct inode *inode, struct file *fd)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1192) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1193) struct dev_data *dev = fd->private_data;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1194)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1195) /* closing ep0 === shutdown all */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1196)
f50b878fed33e drivers/usb/gadget/legacy/inode.c 1197) if (dev->gadget_registered) {
7b0a271d5cadf drivers/usb/gadget/legacy/inode.c 1198) usb_gadget_unregister_driver (&gadgetfs_driver);
f50b878fed33e drivers/usb/gadget/legacy/inode.c 1199) dev->gadget_registered = false;
f50b878fed33e drivers/usb/gadget/legacy/inode.c 1200) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1201)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1202) /* at this point "good" hardware has disconnected the
^1da177e4c3f4 drivers/usb/gadget/inode.c 1203) * device from USB; the host won't see it any more.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1204) * alternatively, all host requests will time out.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1205) */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1206)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1207) kfree (dev->buf);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1208) dev->buf = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1209)
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1210) /* other endpoints were all decoupled from this device */
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1211) spin_lock_irq(&dev->lock);
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1212) dev->state = STATE_DEV_DISABLED;
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1213) spin_unlock_irq(&dev->lock);
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1214)
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1215) put_dev (dev);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1216) return 0;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1217) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1218)
afc9a42b7464f drivers/usb/gadget/legacy/inode.c 1219) static __poll_t
e22fc27c87b41 drivers/usb/gadget/inode.c 1220) ep0_poll (struct file *fd, poll_table *wait)
]
|
| 347/2 |
2026/07/31 07:53 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 68987
output: 42
thoughts: 1234
Thoughts: **Debugging a GadgetFS Use-After-Free Vulnerability**
Okay, let's break this down. First, `dev_release` always calls `put_dev(dev)`, that's a constant. The initial thought I had was about what happens if `usb_gadget_register_driver` fails, and it looks like that's the key. If registration fails, `dev_config` returns an error, and `dev_release` gets called when the file is closed.
Now, if `usb_gadget_register_driver` fails because `gadgetfs_bind` failed, `gadgetfs_bind` already did a `gadgetfs_unbind`, which itself calls `put_dev(dev)`. So, `dev_release` calls it *again*. That's the redundant `put_dev`. I think the bug was introduced with `1da177e4c3f4`. I need to confirm `gadgetfs_unbind` *always* calls `put_dev(dev)`, and yes, it does at the end. That's a good starting point.
No other commit appears to have messed with refcounting. Let's look at the initialization of the `dev` struct; in `gadgetfs_fill_super`, `dev_new()` gives it a count of 1.
Then, when we `gadget_dev_open`, the `inode`'s `i_private` is the `dev`. Critically, `gadget_dev_open` calls `get_dev(dev)`. So opening the file *increments* the refcount. This gives `dev` a count of 2. `dev_config` is then called (through a `write` call on the file). If `gadgetfs_bind` succeeds, *it* calls `get_dev(dev)`, so the count goes to 3. If it *fails*, `gadgetfs_unbind` happens, reducing the count back to 1. But `dev_config` returns an error. Then, the user closes the file, `dev_release` is called, and `put_dev(dev)` is called. At this point, the refcount should be 0, and `dev` is freed.
The problem, as I see it, is that *the inode still exists*. The `inode`'s `i_private` field, which contains a pointer to the now-freed `dev` object, remains valid. The bug report points out the key: if the file is opened again, `gadget_dev_open` attempts to access that freed memory via the `inode->i_private` pointer. This results in the slab-use-after-free crash.
So, the issue is that the `dev` struct is freed, but the inode and other data structures in the filesystem, which still holds the pointer to `dev`, remain valid. The inode is only destroyed on unmount.
Now, let's trace this through with a *successful* `gadgetfs_bind`: count starts at 1, `gadget_dev_open` goes to 2, and a successful bind increments it to 3. When the user closes, `dev_release` is called, and `put_dev(dev)` reduces the count to 2.
*Wait*, does closing the file unregister the driver? Let's check `dev_release`: Ah yes, if the driver is registered, `usb_gadget_unregister_driver` gets called, which in turn calls `gadgetfs_unbind`. `gadgetfs_unbind` calls `put_dev(dev)`, so the refcount becomes 1. Then `dev_release` *also* calls `put_dev(dev)`, and the refcount becomes 0. `dev` is freed! The inode still exists and points to invalid memory! If the user opens the file again, it will access the freed `dev`. I've got it!
|
| 348/2 |
2026/07/31 07:54 |
tool |
git-blame |
0m
Args: map[End:1210 File:drivers/usb/gadget/legacy/inode.c Start:1190]
Results: map[Output:^1da177e4c3f4 drivers/usb/gadget/inode.c 1190) static int
^1da177e4c3f4 drivers/usb/gadget/inode.c 1191) dev_release (struct inode *inode, struct file *fd)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1192) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 1193) struct dev_data *dev = fd->private_data;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1194)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1195) /* closing ep0 === shutdown all */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1196)
f50b878fed33e drivers/usb/gadget/legacy/inode.c 1197) if (dev->gadget_registered) {
7b0a271d5cadf drivers/usb/gadget/legacy/inode.c 1198) usb_gadget_unregister_driver (&gadgetfs_driver);
f50b878fed33e drivers/usb/gadget/legacy/inode.c 1199) dev->gadget_registered = false;
f50b878fed33e drivers/usb/gadget/legacy/inode.c 1200) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 1201)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1202) /* at this point "good" hardware has disconnected the
^1da177e4c3f4 drivers/usb/gadget/inode.c 1203) * device from USB; the host won't see it any more.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1204) * alternatively, all host requests will time out.
^1da177e4c3f4 drivers/usb/gadget/inode.c 1205) */
^1da177e4c3f4 drivers/usb/gadget/inode.c 1206)
^1da177e4c3f4 drivers/usb/gadget/inode.c 1207) kfree (dev->buf);
^1da177e4c3f4 drivers/usb/gadget/inode.c 1208) dev->buf = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 1209)
f0cae93f3f7e9 drivers/usb/gadget/inode.c 1210) /* other endpoints were all decoupled from this device */
]
|
| 349/2 |
2026/07/31 07:54 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 71909
output: 26
thoughts: 47
Thoughts: **Investigating USB Gadget Driver Unregistration**
Okay, so I'm trying to understand this code and something's caught my eye. The function `usb_gadget_unregister_driver`... that was introduced in commit `7b0a271d5cadf`, was it? Just want to be sure I have the history right, and it aligns with my expectations. Need to make a mental note to verify. Right, best to double-check that commit and verify what was going on at the time that this was introduced into the code base. Let's pull up that commit. Need to get the context right to understand how it's being used.
|
| 350/2 |
2026/07/31 07:54 |
tool |
git-show |
0m
Args: map[Commit:7b0a271d5cadf]
Results: map[Output:commit 7b0a271d5cadf5fbb5a9c7cb868776af2a2c248c
Author: Marek Szyprowski <m.szyprowski@samsung.com>
Date: Thu Feb 18 08:59:26 2016 +0100
usb: gadget: gadgetfs: unregister gadget only if it got successfully registered
Gadgetfs driver called usb_gadget_unregister_driver unconditionally, even
if it didn't register it earlier due to other failures. This patch fixes
this.
Reported-by: Vegard Nossum <vegard.nossum@oracle.com>
Signed-off-by: Marek Szyprowski <m.szyprowski@samsung.com>
Tested-by: Vegard Nossum <vegard.nossum@oracle.com>
Signed-off-by: Felipe Balbi <balbi@kernel.org>
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 7e179f81d05c..87fb0fd6aaab 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -130,7 +130,8 @@ struct dev_data {
setup_can_stall : 1,
setup_out_ready : 1,
setup_out_error : 1,
- setup_abort : 1;
+ setup_abort : 1,
+ gadget_registered : 1;
unsigned setup_wLength;
/* the rest is basically write-once */
@@ -1179,7 +1180,8 @@ dev_release (struct inode *inode, struct file *fd)
/* closing ep0 === shutdown all */
- usb_gadget_unregister_driver (&gadgetfs_driver);
+ if (dev->gadget_registered)
+ usb_gadget_unregister_driver (&gadgetfs_driver);
/* at this point "good" hardware has disconnected the
* device from USB; the host won't see it any more.
@@ -1847,6 +1849,7 @@ dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
* kick in after the ep0 descriptor is closed.
*/
value = len;
+ dev->gadget_registered = true;
}
return value;
]
|
| 351/2 |
2026/07/31 07:54 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 72798
output: 42
thoughts: 719
Thoughts: **Analyzing a Use-After-Free Vulnerability**
Okay, so this commit `7b0a271d5cadf` added `dev->gadget_registered`. That's interesting. Before that, `dev_release` unconditionally called `usb_gadget_unregister_driver`. Hmm, that seems odd. If `usb_gadget_unregister_driver` was called regardless of driver registration status, what happened when the driver wasn't actually registered?
My initial thought is that if `usb_gadget_register_driver` had failed, `dev_config` would have returned an error. Then, `dev_release` would still have blindly called `usb_gadget_unregister_driver`. Perhaps `usb_gadget_unregister_driver` simply checked if the driver was registered and did nothing if it wasn't? Yes, that's likely the case, it probably has that check built-in.
But here's a wrinkle: if `gadgetfs_bind` fails, `usb_gadget_register_driver` fails and returns an error. The driver is *not* registered. So, `usb_gadget_unregister_driver` does nothing. This means `gadgetfs_unbind` isn't called from `dev_release` in that error path. In fact, `gadgetfs_unbind` is only called from `gadgetfs_bind`'s error path!
Let me trace the reference count to confirm. We start with a count of 1 from `dev_new()`. `gadget_dev_open` increments the count to 2 with `get_dev(dev)`. Then, in `dev_config`, we call `usb_gadget_register_driver`, which calls `gadgetfs_bind`. If `gadgetfs_bind` *fails*, it calls `gadgetfs_unbind`, which decrements the count to 1 with `put_dev(dev)`. Now, `dev_config` returns an error. The user closes the file, triggering `dev_release`. `dev_release` *now* checks `dev->gadget_registered` (which is false in this failure scenario). It skips `usb_gadget_unregister_driver`, then calls `put_dev(dev)`, making the count zero, and `dev` is freed. *But*, the inode still points to this freed `dev`! If the user then re-opens the file, `gadget_dev_open` will try to access `inode->i_private`, which is now freed memory. Bingo! That's a classic use-after-free vulnerability!
Now, if `gadgetfs_bind` *succeeds*, it's a different story. The initial count is 1. `gadget_dev_open` increments it to 2. `gadgetfs_bind` succeeds, and `get_dev(dev)` increments it to 3. `dev_config` sets `dev->gadget_registered = true`. The user closes the file, hitting `dev_release`. `dev_release` *does* call `usb_gadget_unregister_driver`, which then calls `gadgetfs_unbind`. `gadgetfs_unbind` decrements to 2 with `put_dev(dev)`. `dev_release` *also* calls `put_dev(dev)`, bringing the count to 1. So, in this successful path, `dev` is *not* immediately freed. When is it freed then? It looks like it's freed when the filesystem is unmounted! I'd better go look into `gadgetfs_kill_sb` or similar to see the cleanup in that scenario.
|
| 352/2 |
2026/07/31 07:54 |
tool |
git-blame |
0m
Args: map[End:2120 File:drivers/usb/gadget/legacy/inode.c Start:2090]
Results: map[Output:e5d82a7360d12 drivers/usb/gadget/legacy/inode.c 2090) };
e5d82a7360d12 drivers/usb/gadget/legacy/inode.c 2091)
e5d82a7360d12 drivers/usb/gadget/legacy/inode.c 2092) static int gadgetfs_init_fs_context(struct fs_context *fc)
e5d82a7360d12 drivers/usb/gadget/legacy/inode.c 2093) {
e5d82a7360d12 drivers/usb/gadget/legacy/inode.c 2094) fc->ops = &gadgetfs_context_ops;
e5d82a7360d12 drivers/usb/gadget/legacy/inode.c 2095) return 0;
^1da177e4c3f4 drivers/usb/gadget/inode.c 2096) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 2097)
^1da177e4c3f4 drivers/usb/gadget/inode.c 2098) static void
^1da177e4c3f4 drivers/usb/gadget/inode.c 2099) gadgetfs_kill_sb (struct super_block *sb)
^1da177e4c3f4 drivers/usb/gadget/inode.c 2100) {
d18dcfe9860e8 drivers/usb/gadget/legacy/inode.c 2101) mutex_lock(&sb_mutex);
57db9d428ba50 drivers/usb/gadget/legacy/inode.c 2102) kill_anon_super (sb);
^1da177e4c3f4 drivers/usb/gadget/inode.c 2103) if (the_device) {
^1da177e4c3f4 drivers/usb/gadget/inode.c 2104) put_dev (the_device);
^1da177e4c3f4 drivers/usb/gadget/inode.c 2105) the_device = NULL;
^1da177e4c3f4 drivers/usb/gadget/inode.c 2106) }
175f712119c57 drivers/usb/gadget/legacy/inode.c 2107) kfree(CHIP);
175f712119c57 drivers/usb/gadget/legacy/inode.c 2108) CHIP = NULL;
d18dcfe9860e8 drivers/usb/gadget/legacy/inode.c 2109) mutex_unlock(&sb_mutex);
^1da177e4c3f4 drivers/usb/gadget/inode.c 2110) }
^1da177e4c3f4 drivers/usb/gadget/inode.c 2111)
^1da177e4c3f4 drivers/usb/gadget/inode.c 2112) /*----------------------------------------------------------------------*/
^1da177e4c3f4 drivers/usb/gadget/inode.c 2113)
^1da177e4c3f4 drivers/usb/gadget/inode.c 2114) static struct file_system_type gadgetfs_type = {
^1da177e4c3f4 drivers/usb/gadget/inode.c 2115) .owner = THIS_MODULE,
^1da177e4c3f4 drivers/usb/gadget/inode.c 2116) .name = shortname,
e5d82a7360d12 drivers/usb/gadget/legacy/inode.c 2117) .init_fs_context = gadgetfs_init_fs_context,
^1da177e4c3f4 drivers/usb/gadget/inode.c 2118) .kill_sb = gadgetfs_kill_sb,
^1da177e4c3f4 drivers/usb/gadget/inode.c 2119) };
7f78e03513940 drivers/usb/gadget/inode.c 2120) MODULE_ALIAS_FS("gadgetfs");
]
|
| 353/2 |
2026/07/31 07:54 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 75522
output: 54
thoughts: 1676
Thoughts: **Analysis of the GadgetFS Reference Counting Bug**
Okay, so here's what I've figured out. `gadgetfs_kill_sb` calls `put_dev(the_device)`. If `gadgetfs_bind` succeeds, the reference count is incremented by 1 after `dev_release`, and then decremented again when `gadgetfs_kill_sb` calls `put_dev`. That works as expected; the device is freed properly.
However, if `gadgetfs_bind` fails, `dev_release` decrements the count to 0, and the device is prematurely freed. Then, `gadgetfs_kill_sb` *still* tries to `put_dev(the_device)`, resulting in a use-after-free! Also, `gadget_dev_open` will lead to another use-after-free.
The core problem is that `gadgetfs_unbind` is decrementing a reference count that was *never* incremented in the failure path of `gadgetfs_bind`. This bug has to be as old as dirt.
The bug report confirms this: `gadgetfs_bind` takes a reference with `get_dev` upon success, but calls `gadgetfs_unbind` on failure, which drops a reference that was never acquired. The provided code snippets match this perfectly. The critical snippet from `gadgetfs_bind` clearly shows the `get_dev` call *after* the potentially failing `activate_ep_files` and the `gadgetfs_unbind` call in the error path. `gadgetfs_unbind` then calls `put_dev` without the matching `get_dev` call.
Now, could any other commit have introduced this? Let's see. The bug report points to the initial commit, so that's where I'm focusing. It makes sense, as this is a fundamental flaw in the error handling.
I've checked the code in the initial commit, which is `1da177e4c3f4212273a92e4f70ce7223680270fa`. I've confirmed that the critical code snippets for both `gadgetfs_bind` and `gadgetfs_unbind` match exactly what's described in the bug report and what I've just analyzed. `git blame` confirms that the error label, the `gadgetfs_unbind` call, and the `get_dev` are all from this initial commit.
The fix patch replaces the `gadgetfs_unbind` call in the error path with direct cleanup, avoiding the problematic `put_dev`. That confirms my diagnosis.
So, could it be a later change to `activate_ep_files` or the introduction of fault injection? Those are just environmental factors; the bug is the *unbalanced* refcount. It doesn't matter how often `activate_ep_files` fails, the unbalanced `get_dev` and `put_dev` remain the root cause. This has been present since the beginning of the code.
I've also double-checked: `put_dev(dev)` in `gadgetfs_unbind`, `get_dev(dev)` at the end of `gadgetfs_bind`, and `gadgetfs_unbind(gadget)` in the error path were all introduced in the initial commit, `1da177e4c3f4`.
Therefore, the bug was definitely introduced in `1da177e4c3f4212273a92e4f70ce7223680270fa`.
|
| 354/2 |
2026/07/31 07:54 |
tool |
set-results |
0m
Error:
Args: map[FixesHash:1da177e4c3f4212273a92e4f70ce7223680270fa]
Results: map[FixesHash:1da177e4c3f4212273a92e4f70ce7223680270fa]
|
| 355/2 |
2026/07/31 07:54 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 78110
output: 32
thoughts: 103
Thoughts: **Debugging a Missing Object**
Okay, so I'm hitting a snag. It looks like I can't find the object with hash `1da177e4c3f4212273a92e4f70ce7223680270fa`. Hmm, that's unusual. My first thought is a possible typo. Is it possible that the hash I'm looking for is slightly off? Let me double-check. Maybe I misremembered it, or there was a copy-paste error.
Ah! Let me quickly confirm if the *correct* hash is `1da177e4c3f412273a92e4f70ce7223680270fa`. Better to be precise; a single character out of place, and you are lost. Right, time to verify and compare the initial commit's actual hash against my current working version. Precision is key in tracking down these things.
|
| 356/2 |
2026/07/31 07:54 |
tool |
git-log |
0m
Args: map[Count:1 PathPrefix:drivers/usb/gadget/legacy/inode.c]
Results: map[Output:bf4afc53b77a Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
]
|
| 357/2 |
2026/07/31 07:54 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 78504
output: 26
thoughts: 20
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Getting the Full Hash**
Okay, so I need to grab the full hash for `1da177e4c3f4`. That short form is definitely a commit, and I need the complete representation. I'm probably looking at a specific context – likely a Git repository, and I'm assuming that the tool in question is capable of resolving that short hash to its full, 40-character SHA-1 representation. I'm either going to run a Git command directly, probably using `git rev-parse`, or leverage some API function. The method I choose will depend on the environment. I'm going to determine which is faster and available in this situation. My brain is already starting to formulate the command or function call: maybe `git rev-parse 1da177e4c3f4` if I'm at a command line, or something similar if I'm using a library. The specific command might depend on which library I'm using. Ultimately, I'm trying to ensure I'm getting the precise identifier for the commit object, not a partial or ambiguous one.
|
| 358/2 |
2026/07/31 07:55 |
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
]
]
|
| 359/2 |
2026/07/31 07:55 |
llm |
fixes-finder |
0m
Model:
Tokens:
input: 90674
output: 53
thoughts: 53
Thoughts: Okay, here's my interpretation of that.
**Setting the Stage with Git**
Alright, so the baseline, the very beginning of this process, is pegged to this commit hash: `1da177e4c3f41524e886b7f1b8a0c1fc7321cac2`. Right, that's my starting point. That hash is the definitive fingerprint, the immutable record of the state I'm working from. Now, I need to make sure I anchor my actions, whatever I do next, to that specific point in history. So I'm setting the stage, locking it down. This base is now my foundation.
|
| 360/2 |
2026/07/31 07:55 |
tool |
set-results |
0m
Args: map[FixesHash:1da177e4c3f41524e886b7f1b8a0c1fc7321cac2]
Results: map[FixesHash:1da177e4c3f41524e886b7f1b8a0c1fc7321cac2]
|
| 361/1 |
2026/07/31 07:55 |
action |
format-fixes |
0m
Results: map[Fixes:map[AuthorEmail:torvalds@ppc970.osdl.org AuthorName:Linus Torvalds Hash:1da177e4c3f41524e886b7f1b8a0c1fc7321cac2 Title:Linux-2.6.12-rc2]]
|
| 362/1 |
2026/07/31 07:55 |
action |
get-maintainers |
0m
Results: map[Recipients:[map[Email:brauner@kernel.org Name:Christian Brauner To:false] map[Email:gregkh@linuxfoundation.org Name:Greg Kroah-Hartman To:true] map[Email:jack@suse.cz Name:Jan Kara To:false] map[Email:kees@kernel.org Name:Kees Cook To:false] map[Email:linux-kernel@vger.kernel.org Name: To:false] map[Email:linux-usb@vger.kernel.org Name: To:true] map[Email:mjguzik@gmail.com Name:Mateusz Guzik To:false] map[Email:viro@zeniv.linux.org.uk Name:Al Viro To:false] map[Email:torvalds@ppc970.osdl.org Name:Linus Torvalds To:true]]]
|
| 363/1 |
2026/07/31 07:55 |
action |
get-recent-commits |
0m
Results: map[RecentCommits:Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
treewide: Replace kmalloc with kmalloc_obj for non-scalar types
convert gadgetfs
gadgetfs: switch to simple_remove_by_name()
fs: rename generic_delete_inode() and generic_drop_inode()
functionfs, gadgetfs: use simple_recursive_removal()
USB: gadget: Replace deprecated strncpy() with strscpy()
USB: gadget: Use str_enable_disable-like helpers
[tree-wide] finally take no_llseek out
legacy: convert to new timestamp accessors
usb: gadgetfs: return USB_GADGET_DELAYED_STATUS from setup()
usb: convert to ctime accessor functions
usb: gadgetfs: Fix ep_read_iter to handle ITER_UBUF
USB: gadgetfs: Fix race between mounting and unmounting
gadgetfs: ep_io - wait until IRQ finishes
USB: gadget: Rename usb_gadget_probe_driver()
usb: gadget: eliminate anonymous module_init & module_exit
headers/prep: usb: gadget: Fix namespace collision
usb: gadget: clear related members when goto fail
usb: gadget: don't release an existing dev->buf
]
|
| 364/1 |
2026/07/31 07:55 |
agent |
description-generator |
0m
Model:
Instruction:
You are an experienced Linux kernel developer tasked with writing a commit description for
a kernel bug fixing commit. The description should start with a one-line summary,
and then include description of the bug being fixed, and how it's fixed by the provided patch.
The one-line summary should describe the change being made, rather than mention the tool that
detected the bug.
The description must not contain lines starting with '#' because they will dropped by git as comments.
The description must not contain lines starting with '--' or '---' (including inline code diffs)
because they may confuse git/patch utilities.
Your final reply should contain only the text of the commit description.
The one-line summary must be not longer than 72 characters.
IMPORTANT: Do not wrap lines manually (e.g., at 80 characters); we will reformat the text
automatically, so keep paragraphs as single lines without newlines.
Generally try to phrase the description without mentioning syzkaller
(avoid phrases like "the bug was triggered by syzkaller" or "the bug was triggered by fuzzer", etc).
How the bug was triggered is generally an irrelevant detail.
Any bug triggered by a fuzzer can also be triggered by a malicious user, or a buggy program.
If the crash is reported by a sanitizer (e.g., KASAN, KMSAN, lockdep), include the relevant
parts of the sanitizer output to illustrate the problem. Exclude less relevant sections,
as the stack trace can be very long. Describe the execution path that leads to the manifestation
of the kernel bug.
Prefer calling several tools at the same time to save round-trips.
Prompt:
The crash that corresponds to the bug is:
==================================================================
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Not tainted syzkaller #1 PREEMPT
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
print_address_description+0xb0/0x238 mm/kasan/report.c:378
print_report+0x68/0x84 mm/kasan/report.c:482
kasan_report+0x8c/0xc4 mm/kasan/report.c:595
__kasan_check_byte+0x3c/0x54 mm/kasan/common.c:574
kasan_check_byte include/linux/kasan.h:402 [inline]
lock_acquire+0xa4/0x364 kernel/locking/lockdep.c:5842
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Allocated by task 5241:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_alloc_info+0x44/0x54 mm/kasan/generic.c:570
poison_kmalloc_redzone mm/kasan/common.c:398 [inline]
__kasan_kmalloc+0x9c/0xb4 mm/kasan/common.c:415
kasan_kmalloc include/linux/kasan.h:263 [inline]
__kmalloc_cache_noprof+0x2e8/0x5ec mm/slub.c:5489
_kmalloc_noprof include/linux/slab.h:988 [inline]
_kzalloc_noprof include/linux/slab.h:1309 [inline]
dev_new drivers/usb/gadget/legacy/inode.c:176 [inline]
gadgetfs_fill_super+0x19c/0x370 drivers/usb/gadget/legacy/inode.c:2054
vfs_get_super+0xb8/0x148 fs/super.c:1273
get_tree_single+0x30/0x40 fs/super.c:1300
gadgetfs_get_tree+0x28/0x38 drivers/usb/gadget/legacy/inode.c:2085
vfs_get_tree+0x90/0x28c fs/super.c:1700
fc_mount+0x24/0xac fs/namespace.c:1198
do_new_mount_fc fs/namespace.c:3765 [inline]
do_new_mount+0x2a4/0x538 fs/namespace.c:3841
path_mount+0x5f0/0xa88 fs/namespace.c:4161
do_mount+0xe8/0x148 fs/namespace.c:4174
__do_sys_mount fs/namespace.c:4390 [inline]
__se_sys_mount fs/namespace.c:4367 [inline]
__arm64_sys_mount+0x334/0x380 fs/namespace.c:4367
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Freed by task 5331:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x40/0x78 mm/kasan/common.c:78
kasan_save_free_info+0x58/0x70 mm/kasan/generic.c:584
poison_slab_object mm/kasan/common.c:253 [inline]
__kasan_slab_free+0x74/0xa4 mm/kasan/common.c:285
kasan_slab_free include/linux/kasan.h:235 [inline]
slab_free_hook mm/slub.c:2677 [inline]
slab_free mm/slub.c:6377 [inline]
kfree+0x188/0x690 mm/slub.c:6692
put_dev+0x8c/0xf8 drivers/usb/gadget/legacy/inode.c:169
dev_release+0x100/0x15c drivers/usb/gadget/legacy/inode.c:1215
__fput+0x338/0x74c fs/file_table.c:512
____fput+0x20/0x30 fs/file_table.c:540
task_work_run+0x1cc/0x25c kernel/task_work.c:233
resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]
__exit_to_user_mode_loop kernel/entry/common.c:70 [inline]
exit_to_user_mode_loop+0x10c/0x17c kernel/entry/common.c:101
__exit_to_user_mode_prepare include/linux/irq-entry-common.h:207 [inline]
syscall_exit_to_user_mode_prepare include/linux/irq-entry-common.h:230 [inline]
arm64_syscall_exit_to_user_mode arch/arm64/kernel/entry-common.c:88 [inline]
el0_svc+0x18c/0x260 arch/arm64/kernel/entry-common.c:737
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
The buggy address belongs to the object at ffff0000dbe16000
which belongs to the cache kmalloc-1k of size 1024
The buggy address is located 24 bytes inside of
freed 1024-byte region [ffff0000dbe16000, ffff0000dbe16400)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0xffff0000dbe15000 pfn:0x11be10
head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
flags: 0x5ffc00000000240(workingset|head|node=0|zone=2|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
raw: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000240 ffff0000c0001dc0 fffffdffc345e610 fffffdffc34fe610
head: ffff0000dbe15000 0000000800100003 00000000f5000000 0000000000000000
head: 05ffc00000000003 fffffdffc36f8401 00000000ffffffff 00000000ffffffff
head: ffffffffffffffff 0000000000000000 00000000ffffffff 0000000000000008
page dumped because: kasan: bad access detected
Memory state around the buggy address:
ffff0000dbe15f00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff0000dbe15f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff0000dbe16000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff0000dbe16080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff0000dbe16100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
------------[ cut here ]------------
UBSAN: array-index-out-of-bounds in /app/workdir/cache/src/3735123449433f9e6f9fb5b55ddd9994cbcf15f0/kernel/locking/qspinlock.h:68:9
index 13031 is out of range for type 'unsigned long[8]'
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
Call trace:
show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:499 (C)
__dump_stack+0x30/0x40 lib/dump_stack.c:94
dump_stack_lvl+0xd8/0x12c lib/dump_stack.c:120
dump_stack+0x1c/0x28 lib/dump_stack.c:129
ubsan_epilogue+0x14/0x48 lib/ubsan.c:233
__ubsan_handle_out_of_bounds+0xd0/0xf8 lib/ubsan.c:455
decode_tail kernel/locking/qspinlock.h:68 [inline]
queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
---[ end trace ]---
Unable to handle kernel paging request at virtual address ffff800088b48710
KASAN: probably user-memory-access in range [0x0000000445a43880-0x0000000445a43887]
Mem abort info:
ESR = 0x0000000096000047
EC = 0x25: DABT (current EL), IL = 32 bits
SET = 0, FnV = 0
EA = 0, S1PTW = 0
FSC = 0x07: level 3 translation fault
Data abort info:
ISV = 0, ISS = 0x00000047, ISS2 = 0x00000000
CM = 0, WnR = 1, TnD = 0, TagAccess = 0
GCS = 0, Overlay = 0, DirtyBit = 0
swapper pgtable: 4k pages, 48-bit VAs, pgdp=000000021aeb5000
[ffff800088b48710] pgd=0000000000000000, p4d=10000002211ac003, pud=10000002211ad003, pmd=10000002211b1003, pte=0000000000000000
Internal error: Oops: 0000000096000047 [#1] SMP
Modules linked in:
CPU: 1 UID: 0 PID: 5334 Comm: syz.0.18 Tainted: G B syzkaller #1 PREEMPT
Tainted: [B]=BAD_PAGE
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/02/2026
pstate: 834000c5 (Nzcv daIF +PAN -UAO +TCO +DIT -SSBS BTYPE=--)
pc : queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:288
lr : decode_tail kernel/locking/qspinlock.h:68 [inline]
lr : queued_spin_lock_slowpath+0x834/0xd04 kernel/locking/qspinlock.c:285
sp : ffff800097c37560
x29: ffff800097c37600 x28: ffff800088b48710 x27: 1fffe00019980afa
x26: 1fffe0001b7c2c00 x25: ffff0001add9f708 x24: dfff800000000000
x23: ffff700012f86eb0 x22: ffff0001add9f700 x21: 1fffe00035bb3ee0
x20: ffff0000ccc057d0 x19: ffff0000dbe16000 x18: 0000000000000000
x17: 3d3d3d3d3d3d3d3d x16: 0000000000000001 x15: 0000000000000000
x14: 0000000000000000 x13: 0000000000000001 x12: 0000000000000004
x11: ffff700011474c6c x10: ffff800088b48700 x9 : ffff800088b48710
x8 : 0000000000000000 x7 : 0000000000000001 x6 : ffff80008048d694
x5 : 0000000000000000 x4 : 0000000000000000 x3 : ffff8000802f6c98
x2 : 0000000000000002 x1 : 0000000000000004 x0 : ffff0001add9f708
Call trace:
queued_spin_lock_slowpath+0x544/0xd04 kernel/locking/qspinlock.c:291 (P)
queued_spin_lock include/asm-generic/qspinlock.h:114 [inline]
do_raw_spin_lock+0x21c/0x2d0 kernel/locking/spinlock_debug.c:116
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:143 [inline]
_raw_spin_lock_irq+0x60/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
do_open fs/namei.c:4700 [inline]
path_openat+0x21fc/0x2a60 fs/namei.c:4863
do_file_open+0x1c8/0x2e8 fs/namei.c:4892
do_sys_openat2+0x114/0x1e8 fs/open.c:1368
do_sys_open+0xb0/0xe0 fs/open.c:1374
__do_sys_openat fs/open.c:1390 [inline]
__se_sys_openat fs/open.c:1385 [inline]
__arm64_sys_openat+0xa0/0xbc fs/open.c:1385
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Code: aa1c03e0 968a785a 910022c0 52800081 (f9000396)
---[ end trace 0000000000000000 ]---
----------------
Code disassembly (best guess):
0: aa1c03e0 mov x0, x28
4: 968a785a bl 0xfffffffffa29e16c
8: 910022c0 add x0, x22, #0x8
c: 52800081 mov w1, #0x4 // #4
* 10: f9000396 str x22, [x28] <-- trapping instruction
The explanation of the root cause of the bug is:
The root cause of this KASAN slab-use-after-free is a reference counting bug in the error path of `gadgetfs_bind()` in `drivers/usb/gadget/legacy/inode.c`.
When the gadget driver is being bound, `gadgetfs_bind()` performs several initialization steps. If it succeeds, it takes a reference to the `dev` object by calling `get_dev(dev)` at the very end of the function. This reference is meant to be balanced by a call to `put_dev(dev)` inside `gadgetfs_unbind()` when the driver is eventually unbound.
However, if `gadgetfs_bind()` fails midway (e.g., due to the fault injection causing `activate_ep_files()` to fail), it jumps to the `enomem` label and calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**.
### Detailed Trace
1. **Initialization**: When the gadgetfs is mounted, `gadgetfs_fill_super()` calls `dev_new()`, which initializes the `dev` object with a refcount of `1`.
2. **First Open**: The reproducer opens the `ep0` file (`dummy_udc`). This calls `gadget_dev_open()`, which increments the refcount to `2` via `get_dev(dev)`.
3. **Configuration**: The reproducer writes to the `ep0` file descriptor, triggering `dev_config()`. This parses the descriptors and calls `usb_gadget_register_driver()`, which in turn calls `gadgetfs_bind()`.
4. **Fault Injection**: Inside `gadgetfs_bind()`, `activate_ep_files()` fails due to the injected memory allocation failure.
5. **The Bug**: `gadgetfs_bind()` jumps to the `enomem` label and calls `gadgetfs_unbind()`. `gadgetfs_unbind()` calls `put_dev(dev)`, dropping the refcount to `1`. (It should have remained `2` because `gadgetfs_bind()` never took its reference).
6. **File Close**: The `write()` syscall returns `-ENOMEM`. The reproducer process exits (or closes the file descriptor), triggering `dev_release()`. This calls `put_dev(dev)`, dropping the refcount to `0`. The `dev` object is freed.
7. **Use-After-Free**: The reproducer (or another thread) opens the `ep0` file again. `gadget_dev_open()` is called, which accesses the freed `dev` object via `inode->i_private` to acquire `dev->lock`, resulting in the KASAN slab-use-after-free crash.
### The Fix
Instead of calling `gadgetfs_unbind()` on failure, `gadgetfs_bind()` should manually undo the specific initialization steps it performed before the failure.
Note that `activate_ep_files()` already cleans up after itself if it fails (by calling `destroy_ep_files()`), so we only need to free `dev->req` (if it was allocated) and clear the gadget data pointers.
```c
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,12 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request (gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data (gadget, NULL);
return -ENOMEM;
}
```
By doing this manual cleanup, we avoid the unbalanced `put_dev(dev)`, prevent `dev->state` from being incorrectly set to `STATE_DEV_UNBOUND` (which would prevent the user from retrying the configuration write), and avoid redundant calls to `destroy_ep_files()`.
The diff of the bug fix is:
diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index d87a8ab51..365f9ab4d 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1700,7 +1700,13 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
return 0;
enomem:
- gadgetfs_unbind (gadget);
+ if (dev->req) {
+ usb_ep_free_request(gadget->ep0, dev->req);
+ dev->req = NULL;
+ }
+ gadget->ep0->driver_data = NULL;
+ dev->gadget = NULL;
+ set_gadget_data(gadget, NULL);
return -ENOMEM;
}
Additional description of the patch:
I have applied the fix to `drivers/usb/gadget/legacy/inode.c`.
### Explanation of the Fix
The root cause of the KASAN slab-use-after-free is an unbalanced reference count in the error path of `gadgetfs_bind()`.
When `gadgetfs_bind()` is called, it performs several initialization steps. If it succeeds, it takes a reference to the `dev` object by calling `get_dev(dev)` at the very end of the function. This reference is meant to be balanced by a call to `put_dev(dev)` inside `gadgetfs_unbind()` when the driver is eventually unbound.
However, if `gadgetfs_bind()` fails midway (e.g., due to a memory allocation failure in `usb_ep_alloc_request()` or `activate_ep_files()`), it jumps to the `enomem` label and calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, `gadgetfs_unbind()` drops a reference that was **never acquired**. This leads to the `dev` object being freed prematurely when the file descriptor is closed, resulting in a Use-After-Free when the file is opened again.
Furthermore, calling `gadgetfs_unbind()` on a partially initialized object is an anti-pattern. `gadgetfs_unbind()` sets `dev->state = STATE_DEV_UNBOUND`, which is incorrect because the device was never fully bound. This incorrect state prevents the user from retrying the configuration write.
To fix this, I replaced the monolithic `gadgetfs_unbind()` call in the `enomem` error path with manual, step-by-step cleanup of exactly the resources that were allocated prior to the failure:
1. If `dev->req` was allocated, it is freed and set to `NULL`.
2. The gadget data pointers (`gadget->ep0->driver_data`, `dev->gadget`, and `set_gadget_data`) are cleared.
Note that `activate_ep_files()` already cleans up after itself if it fails (by calling `destroy_ep_files()`), so we don't need to manually undo its effects in `gadgetfs_bind()`.
This manual cleanup perfectly aligns with established kernel idioms for error path handling. It ensures that only the resources actually allocated by `gadgetfs_bind()` are cleaned up, preventing the unbalanced `put_dev()` and incorrect state changes that caused the Use-After-Free.
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.
Convert 'alloc_obj' family to use the new default GFP_KERNEL argument
treewide: Replace kmalloc with kmalloc_obj for non-scalar types
convert gadgetfs
gadgetfs: switch to simple_remove_by_name()
fs: rename generic_delete_inode() and generic_drop_inode()
functionfs, gadgetfs: use simple_recursive_removal()
USB: gadget: Replace deprecated strncpy() with strscpy()
USB: gadget: Use str_enable_disable-like helpers
[tree-wide] finally take no_llseek out
legacy: convert to new timestamp accessors
usb: gadgetfs: return USB_GADGET_DELAYED_STATUS from setup()
usb: convert to ctime accessor functions
usb: gadgetfs: Fix ep_read_iter to handle ITER_UBUF
USB: gadgetfs: Fix race between mounting and unmounting
gadgetfs: ep_io - wait until IRQ finishes
USB: gadget: Rename usb_gadget_probe_driver()
usb: gadget: eliminate anonymous module_init & module_exit
headers/prep: usb: gadget: Fix namespace collision
usb: gadget: clear related members when goto fail
usb: gadget: don't release an existing dev->buf
Reply: usb: gadgetfs: fix unbalanced refcount in gadgetfs_bind() error path
A KASAN slab-use-after-free can occur in gadget_dev_open() due to an
unbalanced reference count in the error path of gadgetfs_bind().
When gadgetfs_bind() is called, it performs several initialization steps.
If it succeeds, it takes a reference to the dev object by calling
get_dev(dev) at the very end of the function. This reference is meant to be
balanced by a call to put_dev(dev) inside gadgetfs_unbind() when the driver
is eventually unbound.
However, if gadgetfs_bind() fails midway (e.g., due to a memory allocation
failure in usb_ep_alloc_request() or activate_ep_files()), it jumps to the
enomem label and calls gadgetfs_unbind(gadget). Because get_dev(dev) was
never called, gadgetfs_unbind() drops a reference that was never acquired.
This leads to the dev object being freed prematurely when the file
descriptor is closed, resulting in a use-after-free when the file is opened
again.
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq
include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70
kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.18/5334
...
Call trace:
...
__raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
_raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
spin_lock_irq include/linux/spinlock.h:372 [inline]
gadget_dev_open+0x50/0x1c4 drivers/usb/gadget/legacy/inode.c:1919
do_dentry_open+0x5c4/0xfc0 fs/open.c:947
vfs_open+0x44/0x2dc fs/open.c:1052
To fix this, replace the monolithic gadgetfs_unbind() call in the enomem
error path with manual, step-by-step cleanup of exactly the resources that
were allocated prior to the failure. If dev->req was allocated, it is freed
and set to NULL. The gadget data pointers (gadget->ep0->driver_data,
dev->gadget, and set_gadget_data) are cleared. Note that
activate_ep_files() already cleans up after itself if it fails, so we don't
need to manually undo its effects.
This ensures that only the resources actually allocated by gadgetfs_bind()
are cleaned up, preventing the unbalanced put_dev() and incorrect state
changes that caused the use-after-free.
|
| 365/2 |
2026/07/31 07:55 |
llm |
description-generator |
0m
Model:
Tokens:
input: 12440
output: 693
thoughts: 2020
Thoughts: **Commit Summary: A Fix for a GadgetFS Reference Counting Issue**
Okay, so I've got a KASAN slab-use-after-free bug in `drivers/usb/gadget/legacy/inode.c`, specifically in `gadget_dev_open()`. It's related to an unbalanced reference count within the error path of `gadgetfs_bind()`. I need a commit message that's clear, concise, and follows the existing style.
First, I need to come up with a good commit subject line. I'm going to shoot for <= 72 characters, matching the `usb: gadgetfs: ` prefix used in recent commits. Let's see... looking at the recent commits, it's either "usb: gadgetfs: fix unbalanced refcount in gadgetfs_bind() error path" or "usb: gadgetfs: fix use-after-free in gadgetfs_bind() error path". Let me check their lengths. Okay, the first one is 68 chars. So, "usb: gadgetfs: fix unbalanced refcount in gadgetfs_bind() error path" seems like a winner.
Now, for the description. The crux of the issue is that when `gadgetfs_bind()` is called, and it does a bunch of setup, it *only* calls `get_dev(dev)` at the very end on success. That reference should be balanced by a `put_dev(dev)` called in `gadgetfs_unbind()` when the driver unbinds.
The problem arises when `gadgetfs_bind()` fails mid-execution (like, say, an allocation failing in `usb_ep_alloc_request()` or `activate_ep_files()`). If it hits that `enomem` label, it calls `gadgetfs_unbind(gadget)`. Because `get_dev(dev)` was never called, that `gadgetfs_unbind()` call drops a reference it never acquired! This causes the `dev` object to be freed prematurely, which leads to a use-after-free the next time the relevant file is accessed in `gadget_dev_open()`. I've got a KASAN report snippet, which I'll include.
The fix is pretty straightforward: instead of calling the heavy-handed `gadgetfs_unbind()` in the error path, I'll replace it with a manual cleanup of the allocated resources, step-by-step. Specifically, I'll free `dev->req` (if it was allocated) and clear relevant gadget data pointers (`gadget->ep0->driver_data`, `dev->gadget`, and `set_gadget_data`). Fortunately, `activate_ep_files()` already handles cleanup if it fails, so no need to undo its effect. The goal is to make sure we're only cleaning up what was actually allocated *before* the error happened. This stops the unbalanced `put_dev()` and avoids the incorrect state change and the use-after-free. The manual cleanup prevents the unbalanced `put_dev()` call.
Here's the final description:
```
usb: gadgetfs: fix unbalanced refcount in gadgetfs_bind() error path
A KASAN slab-use-after-free can occur in gadget_dev_open() due to an unbalanced reference count in the error path of gadgetfs_bind().
When gadgetfs_bind() is called, it performs several initialization steps. If it succeeds, it takes a reference to the dev object by calling get_dev(dev) at the very end of the function. This reference is meant to be balanced by a call to put_dev(dev) inside gadgetfs_unbind() when the driver is eventually unbound.
However, if gadgetfs_bind() fails midway (e.g., due to a memory allocation failure in usb_ep_alloc_request() or activate_ep_files()), it jumps to the enomem label and calls gadgetfs_unbind(gadget). Because get_dev(dev) was never called, gadgetfs_unbind() drops a reference that was never acquired. This leads to the dev object being freed prematurely when the file descriptor is closed, resulting in a use-after-free when the file is opened again.
BUG: KASAN: slab-use-after-free in __raw_spin_lock_irq include/linux/spinlock_api_smp.h:142 [inline]
BUG: KASAN: slab-use-after-free in _raw_spin_lock_irq+0x58/0x70 kernel/locking/spinlock.c:174
Read of size 1 at addr ffff0000dbe16018 by task syz.0.1
|