| 0/0 |
2026/02/06 10:28 |
flow |
moderation |
12m
Results: map[Actionable:true Confident:true Explanation:The bug report describes a use-after-free (UAF) in `v4l2_ioctl` within the `hackrf` driver. The report is self-consistent and actionable.
### Analysis:
1. **Access Stack Trace**: The UAF occurs in `v4l2_ioctl` at `drivers/media/v4l2-core/v4l2-dev.c:364` (or nearby, depending on the exact kernel version). The access is a read of size 8 at an offset of 200 bytes into the `hackrf_dev` structure.
* `struct hackrf_dev` embeds two `struct video_device` objects: `rx_vdev` (at offset 32 bytes) and `tx_vdev` (at offset 1640 bytes).
* `struct video_device` has a `fops` pointer at offset 168 bytes.
* An access at offset 200 bytes into `hackrf_dev` corresponds exactly to `rx_vdev.fops` ($32 + 168 = 200$).
* The `v4l2_ioctl` function attempts to access `vdev->fops->unlocked_ioctl`. If the `hackrf_dev` structure has been freed, this results in a UAF.
2. **Allocation Stack Trace**: The `hackrf_dev` object was allocated in `hackrf_probe` at `drivers/media/usb/hackrf/hackrf.c:1351` using `kzalloc`.
3. **Free Stack Trace**: The object was freed in the error path of the same `hackrf_probe` function at `drivers/media/usb/hackrf/hackrf.c:1523` using `kfree`.
### Root Cause:
The `hackrf_probe` function registers the receiver video device (`rx_vdev`) first. Once `video_register_device` is called, the device becomes visible to userspace. A utility like `v4l_id` (triggered by udev) can immediately open the device and issue ioctls.
If the subsequent registration of the transmitter video device (`tx_vdev`) fails, `hackrf_probe` enters its error cleanup path. This path calls `video_unregister_device(&dev->rx_vdev)` and then immediately calls `kfree(dev)`.
However, `video_unregister_device` does not guarantee that all references to the device are gone; it only prevents new opens. If userspace (like `v4l_id`) already has the device open, the `video_device` (and the `hackrf_dev` it is embedded in) must remain valid until the last user closes it. By calling `kfree(dev)` directly in the probe error path instead of relying on proper refcounting (e.g., via `v4l2_device_put`), the driver creates a UAF condition for any concurrent userspace access.
### Conclusion:
The report provides all three necessary stack traces, which are perfectly consistent with each other and the kernel source code. The bug is a classic refcounting error in a driver's probe failure path.
Final Verdict: Actionable and Confident.]
|
| 1/1 |
2026/02/06 10:28 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/usr/local/google/home/dvyukov/syzkaller/agent/workdir/cache/src/e86f33132f2d4408f7b5cd396ee07c374e4851f1]
|
| 2/1 |
2026/02/06 10:29 |
action |
kernel-builder |
6m
Results: map[KernelObj:/usr/local/google/home/dvyukov/syzkaller/agent/workdir/cache/build/bbcf4448c6d7036834ef788ba897d44c29a3c34a]
|
| 3/1 |
2026/02/06 10:35 |
action |
codesearch-prepare |
3m
Results: map[Index:codesearch-index]
|
| 4/1 |
2026/02/06 10:39 |
agent |
expert |
1m
Model:
Results: map[Actionable:true Confident:true]
Instruction:
You are an experienced Linux kernel developer tasked with determining if the given kernel bug
report is actionable or not. Actionable means that it contains enough info to root cause
the underlying bug, and that the report is self-consistent and makes sense, rather than
e.g. a one-off nonsensical crash induced by a previous memory corruption.
The bug report is about a use-after-free bug generated by KASAN tool.
It should contain 3 stack traces: the bad memory access stack, the heap block allocation stack,
and the heap block free stack. If the report does not contain 3 stacks, it's not actionable.
All 3 stack traces should be related to the same object type,
and usually be in the same kernel subsystem (at least leaf stack frames).
An example of an actionable and consistent report would be: first access stack relates
to an access to a field of struct Foo, allocation/free stacks relate to allocation/free
of the struct Foo.
In inconsistent/nonsensical reports an access may be to a struct Foo, but allocation
stack allocates a different structure in a different subsystem.
Look for other suspicious signals/inconsistencies that can make this report hard to
debug/understand.
In the final reply explain why you think the report is self-consistent and actionable,
or why it's inconsistent and/or not actionable.
Use the provided tools to confirm any assumptions, variables/fields being accessed, etc.
In particular, don't make assumptions about the kernel source code,
use codesearch tools to read the actual source code.
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 bug report is:
==================================================================
BUG: KASAN: slab-use-after-free in v4l2_ioctl+0xc7/0x1e0 drivers/media/v4l2-core/v4l2-dev.c:364
Read of size 8 at addr ffff888053a040c8 by task v4l_id/32375
CPU: 0 UID: 0 PID: 32375 Comm: v4l_id Tainted: G L syzkaller #0 PREEMPT(full)
Tainted: [L]=SOFTLOCKUP
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/25/2025
Call Trace:
<TASK>
dump_stack_lvl+0xe8/0x150 lib/dump_stack.c:120
print_address_description mm/kasan/report.c:378 [inline]
print_report+0xca/0x240 mm/kasan/report.c:482
kasan_report+0x118/0x150 mm/kasan/report.c:595
v4l2_ioctl+0xc7/0x1e0 drivers/media/v4l2-core/v4l2-dev.c:364
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0xec/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7fb4d171d378
Code: 00 00 48 8d 44 24 08 48 89 54 24 e0 48 89 44 24 c0 48 8d 44 24 d0 48 89 44 24 c8 b8 10 00 00 00 c7 44 24 b8 10 00 00 00 0f 05 <89> c2 3d 00 f0 ff ff 77 07 89 d0 c3 0f 1f 40 00 48 8b 15 49 3a 0d
RSP: 002b:00007ffed13f1b38 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
RAX: ffffffffffffffda RBX: 0000000000000003 RCX: 00007fb4d171d378
RDX: 00007ffed13f1b40 RSI: 0000000080685600 RDI: 0000000000000003
RBP: 0000000000000002 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007ffed13f1cf0 R14: 00007fb4d1e94000 R15: 0000562e312264d8
</TASK>
Allocated by task 5913:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x3e/0x80 mm/kasan/common.c:78
poison_kmalloc_redzone mm/kasan/common.c:398 [inline]
__kasan_kmalloc+0x93/0xb0 mm/kasan/common.c:415
kasan_kmalloc include/linux/kasan.h:263 [inline]
__kmalloc_cache_noprof+0x3e2/0x700 mm/slub.c:5776
kmalloc_noprof include/linux/slab.h:957 [inline]
kzalloc_noprof include/linux/slab.h:1094 [inline]
hackrf_probe+0xda/0x1390 drivers/media/usb/hackrf/hackrf.c:1351
usb_probe_interface+0x668/0xc90 drivers/usb/core/driver.c:396
call_driver_probe drivers/base/dd.c:-1 [inline]
really_probe+0x26d/0xad0 drivers/base/dd.c:659
__driver_probe_device+0x18c/0x320 drivers/base/dd.c:801
driver_probe_device+0x4f/0x240 drivers/base/dd.c:831
__device_attach_driver+0x279/0x430 drivers/base/dd.c:959
bus_for_each_drv+0x251/0x2e0 drivers/base/bus.c:500
__device_attach+0x2b8/0x430 drivers/base/dd.c:1031
device_initial_probe+0xa1/0xd0 drivers/base/dd.c:1086
bus_probe_device+0x12a/0x220 drivers/base/bus.c:574
device_add+0x7b6/0xb80 drivers/base/core.c:3689
usb_set_configuration+0x1a87/0x2110 drivers/usb/core/message.c:2210
usb_generic_driver_probe+0x8d/0x150 drivers/usb/core/generic.c:250
usb_probe_device+0x1c4/0x3c0 drivers/usb/core/driver.c:291
call_driver_probe drivers/base/dd.c:-1 [inline]
really_probe+0x26d/0xad0 drivers/base/dd.c:659
__driver_probe_device+0x18c/0x320 drivers/base/dd.c:801
driver_probe_device+0x4f/0x240 drivers/base/dd.c:831
__device_attach_driver+0x279/0x430 drivers/base/dd.c:959
bus_for_each_drv+0x251/0x2e0 drivers/base/bus.c:500
__device_attach+0x2b8/0x430 drivers/base/dd.c:1031
device_initial_probe+0xa1/0xd0 drivers/base/dd.c:1086
bus_probe_device+0x12a/0x220 drivers/base/bus.c:574
device_add+0x7b6/0xb80 drivers/base/core.c:3689
usb_new_device+0xa39/0x1720 drivers/usb/core/hub.c:2695
hub_port_connect drivers/usb/core/hub.c:5567 [inline]
hub_port_connect_change drivers/usb/core/hub.c:5707 [inline]
port_event drivers/usb/core/hub.c:5871 [inline]
hub_event+0x29b1/0x4ef0 drivers/usb/core/hub.c:5953
process_one_work kernel/workqueue.c:3257 [inline]
process_scheduled_works+0xad1/0x1770 kernel/workqueue.c:3340
worker_thread+0x8a0/0xda0 kernel/workqueue.c:3421
kthread+0x711/0x8a0 kernel/kthread.c:463
ret_from_fork+0x510/0xa50 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:246
Freed by task 5913:
kasan_save_stack mm/kasan/common.c:57 [inline]
kasan_save_track+0x3e/0x80 mm/kasan/common.c:78
kasan_save_free_info+0x46/0x50 mm/kasan/generic.c:584
poison_slab_object mm/kasan/common.c:253 [inline]
__kasan_slab_free+0x5c/0x80 mm/kasan/common.c:285
kasan_slab_free include/linux/kasan.h:235 [inline]
slab_free_hook mm/slub.c:2540 [inline]
slab_free mm/slub.c:6670 [inline]
kfree+0x1c0/0x660 mm/slub.c:6878
hackrf_probe+0xd98/0x1390 drivers/media/usb/hackrf/hackrf.c:1523
usb_probe_interface+0x668/0xc90 drivers/usb/core/driver.c:396
call_driver_probe drivers/base/dd.c:-1 [inline]
really_probe+0x26d/0xad0 drivers/base/dd.c:659
__driver_probe_device+0x18c/0x320 drivers/base/dd.c:801
driver_probe_device+0x4f/0x240 drivers/base/dd.c:831
__device_attach_driver+0x279/0x430 drivers/base/dd.c:959
bus_for_each_drv+0x251/0x2e0 drivers/base/bus.c:500
__device_attach+0x2b8/0x430 drivers/base/dd.c:1031
device_initial_probe+0xa1/0xd0 drivers/base/dd.c:1086
bus_probe_device+0x12a/0x220 drivers/base/bus.c:574
device_add+0x7b6/0xb80 drivers/base/core.c:3689
usb_set_configuration+0x1a87/0x2110 drivers/usb/core/message.c:2210
usb_generic_driver_probe+0x8d/0x150 drivers/usb/core/generic.c:250
usb_probe_device+0x1c4/0x3c0 drivers/usb/core/driver.c:291
call_driver_probe drivers/base/dd.c:-1 [inline]
really_probe+0x26d/0xad0 drivers/base/dd.c:659
__driver_probe_device+0x18c/0x320 drivers/base/dd.c:801
driver_probe_device+0x4f/0x240 drivers/base/dd.c:831
__device_attach_driver+0x279/0x430 drivers/base/dd.c:959
bus_for_each_drv+0x251/0x2e0 drivers/base/bus.c:500
__device_attach+0x2b8/0x430 drivers/base/dd.c:1031
device_initial_probe+0xa1/0xd0 drivers/base/dd.c:1086
bus_probe_device+0x12a/0x220 drivers/base/bus.c:574
device_add+0x7b6/0xb80 drivers/base/core.c:3689
usb_new_device+0xa39/0x1720 drivers/usb/core/hub.c:2695
hub_port_connect drivers/usb/core/hub.c:5567 [inline]
hub_port_connect_change drivers/usb/core/hub.c:5707 [inline]
port_event drivers/usb/core/hub.c:5871 [inline]
hub_event+0x29b1/0x4ef0 drivers/usb/core/hub.c:5953
process_one_work kernel/workqueue.c:3257 [inline]
process_scheduled_works+0xad1/0x1770 kernel/workqueue.c:3340
worker_thread+0x8a0/0xda0 kernel/workqueue.c:3421
kthread+0x711/0x8a0 kernel/kthread.c:463
ret_from_fork+0x510/0xa50 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:246
The buggy address belongs to the object at ffff888053a04000
which belongs to the cache kmalloc-8k of size 8192
The buggy address is located 200 bytes inside of
freed 8192-byte region [ffff888053a04000, ffff888053a06000)
The buggy address belongs to the physical page:
page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x53a00
head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
flags: 0xfff00000000040(head|node=0|zone=1|lastcpupid=0x7ff)
page_type: f5(slab)
raw: 00fff00000000040 ffff88813ffa7280 ffffea0001e15000 dead000000000002
raw: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000
head: 00fff00000000040 ffff88813ffa7280 ffffea0001e15000 dead000000000002
head: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000
head: 00fff00000000003 ffffea00014e8001 00000000ffffffff 00000000ffffffff
head: ffffffffffffffff 0000000000000000 00000000ffffffff 0000000000000008
page dumped because: kasan: bad access detected
page_owner tracks the page as allocated
page last allocated via order 3, migratetype Unmovable, gfp_mask 0x528c0(GFP_NOWAIT|__GFP_IO|__GFP_FS|__GFP_NORETRY|__GFP_COMP), pid 8621, tgid 8620 (syz.4.654), ts 255940508668, free_ts 255910733743
set_page_owner include/linux/page_owner.h:32 [inline]
post_alloc_hook+0x234/0x290 mm/page_alloc.c:1857
prep_new_page mm/page_alloc.c:1865 [inline]
get_page_from_freelist+0x24e0/0x2580 mm/page_alloc.c:3915
__alloc_frozen_pages_noprof+0x181/0x370 mm/page_alloc.c:5210
alloc_pages_mpol+0x232/0x4a0 mm/mempolicy.c:2486
alloc_slab_page mm/slub.c:3075 [inline]
allocate_slab+0x86/0x3b0 mm/slub.c:3248
new_slab mm/slub.c:3302 [inline]
___slab_alloc+0xe53/0x1820 mm/slub.c:4656
__slab_alloc+0x65/0x100 mm/slub.c:4779
__slab_alloc_node mm/slub.c:4855 [inline]
slab_alloc_node mm/slub.c:5251 [inline]
__do_kmalloc_node mm/slub.c:5656 [inline]
__kvmalloc_node_noprof+0x6b6/0x920 mm/slub.c:7136
snd_pcm_plugin_alloc+0x19a/0x780 sound/core/oss/pcm_plugin.c:74
snd_pcm_plug_alloc+0x1d7/0x280 sound/core/oss/pcm_plugin.c:121
snd_pcm_oss_change_params_locked+0x2ae2/0x3f70 sound/core/oss/pcm_oss.c:1041
snd_pcm_oss_make_ready_locked+0x7d/0x300 sound/core/oss/pcm_oss.c:1186
snd_pcm_oss_write1 sound/core/oss/pcm_oss.c:1404 [inline]
snd_pcm_oss_write+0x281/0xf20 sound/core/oss/pcm_oss.c:2794
vfs_write+0x27e/0xb30 fs/read_write.c:684
ksys_write+0x145/0x250 fs/read_write.c:738
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0xec/0xf80 arch/x86/entry/syscall_64.c:94
page last free pid 5199 tgid 5199 stack trace:
reset_page_owner include/linux/page_owner.h:25 [inline]
free_pages_prepare mm/page_alloc.c:1406 [inline]
__free_frozen_pages+0xbc8/0xd30 mm/page_alloc.c:2943
__slab_free+0x2ce/0x320 mm/slub.c:6004
qlink_free mm/kasan/quarantine.c:163 [inline]
qlist_free_all+0x97/0x100 mm/kasan/quarantine.c:179
kasan_quarantine_reduce+0x148/0x160 mm/kasan/quarantine.c:286
__kasan_slab_alloc+0x22/0x80 mm/kasan/common.c:350
kasan_slab_alloc include/linux/kasan.h:253 [inline]
slab_post_alloc_hook mm/slub.c:4953 [inline]
slab_alloc_node mm/slub.c:5263 [inline]
kmem_cache_alloc_noprof+0x37d/0x710 mm/slub.c:5270
getname_flags+0xb8/0x540 fs/namei.c:146
getname include/linux/fs.h:2498 [inline]
__do_sys_unlink fs/namei.c:5474 [inline]
__se_sys_unlink fs/namei.c:5472 [inline]
__x64_sys_unlink+0x3a/0x50 fs/namei.c:5472
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0xec/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
Memory state around the buggy address:
ffff888053a03f80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff888053a04000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
>ffff888053a04080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
^
ffff888053a04100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff888053a04180: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
Reply: The bug report describes a use-after-free (UAF) in `v4l2_ioctl` within the `hackrf` driver. The report is self-consistent and actionable.
### Analysis:
1. **Access Stack Trace**: The UAF occurs in `v4l2_ioctl` at `drivers/media/v4l2-core/v4l2-dev.c:364` (or nearby, depending on the exact kernel version). The access is a read of size 8 at an offset of 200 bytes into the `hackrf_dev` structure.
* `struct hackrf_dev` embeds two `struct video_device` objects: `rx_vdev` (at offset 32 bytes) and `tx_vdev` (at offset 1640 bytes).
* `struct video_device` has a `fops` pointer at offset 168 bytes.
* An access at offset 200 bytes into `hackrf_dev` corresponds exactly to `rx_vdev.fops` ($32 + 168 = 200$).
* The `v4l2_ioctl` function attempts to access `vdev->fops->unlocked_ioctl`. If the `hackrf_dev` structure has been freed, this results in a UAF.
2. **Allocation Stack Trace**: The `hackrf_dev` object was allocated in `hackrf_probe` at `drivers/media/usb/hackrf/hackrf.c:1351` using `kzalloc`.
3. **Free Stack Trace**: The object was freed in the error path of the same `hackrf_probe` function at `drivers/media/usb/hackrf/hackrf.c:1523` using `kfree`.
### Root Cause:
The `hackrf_probe` function registers the receiver video device (`rx_vdev`) first. Once `video_register_device` is called, the device becomes visible to userspace. A utility like `v4l_id` (triggered by udev) can immediately open the device and issue ioctls.
If the subsequent registration of the transmitter video device (`tx_vdev`) fails, `hackrf_probe` enters its error cleanup path. This path calls `video_unregister_device(&dev->rx_vdev)` and then immediately calls `kfree(dev)`.
However, `video_unregister_device` does not guarantee that all references to the device are gone; it only prevents new opens. If userspace (like `v4l_id`) already has the device open, the `video_device` (and the `hackrf_dev` it is embedded in) must remain valid until the last user closes it. By calling `kfree(dev)` directly in the probe error path instead of relying on proper refcounting (e.g., via `v4l2_device_put`), the driver creates a UAF condition for any concurrent userspace access.
### Conclusion:
The report provides all three necessary stack traces, which are perfectly consistent with each other and the kernel source code. The bug is a classic refcounting error in a driver's probe failure path.
Final Verdict: Actionable and Confident.
|
| 5/2 |
2026/02/06 10:39 |
llm |
expert |
0m
Model:
Tokens:
input: 8543
output: 89
thoughts: 488
Thoughts: **Analyzing a `slab-use-after-free` in `v4l2_ioctl`**
Okay, so I've got a `slab-use-after-free` issue. Specifically, a read of size 8 at `ffff888053a040c8` within the `v4l2_ioctl` function. The object in question was allocated and subsequently freed, both within `hackrf_probe`.
Let's break down the stack traces to see what's happening.
The access is clearly triggered by `v4l2_ioctl`, at `drivers/media/v4l2-core/v4l2-dev.c:364`, which then traces back through the usual `vfs_ioctl` calls. That's the point of the crash.
The object allocation happens at `drivers/media/usb/hackrf/hackrf.c:1351` within `hackrf_probe`, and the freeing action also happens within `hackrf_probe` but at `drivers/media/usb/hackrf/hackrf.c:1523`.
The fact that the object is allocated and freed within the same `hackrf_probe` function is a key indicator. It usually suggests the probe failed part-way and is attempting to clean up. But the call to `v4l2_ioctl` indicates that the device was somehow registered, meaning either something went wrong *after* registration, or there's a race condition in play, such as a double free.
My next step is clear: I need to scrutinize the code at these specific locations, particularly how the object is handled in the probe function. I'll need to review the code at `drivers/media/v4l2-core/v4l2-dev.c:364` (the crash site), `drivers/media/usb/hackrf/hackrf.c:1351` (allocation), and `drivers/media/usb/hackrf/hackrf.c:1523` (freeing) to understand the order of operations, and possible issues. I expect I'll find the root cause in one of those three places.
|
| 6/2 |
2026/02/06 10:39 |
tool |
codesearch-dir-index |
0m
Args: map[Dir:drivers/media/usb/hackrf/]
Results: map[Files:[hackrf.c] Subdirs:<nil>]
|
| 7/2 |
2026/02/06 10:39 |
tool |
read-file |
0m
Args: map[File:drivers/media/v4l2-core/v4l2-dev.c]
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Video capture interface for Linux version 2
*
* A generic video device interface for the LINUX operating system
* using a set of device structures/vectors for low level operations.
*
* Authors: Alan Cox, <alan@lxorguk.ukuu.org.uk> (version 1)
* Mauro Carvalho Chehab <mchehab@kernel.org> (version 2)
*
* Fixes: 20000516 Claudio Matsuoka <claudio@conectiva.com>
* - Added procfs support
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/debugfs.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kmod.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <media/v4l2-common.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-event.h>
#define VIDEO_NUM_DEVICES 256
#define VIDEO_NAME "video4linux"
#define dprintk(fmt, arg...) do { \
printk(KERN_DEBUG pr_fmt("%s: " fmt), \
__func__, ##arg); \
} while (0)
/*
* sysfs stuff
*/
static ssize_t index_show(struct device *cd,
struct device_attribute *attr, char *buf)
{
struct video_device *vdev = to_video_device(cd);
return sprintf(buf, "%i\n", vdev->index);
}
static DEVICE_ATTR_RO(index);
static ssize_t dev_debug_show(struct device *cd,
struct device_attribute *attr, char *buf)
{
struct video_device *vdev = to_video_device(cd);
return sprintf(buf, "%i\n", vdev->dev_debug);
}
static ssize_t dev_debug_store(struct device *cd, struct device_attribute *attr,
const char *buf, size_t len)
{
struct video_device *vdev = to_video_device(cd);
int res = 0;
u16 value;
res = kstrtou16(buf, 0, &value);
if (res)
return res;
vdev->dev_debug = value;
return len;
}
static DEVICE_ATTR_RW(dev_debug);
static ssize_t name_show(struct device *cd,
struct device_attribute *attr, char *buf)
{
struct video_device *vdev = to_video_device(cd);
return sprintf(buf, "%.*s\n", (int)sizeof(vdev->name), vdev->name);
}
static DEVICE_ATTR_RO(name);
static struct attribute *video_device_attrs[] = {
&dev_attr_name.attr,
&dev_attr_dev_debug.attr,
&dev_attr_index.attr,
NULL,
};
ATTRIBUTE_GROUPS(video_device);
static struct dentry *v4l2_debugfs_root_dir;
/*
* Active devices
*/
static struct video_device *video_devices[VIDEO_NUM_DEVICES];
static DEFINE_MUTEX(videodev_lock);
static DECLARE_BITMAP(devnode_nums[VFL_TYPE_MAX], VIDEO_NUM_DEVICES);
/* Device node utility functions */
/* Note: these utility functions all assume that vfl_type is in the range
[0, VFL_TYPE_MAX-1]. */
#ifdef CONFIG_VIDEO_FIXED_MINOR_RANGES
/* Return the bitmap corresponding to vfl_type. */
static inline unsigned long *devnode_bits(enum vfl_devnode_type vfl_type)
{
/* Any types not assigned to fixed minor ranges must be mapped to
one single bitmap for the purposes of finding a free node number
since all those unassigned types use the same minor range. */
int idx = (vfl_type > VFL_TYPE_RADIO) ? VFL_TYPE_MAX - 1 : vfl_type;
return devnode_nums[idx];
}
#else
/* Return the bitmap corresponding to vfl_type. */
static inline unsigned long *devnode_bits(enum vfl_devnode_type vfl_type)
{
return devnode_nums[vfl_type];
}
#endif
/* Mark device node number vdev->num as used */
static inline void devnode_set(struct video_device *vdev)
{
set_bit(vdev->num, devnode_bits(vdev->vfl_type));
}
/* Mark device node number vdev->num as unused */
static inline void devnode_clear(struct video_device *vdev)
{
clear_bit(vdev->num, devnode_bits(vdev->vfl_type));
}
/* Try to find a free device node number in the range [from, to> */
static inline int devnode_find(struct video_device *vdev, int from, int to)
{
return find_next_zero_bit(devnode_bits(vdev->vfl_type), to, from);
}
struct video_device *video_device_alloc(void)
{
return kzalloc(sizeof(struct video_device), GFP_KERNEL);
}
EXPORT_SYMBOL(video_device_alloc);
void video_device_release(struct video_device *vdev)
{
kfree(vdev);
}
EXPORT_SYMBOL(video_device_release);
void video_device_release_empty(struct video_device *vdev)
{
/* Do nothing */
/* Only valid when the video_device struct is a static. */
}
EXPORT_SYMBOL(video_device_release_empty);
static inline void video_get(struct video_device *vdev)
{
get_device(&vdev->dev);
}
static inline void video_put(struct video_device *vdev)
{
put_device(&vdev->dev);
}
/* Called when the last user of the video device exits. */
static void v4l2_device_release(struct device *cd)
{
struct video_device *vdev = to_video_device(cd);
struct v4l2_device *v4l2_dev = vdev->v4l2_dev;
mutex_lock(&videodev_lock);
if (WARN_ON(video_devices[vdev->minor] != vdev)) {
/* should not happen */
mutex_unlock(&videodev_lock);
return;
}
/* Free up this device for reuse */
video_devices[vdev->minor] = NULL;
/* Delete the cdev on this minor as well */
cdev_del(vdev->cdev);
/* Just in case some driver tries to access this from
the release() callback. */
vdev->cdev = NULL;
/* Mark device node number as free */
devnode_clear(vdev);
mutex_unlock(&videodev_lock);
#if defined(CONFIG_MEDIA_CONTROLLER)
if (v4l2_dev->mdev && vdev->vfl_dir != VFL_DIR_M2M) {
/* Remove interfaces and interface links */
media_devnode_remove(vdev->intf_devnode);
if (vdev->entity.function != MEDIA_ENT_F_UNKNOWN)
media_device_unregister_entity(&vdev->entity);
}
#endif
/* Do not call v4l2_device_put if there is no release callback set.
* Drivers that have no v4l2_device release callback might free the
* v4l2_dev instance in the video_device release callback below, so we
* must perform this check here.
*
* TODO: In the long run all drivers that use v4l2_device should use the
* v4l2_device release callback. This check will then be unnecessary.
*/
if (v4l2_dev->release == NULL)
v4l2_dev = NULL;
/* Release video_device and perform other
cleanups as needed. */
vdev->release(vdev);
/* Decrease v4l2_device refcount */
if (v4l2_dev)
v4l2_device_put(v4l2_dev);
}
static const struct class video_class = {
.name = VIDEO_NAME,
.dev_groups = video_device_groups,
};
struct video_device *video_devdata(struct file *file)
{
return video_devices[iminor(file_inode(file))];
}
EXPORT_SYMBOL(video_devdata);
/* Priority handling */
static inline bool prio_is_valid(enum v4l2_priority prio)
{
return prio == V4L2_PRIORITY_BACKGROUND ||
prio == V4L2_PRIORITY_INTERACTIVE ||
prio == V4L2_PRIORITY_RECORD;
}
void v4l2_prio_init(struct v4l2_prio_state *global)
{
memset(global, 0, sizeof(*global));
}
EXPORT_SYMBOL(v4l2_prio_init);
int v4l2_prio_change(struct v4l2_prio_state *global, enum v4l2_priority *local,
enum v4l2_priority new)
{
if (!prio_is_valid(new))
return -EINVAL;
if (*local == new)
return 0;
atomic_inc(&global->prios[new]);
if (prio_is_valid(*local))
atomic_dec(&global->prios[*local]);
*local = new;
return 0;
}
EXPORT_SYMBOL(v4l2_prio_change);
void v4l2_prio_open(struct v4l2_prio_state *global, enum v4l2_priority *local)
{
v4l2_prio_change(global, local, V4L2_PRIORITY_DEFAULT);
}
EXPORT_SYMBOL(v4l2_prio_open);
void v4l2_prio_close(struct v4l2_prio_state *global, enum v4l2_priority local)
{
if (prio_is_valid(local))
atomic_dec(&global->prios[local]);
}
EXPORT_SYMBOL(v4l2_prio_close);
enum v4l2_priority v4l2_prio_max(struct v4l2_prio_state *global)
{
if (atomic_read(&global->prios[V4L2_PRIORITY_RECORD]) > 0)
return V4L2_PRIORITY_RECORD;
if (atomic_read(&global->prios[V4L2_PRIORITY_INTERACTIVE]) > 0)
return V4L2_PRIORITY_INTERACTIVE;
if (atomic_read(&global->prios[V4L2_PRIORITY_BACKGROUND]) > 0)
return V4L2_PRIORITY_BACKGROUND;
return V4L2_PRIORITY_UNSET;
}
EXPORT_SYMBOL(v4l2_prio_max);
int v4l2_prio_check(struct v4l2_prio_state *global, enum v4l2_priority local)
{
return (local < v4l2_prio_max(global)) ? -EBUSY : 0;
}
EXPORT_SYMBOL(v4l2_prio_check);
static ssize_t v4l2_read(struct file *filp, char __user *buf,
size_t sz, loff_t *off)
{
struct video_device *vdev = video_devdata(filp);
int ret = -ENODEV;
if (!vdev->fops->read)
return -EINVAL;
if (video_is_registered(vdev))
ret = vdev->fops->read(filp, buf, sz, off);
if ((vdev->dev_debug & V4L2_DEV_DEBUG_FOP) &&
(vdev->dev_debug & V4L2_DEV_DEBUG_STREAMING))
dprintk("%s: read: %zd (%d)\n",
video_device_node_name(vdev), sz, ret);
return ret;
}
static ssize_t v4l2_write(struct file *filp, const char __user *buf,
size_t sz, loff_t *off)
{
struct video_device *vdev = video_devdata(filp);
int ret = -ENODEV;
if (!vdev->fops->write)
return -EINVAL;
if (video_is_registered(vdev))
ret = vdev->fops->write(filp, buf, sz, off);
if ((vdev->dev_debug & V4L2_DEV_DEBUG_FOP) &&
(vdev->dev_debug & V4L2_DEV_DEBUG_STREAMING))
dprintk("%s: write: %zd (%d)\n",
video_device_node_name(vdev), sz, ret);
return ret;
}
static __poll_t v4l2_poll(struct file *filp, struct poll_table_struct *poll)
{
struct video_device *vdev = video_devdata(filp);
__poll_t res = EPOLLERR | EPOLLHUP | EPOLLPRI;
if (video_is_registered(vdev)) {
if (!vdev->fops->poll)
res = DEFAULT_POLLMASK;
else
res = vdev->fops->poll(filp, poll);
}
if (vdev->dev_debug & V4L2_DEV_DEBUG_POLL)
dprintk("%s: poll: %08x %08x\n",
video_device_node_name(vdev), res,
poll_requested_events(poll));
return res;
}
static long v4l2_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct video_device *vdev = video_devdata(filp);
int ret = -ENODEV;
if (vdev->fops->unlocked_ioctl) {
if (video_is_registered(vdev))
ret = vdev->fops->unlocked_ioctl(filp, cmd, arg);
} else
ret = -ENOTTY;
return ret;
}
#ifdef CONFIG_MMU
#define v4l2_get_unmapped_area NULL
#else
static unsigned long v4l2_get_unmapped_area(struct file *filp,
unsigned long addr, unsigned long len, unsigned long pgoff,
unsigned long flags)
{
struct video_device *vdev = video_devdata(filp);
int ret;
if (!vdev->fops->get_unmapped_area)
return -ENOSYS;
if (!video_is_registered(vdev))
return -ENODEV;
ret = vdev->fops->get_unmapped_area(filp, addr, len, pgoff, flags);
if (vdev->dev_debug & V4L2_DEV_DEBUG_FOP)
dprintk("%s: get_unmapped_area (%d)\n",
video_device_node_name(vdev), ret);
return ret;
}
#endif
static int v4l2_mmap(struct file *filp, struct vm_area_struct *vm)
{
struct video_device *vdev = video_devdata(filp);
int ret = -ENODEV;
if (!vdev->fops->mmap)
return -ENODEV;
if (video_is_registered(vdev))
ret = vdev->fops->mmap(filp, vm);
if (vdev->dev_debug & V4L2_DEV_DEBUG_FOP)
dprintk("%s: mmap (%d)\n",
video_device_node_name(vdev), ret);
return ret;
}
/* Override for the open function */
static int v4l2_open(struct inode *inode, struct file *filp)
{
struct video_device *vdev;
int ret;
/* Check if the video device is available */
mutex_lock(&videodev_lock);
vdev = video_devdata(filp);
/* return ENODEV if the video device has already been removed. */
if (vdev == NULL || !video_is_registered(vdev)) {
mutex_unlock(&videodev_lock);
return -ENODEV;
}
/* and increase the device refcount */
video_get(vdev);
mutex_unlock(&videodev_lock);
if (!video_is_registered(vdev)) {
ret = -ENODEV;
goto done;
}
ret = vdev->fops->open(filp);
if (ret)
goto done;
/* All drivers must use v4l2_fh. */
if (WARN_ON(!test_bit(V4L2_FL_USES_V4L2_FH, &vdev->flags))) {
vdev->fops->release(filp);
ret = -ENODEV;
}
done:
if (vdev->dev_debug & V4L2_DEV_DEBUG_FOP)
dprintk("%s: open (%d)\n",
video_device_node_name(vdev), ret);
/* decrease the refcount in case of an error */
if (ret)
video_put(vdev);
return ret;
}
/* Override for the release function */
static int v4l2_release(struct inode *inode, struct file *filp)
{
struct video_device *vdev = video_devdata(filp);
int ret;
/*
* We need to serialize the release() with queueing new requests.
* The release() may trigger the cancellation of a streaming
* operation, and that should not be mixed with queueing a new
* request at the same time.
*/
if (v4l2_device_supports_requests(vdev->v4l2_dev)) {
mutex_lock(&vdev->v4l2_dev->mdev->req_queue_mutex);
ret = vdev->fops->release(filp);
mutex_unlock(&vdev->v4l2_dev->mdev->req_queue_mutex);
} else {
ret = vdev->fops->release(filp);
}
if (vdev->dev_debug & V4L2_DEV_DEBUG_FOP)
dprintk("%s: release\n",
video_device_node_name(vdev));
/* decrease the refcount unconditionally since the release()
return value is ignored. */
video_put(vdev);
return ret;
}
static const struct file_operations v4l2_fops = {
.owner = THIS_MODULE,
.read = v4l2_read,
.write = v4l2_write,
.open = v4l2_open,
.get_unmapped_area = v4l2_get_unmapped_area,
.mmap = v4l2_mmap,
.unlocked_ioctl = v4l2_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = v4l2_compat_ioctl32,
#endif
.release = v4l2_release,
.poll = v4l2_poll,
};
/**
* get_index - assign stream index number based on v4l2_dev
* @vdev: video_device to assign index number to, vdev->v4l2_dev should be assigned
*
* Note that when this is called the new device has not yet been registered
* in the video_device array, but it was able to obtain a minor number.
*
* This means that we can always obtain a free stream index number since
* the worst case scenario is that there are VIDEO_NUM_DEVICES - 1 slots in
* use of the video_device array.
*
* Returns a free index number.
*/
static int get_index(struct video_device *vdev)
{
/* This can be static since this function is called with the global
videodev_lock held. */
static DECLARE_BITMAP(used, VIDEO_NUM_DEVICES);
int i;
bitmap_zero(used, VIDEO_NUM_DEVICES);
for (i = 0; i < VIDEO_NUM_DEVICES; i++) {
if (video_devices[i] != NULL &&
video_devices[i]->v4l2_dev == vdev->v4l2_dev) {
__set_bit(video_devices[i]->index, used);
}
}
return find_first_zero_bit(used, VIDEO_NUM_DEVICES);
}
#define SET_VALID_IOCTL(ops, cmd, op) \
do { if ((ops)->op) __set_bit(_IOC_NR(cmd), valid_ioctls); } while (0)
/* This determines which ioctls are actually implemented in the driver.
It's a one-time thing which simplifies video_ioctl2 as it can just do
a bit test.
Note that drivers can override this by setting bits to 1 in
vdev->valid_ioctls. If an ioctl is marked as 1 when this function is
called, then that ioctl will actually be marked as unimplemented.
It does that by first setting up the local valid_ioctls bitmap, and
at the end do a:
vdev->valid_ioctls = valid_ioctls & ~(vdev->valid_ioctls)
*/
static void determine_valid_ioctls(struct video_device *vdev)
{
const u32 vid_caps = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_VIDEO_CAPTURE_MPLANE |
V4L2_CAP_VIDEO_OUTPUT |
V4L2_CAP_VIDEO_OUTPUT_MPLANE |
V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE;
const u32 meta_caps = V4L2_CAP_META_CAPTURE |
V4L2_CAP_META_OUTPUT;
DECLARE_BITMAP(valid_ioctls, BASE_VIDIOC_PRIVATE);
const struct v4l2_ioctl_ops *ops = vdev->ioctl_ops;
bool is_vid = vdev->vfl_type == VFL_TYPE_VIDEO &&
(vdev->device_caps & vid_caps);
bool is_vbi = vdev->vfl_type == VFL_TYPE_VBI;
bool is_radio = vdev->vfl_type == VFL_TYPE_RADIO;
bool is_sdr = vdev->vfl_type == VFL_TYPE_SDR;
bool is_tch = vdev->vfl_type == VFL_TYPE_TOUCH;
bool is_meta = vdev->vfl_type == VFL_TYPE_VIDEO &&
(vdev->device_caps & meta_caps);
bool is_rx = vdev->vfl_dir != VFL_DIR_TX;
bool is_tx = vdev->vfl_dir != VFL_DIR_RX;
bool is_io_mc = vdev->device_caps & V4L2_CAP_IO_MC;
bool has_streaming = vdev->device_caps & V4L2_CAP_STREAMING;
bool is_edid = vdev->device_caps & V4L2_CAP_EDID;
bitmap_zero(valid_ioctls, BASE_VIDIOC_PRIVATE);
/* vfl_type and vfl_dir independent ioctls */
SET_VALID_IOCTL(ops, VIDIOC_QUERYCAP, vidioc_querycap);
__set_bit(_IOC_NR(VIDIOC_G_PRIORITY), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_S_PRIORITY), valid_ioctls);
/* Note: the control handler can also be passed through the filehandle,
and that can't be tested here. If the bit for these control ioctls
is set, then the ioctl is valid. But if it is 0, then it can still
be valid if the filehandle passed the control handler. */
if (vdev->ctrl_handler || ops->vidioc_query_ext_ctrl)
__set_bit(_IOC_NR(VIDIOC_QUERYCTRL), valid_ioctls);
if (vdev->ctrl_handler || ops->vidioc_query_ext_ctrl)
__set_bit(_IOC_NR(VIDIOC_QUERY_EXT_CTRL), valid_ioctls);
if (vdev->ctrl_handler || ops->vidioc_g_ext_ctrls)
__set_bit(_IOC_NR(VIDIOC_G_CTRL), valid_ioctls);
if (vdev->ctrl_handler || ops->vidioc_s_ext_ctrls)
__set_bit(_IOC_NR(VIDIOC_S_CTRL), valid_ioctls);
if (vdev->ctrl_handler || ops->vidioc_g_ext_ctrls)
__set_bit(_IOC_NR(VIDIOC_G_EXT_CTRLS), valid_ioctls);
if (vdev->ctrl_handler || ops->vidioc_s_ext_ctrls)
__set_bit(_IOC_NR(VIDIOC_S_EXT_CTRLS), valid_ioctls);
if (vdev->ctrl_handler || ops->vidioc_try_ext_ctrls)
__set_bit(_IOC_NR(VIDIOC_TRY_EXT_CTRLS), valid_ioctls);
if (vdev->ctrl_handler || ops->vidioc_querymenu)
__set_bit(_IOC_NR(VIDIOC_QUERYMENU), valid_ioctls);
if (!is_tch) {
SET_VALID_IOCTL(ops, VIDIOC_G_FREQUENCY, vidioc_g_frequency);
SET_VALID_IOCTL(ops, VIDIOC_S_FREQUENCY, vidioc_s_frequency);
}
SET_VALID_IOCTL(ops, VIDIOC_LOG_STATUS, vidioc_log_status);
#ifdef CONFIG_VIDEO_ADV_DEBUG
__set_bit(_IOC_NR(VIDIOC_DBG_G_CHIP_INFO), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_DBG_G_REGISTER), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_DBG_S_REGISTER), valid_ioctls);
#endif
/* yes, really vidioc_subscribe_event */
SET_VALID_IOCTL(ops, VIDIOC_DQEVENT, vidioc_subscribe_event);
SET_VALID_IOCTL(ops, VIDIOC_SUBSCRIBE_EVENT, vidioc_subscribe_event);
SET_VALID_IOCTL(ops, VIDIOC_UNSUBSCRIBE_EVENT, vidioc_unsubscribe_event);
if (ops->vidioc_enum_freq_bands || ops->vidioc_g_tuner || ops->vidioc_g_modulator)
__set_bit(_IOC_NR(VIDIOC_ENUM_FREQ_BANDS), valid_ioctls);
if (is_vid) {
/* video specific ioctls */
if ((is_rx && (ops->vidioc_enum_fmt_vid_cap ||
ops->vidioc_enum_fmt_vid_overlay)) ||
(is_tx && ops->vidioc_enum_fmt_vid_out))
__set_bit(_IOC_NR(VIDIOC_ENUM_FMT), valid_ioctls);
if ((is_rx && (ops->vidioc_g_fmt_vid_cap ||
ops->vidioc_g_fmt_vid_cap_mplane ||
ops->vidioc_g_fmt_vid_overlay)) ||
(is_tx && (ops->vidioc_g_fmt_vid_out ||
ops->vidioc_g_fmt_vid_out_mplane ||
ops->vidioc_g_fmt_vid_out_overlay)))
__set_bit(_IOC_NR(VIDIOC_G_FMT), valid_ioctls);
if ((is_rx && (ops->vidioc_s_fmt_vid_cap ||
ops->vidioc_s_fmt_vid_cap_mplane ||
ops->vidioc_s_fmt_vid_overlay)) ||
(is_tx && (ops->vidioc_s_fmt_vid_out ||
ops->vidioc_s_fmt_vid_out_mplane ||
ops->vidioc_s_fmt_vid_out_overlay)))
__set_bit(_IOC_NR(VIDIOC_S_FMT), valid_ioctls);
if ((is_rx && (ops->vidioc_try_fmt_vid_cap ||
ops->vidioc_try_fmt_vid_cap_mplane ||
ops->vidioc_try_fmt_vid_overlay)) ||
(is_tx && (ops->vidioc_try_fmt_vid_out ||
ops->vidioc_try_fmt_vid_out_mplane ||
ops->vidioc_try_fmt_vid_out_overlay)))
__set_bit(_IOC_NR(VIDIOC_TRY_FMT), valid_ioctls);
SET_VALID_IOCTL(ops, VIDIOC_OVERLAY, vidioc_overlay);
SET_VALID_IOCTL(ops, VIDIOC_G_FBUF, vidioc_g_fbuf);
SET_VALID_IOCTL(ops, VIDIOC_S_FBUF, vidioc_s_fbuf);
SET_VALID_IOCTL(ops, VIDIOC_G_JPEGCOMP, vidioc_g_jpegcomp);
SET_VALID_IOCTL(ops, VIDIOC_S_JPEGCOMP, vidioc_s_jpegcomp);
SET_VALID_IOCTL(ops, VIDIOC_G_ENC_INDEX, vidioc_g_enc_index);
SET_VALID_IOCTL(ops, VIDIOC_ENCODER_CMD, vidioc_encoder_cmd);
SET_VALID_IOCTL(ops, VIDIOC_TRY_ENCODER_CMD, vidioc_try_encoder_cmd);
SET_VALID_IOCTL(ops, VIDIOC_DECODER_CMD, vidioc_decoder_cmd);
SET_VALID_IOCTL(ops, VIDIOC_TRY_DECODER_CMD, vidioc_try_decoder_cmd);
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FRAMESIZES, vidioc_enum_framesizes);
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FRAMEINTERVALS, vidioc_enum_frameintervals);
if (ops->vidioc_g_selection &&
!test_bit(_IOC_NR(VIDIOC_G_SELECTION), vdev->valid_ioctls)) {
__set_bit(_IOC_NR(VIDIOC_G_CROP), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_CROPCAP), valid_ioctls);
}
if (ops->vidioc_s_selection &&
!test_bit(_IOC_NR(VIDIOC_S_SELECTION), vdev->valid_ioctls))
__set_bit(_IOC_NR(VIDIOC_S_CROP), valid_ioctls);
SET_VALID_IOCTL(ops, VIDIOC_G_SELECTION, vidioc_g_selection);
SET_VALID_IOCTL(ops, VIDIOC_S_SELECTION, vidioc_s_selection);
}
if (is_meta && is_rx) {
/* metadata capture specific ioctls */
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FMT, vidioc_enum_fmt_meta_cap);
SET_VALID_IOCTL(ops, VIDIOC_G_FMT, vidioc_g_fmt_meta_cap);
SET_VALID_IOCTL(ops, VIDIOC_S_FMT, vidioc_s_fmt_meta_cap);
SET_VALID_IOCTL(ops, VIDIOC_TRY_FMT, vidioc_try_fmt_meta_cap);
} else if (is_meta && is_tx) {
/* metadata output specific ioctls */
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FMT, vidioc_enum_fmt_meta_out);
SET_VALID_IOCTL(ops, VIDIOC_G_FMT, vidioc_g_fmt_meta_out);
SET_VALID_IOCTL(ops, VIDIOC_S_FMT, vidioc_s_fmt_meta_out);
SET_VALID_IOCTL(ops, VIDIOC_TRY_FMT, vidioc_try_fmt_meta_out);
}
if (is_vbi) {
/* vbi specific ioctls */
if ((is_rx && (ops->vidioc_g_fmt_vbi_cap ||
ops->vidioc_g_fmt_sliced_vbi_cap)) ||
(is_tx && (ops->vidioc_g_fmt_vbi_out ||
ops->vidioc_g_fmt_sliced_vbi_out)))
__set_bit(_IOC_NR(VIDIOC_G_FMT), valid_ioctls);
if ((is_rx && (ops->vidioc_s_fmt_vbi_cap ||
ops->vidioc_s_fmt_sliced_vbi_cap)) ||
(is_tx && (ops->vidioc_s_fmt_vbi_out ||
ops->vidioc_s_fmt_sliced_vbi_out)))
__set_bit(_IOC_NR(VIDIOC_S_FMT), valid_ioctls);
if ((is_rx && (ops->vidioc_try_fmt_vbi_cap ||
ops->vidioc_try_fmt_sliced_vbi_cap)) ||
(is_tx && (ops->vidioc_try_fmt_vbi_out ||
ops->vidioc_try_fmt_sliced_vbi_out)))
__set_bit(_IOC_NR(VIDIOC_TRY_FMT), valid_ioctls);
SET_VALID_IOCTL(ops, VIDIOC_G_SLICED_VBI_CAP, vidioc_g_sliced_vbi_cap);
} else if (is_tch) {
/* touch specific ioctls */
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FMT, vidioc_enum_fmt_vid_cap);
SET_VALID_IOCTL(ops, VIDIOC_G_FMT, vidioc_g_fmt_vid_cap);
SET_VALID_IOCTL(ops, VIDIOC_S_FMT, vidioc_s_fmt_vid_cap);
SET_VALID_IOCTL(ops, VIDIOC_TRY_FMT, vidioc_try_fmt_vid_cap);
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FRAMESIZES, vidioc_enum_framesizes);
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FRAMEINTERVALS, vidioc_enum_frameintervals);
SET_VALID_IOCTL(ops, VIDIOC_ENUMINPUT, vidioc_enum_input);
SET_VALID_IOCTL(ops, VIDIOC_G_INPUT, vidioc_g_input);
SET_VALID_IOCTL(ops, VIDIOC_S_INPUT, vidioc_s_input);
SET_VALID_IOCTL(ops, VIDIOC_G_PARM, vidioc_g_parm);
SET_VALID_IOCTL(ops, VIDIOC_S_PARM, vidioc_s_parm);
} else if (is_sdr && is_rx) {
/* SDR receiver specific ioctls */
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FMT, vidioc_enum_fmt_sdr_cap);
SET_VALID_IOCTL(ops, VIDIOC_G_FMT, vidioc_g_fmt_sdr_cap);
SET_VALID_IOCTL(ops, VIDIOC_S_FMT, vidioc_s_fmt_sdr_cap);
SET_VALID_IOCTL(ops, VIDIOC_TRY_FMT, vidioc_try_fmt_sdr_cap);
} else if (is_sdr && is_tx) {
/* SDR transmitter specific ioctls */
SET_VALID_IOCTL(ops, VIDIOC_ENUM_FMT, vidioc_enum_fmt_sdr_out);
SET_VALID_IOCTL(ops, VIDIOC_G_FMT, vidioc_g_fmt_sdr_out);
SET_VALID_IOCTL(ops, VIDIOC_S_FMT, vidioc_s_fmt_sdr_out);
SET_VALID_IOCTL(ops, VIDIOC_TRY_FMT, vidioc_try_fmt_sdr_out);
}
if (has_streaming) {
/* ioctls valid for streaming I/O */
SET_VALID_IOCTL(ops, VIDIOC_REQBUFS, vidioc_reqbufs);
SET_VALID_IOCTL(ops, VIDIOC_QUERYBUF, vidioc_querybuf);
SET_VALID_IOCTL(ops, VIDIOC_QBUF, vidioc_qbuf);
SET_VALID_IOCTL(ops, VIDIOC_EXPBUF, vidioc_expbuf);
SET_VALID_IOCTL(ops, VIDIOC_DQBUF, vidioc_dqbuf);
SET_VALID_IOCTL(ops, VIDIOC_CREATE_BUFS, vidioc_create_bufs);
SET_VALID_IOCTL(ops, VIDIOC_PREPARE_BUF, vidioc_prepare_buf);
SET_VALID_IOCTL(ops, VIDIOC_STREAMON, vidioc_streamon);
SET_VALID_IOCTL(ops, VIDIOC_STREAMOFF, vidioc_streamoff);
/* VIDIOC_CREATE_BUFS support is mandatory to enable VIDIOC_REMOVE_BUFS */
if (ops->vidioc_create_bufs)
SET_VALID_IOCTL(ops, VIDIOC_REMOVE_BUFS, vidioc_remove_bufs);
}
if (is_vid || is_vbi || is_meta) {
/* ioctls valid for video, vbi and metadata */
if (ops->vidioc_s_std)
__set_bit(_IOC_NR(VIDIOC_ENUMSTD), valid_ioctls);
SET_VALID_IOCTL(ops, VIDIOC_S_STD, vidioc_s_std);
SET_VALID_IOCTL(ops, VIDIOC_G_STD, vidioc_g_std);
if (is_rx) {
SET_VALID_IOCTL(ops, VIDIOC_QUERYSTD, vidioc_querystd);
if (is_io_mc) {
__set_bit(_IOC_NR(VIDIOC_ENUMINPUT), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_G_INPUT), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_S_INPUT), valid_ioctls);
} else {
SET_VALID_IOCTL(ops, VIDIOC_ENUMINPUT, vidioc_enum_input);
SET_VALID_IOCTL(ops, VIDIOC_G_INPUT, vidioc_g_input);
SET_VALID_IOCTL(ops, VIDIOC_S_INPUT, vidioc_s_input);
}
SET_VALID_IOCTL(ops, VIDIOC_ENUMAUDIO, vidioc_enumaudio);
SET_VALID_IOCTL(ops, VIDIOC_G_AUDIO, vidioc_g_audio);
SET_VALID_IOCTL(ops, VIDIOC_S_AUDIO, vidioc_s_audio);
SET_VALID_IOCTL(ops, VIDIOC_QUERY_DV_TIMINGS, vidioc_query_dv_timings);
SET_VALID_IOCTL(ops, VIDIOC_S_EDID, vidioc_s_edid);
}
if (is_tx) {
if (is_io_mc) {
__set_bit(_IOC_NR(VIDIOC_ENUMOUTPUT), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_G_OUTPUT), valid_ioctls);
__set_bit(_IOC_NR(VIDIOC_S_OUTPUT), valid_ioctls);
} else {
SET_VALID_IOCTL(ops, VIDIOC_ENUMOUTPUT, vidioc_enum_output);
SET_VALID_IOCTL(ops, VIDIOC_G_OUTPUT, vidioc_g_output);
SET_VALID_IOCTL(ops, VIDIOC_S_OUTPUT, vidioc_s_output);
}
SET_VALID_IOCTL(ops, VIDIOC_ENUMAUDOUT, vidioc_enumaudout);
SET_VALID_IOCTL(ops, VIDIOC_G_AUDOUT, vidioc_g_audout);
SET_VALID_IOCTL(ops, VIDIOC_S_AUDOUT, vidioc_s_audout);
}
if (ops->vidioc_g_parm || ops->vidioc_g_std)
__set_bit(_IOC_NR(VIDIOC_G_PARM), valid_ioctls);
SET_VALID_IOCTL(ops, VIDIOC_S_PARM, vidioc_s_parm);
SET_VALID_IOCTL(ops, VIDIOC_S_DV_TIMINGS, vidioc_s_dv_timings);
SET_VALID_IOCTL(ops, VIDIOC_G_DV_TIMINGS, vidioc_g_dv_timings);
SET_VALID_IOCTL(ops, VIDIOC_ENUM_DV_TIMINGS, vidioc_enum_dv_timings);
SET_VALID_IOCTL(ops, VIDIOC_DV_TIMINGS_CAP, vidioc_dv_timings_cap);
SET_VALID_IOCTL(ops, VIDIOC_G_EDID, vidioc_g_edid);
}
if (is_tx && (is_radio || is_sdr)) {
/* radio transmitter only ioctls */
SET_VALID_IOCTL(ops, VIDIOC_G_MODULATOR, vidioc_g_modulator);
SET_VALID_IOCTL(ops, VIDIOC_S_MODULATOR, vidioc_s_modulator);
}
if (is_rx && !is_tch) {
/* receiver only ioctls */
SET_VALID_IOCTL(ops, VIDIOC_G_TUNER, vidioc_g_tuner);
SET_VALID_IOCTL(ops, VIDIOC_S_TUNER, vidioc_s_tuner);
SET_VALID_IOCTL(ops, VIDIOC_S_HW_FREQ_SEEK, vidioc_s_hw_freq_seek);
}
if (is_edid) {
SET_VALID_IOCTL(ops, VIDIOC_G_EDID, vidioc_g_edid);
if (is_tx) {
SET_VALID_IOCTL(ops, VIDIOC_G_OUTPUT, vidioc_g_output);
SET_VALID_IOCTL(ops, VIDIOC_S_OUTPUT, vidioc_s_output);
SET_VALID_IOCTL(ops, VIDIOC_ENUMOUTPUT, vidioc_enum_output);
}
if (is_rx) {
SET_VALID_IOCTL(ops, VIDIOC_ENUMINPUT, vidioc_enum_input);
SET_VALID_IOCTL(ops, VIDIOC_G_INPUT, vidioc_g_input);
SET_VALID_IOCTL(ops, VIDIOC_S_INPUT, vidioc_s_input);
SET_VALID_IOCTL(ops, VIDIOC_S_EDID, vidioc_s_edid);
}
}
bitmap_andnot(vdev->valid_ioctls, valid_ioctls, vdev->valid_ioctls,
BASE_VIDIOC_PRIVATE);
}
static int video_register_media_controller(struct video_device *vdev)
{
#if defined(CONFIG_MEDIA_CONTROLLER)
u32 intf_type;
int ret;
/* Memory-to-memory devices are more complex and use
* their own function to register its mc entities.
*/
if (!vdev->v4l2_dev->mdev || vdev->vfl_dir == VFL_DIR_M2M)
return 0;
vdev->entity.obj_type = MEDIA_ENTITY_TYPE_VIDEO_DEVICE;
vdev->entity.function = MEDIA_ENT_F_UNKNOWN;
switch (vdev->vfl_type) {
case VFL_TYPE_VIDEO:
intf_type = MEDIA_INTF_T_V4L_VIDEO;
vdev->entity.function = MEDIA_ENT_F_IO_V4L;
break;
case VFL_TYPE_VBI:
intf_type = MEDIA_INTF_T_V4L_VBI;
vdev->entity.function = MEDIA_ENT_F_IO_VBI;
break;
case VFL_TYPE_SDR:
intf_type = MEDIA_INTF_T_V4L_SWRADIO;
vdev->entity.function = MEDIA_ENT_F_IO_SWRADIO;
break;
case VFL_TYPE_TOUCH:
intf_type = MEDIA_INTF_T_V4L_TOUCH;
vdev->entity.function = MEDIA_ENT_F_IO_V4L;
break;
case VFL_TYPE_RADIO:
intf_type = MEDIA_INTF_T_V4L_RADIO;
/*
* Radio doesn't have an entity at the V4L2 side to represent
* radio input or output. Instead, the audio input/output goes
* via either physical wires or ALSA.
*/
break;
case VFL_TYPE_SUBDEV:
intf_type = MEDIA_INTF_T_V4L_SUBDEV;
/* Entity will be created via v4l2_device_register_subdev() */
break;
default:
return 0;
}
if (vdev->entity.function != MEDIA_ENT_F_UNKNOWN) {
vdev->entity.name = vdev->name;
/* Needed just for backward compatibility with legacy MC API */
vdev->entity.info.dev.major = VIDEO_MAJOR;
vdev->entity.info.dev.minor = vdev->minor;
ret = media_device_register_entity(vdev->v4l2_dev->mdev,
&vdev->entity);
if (ret < 0) {
pr_warn("%s: media_device_register_entity failed\n",
__func__);
return ret;
}
}
vdev->intf_devnode = media_devnode_create(vdev->v4l2_dev->mdev,
intf_type,
0, VIDEO_MAJOR,
vdev->minor);
if (!vdev->intf_devnode) {
media_device_unregister_entity(&vdev->entity);
return -ENOMEM;
}
if (vdev->entity.function != MEDIA_ENT_F_UNKNOWN) {
struct media_link *link;
link = media_create_intf_link(&vdev->entity,
&vdev->intf_devnode->intf,
MEDIA_LNK_FL_ENABLED |
MEDIA_LNK_FL_IMMUTABLE);
if (!link) {
media_devnode_remove(vdev->intf_devnode);
media_device_unregister_entity(&vdev->entity);
return -ENOMEM;
}
}
/* FIXME: how to create the other interface links? */
#endif
return 0;
}
int __video_register_device(struct video_device *vdev,
enum vfl_devnode_type type,
int nr, int warn_if_nr_in_use,
struct module *owner)
{
int i = 0;
int ret;
int minor_offset = 0;
int minor_cnt = VIDEO_NUM_DEVICES;
const char *name_base;
/* A minor value of -1 marks this video device as never
having been registered */
vdev->minor = -1;
/* the release callback MUST be present */
if (WARN_ON(!vdev->release))
return -EINVAL;
/* the v4l2_dev pointer MUST be present */
if (WARN_ON(!vdev->v4l2_dev))
return -EINVAL;
/* the device_caps field MUST be set for all but subdevs */
if (WARN_ON(type != VFL_TYPE_SUBDEV && !vdev->device_caps))
return -EINVAL;
/* the open and release file operations are mandatory */
if (WARN_ON(!vdev->fops || !vdev->fops->open || !vdev->fops->release))
return -EINVAL;
/* v4l2_fh support */
spin_lock_init(&vdev->fh_lock);
INIT_LIST_HEAD(&vdev->fh_list);
/* Part 1: check device type */
switch (type) {
case VFL_TYPE_VIDEO:
name_base = "video";
break;
case VFL_TYPE_VBI:
name_base = "vbi";
break;
case VFL_TYPE_RADIO:
name_base = "radio";
break;
case VFL_TYPE_SUBDEV:
name_base = "v4l-subdev";
break;
case VFL_TYPE_SDR:
/* Use device name 'swradio' because 'sdr' was already taken. */
name_base = "swradio";
break;
case VFL_TYPE_TOUCH:
name_base = "v4l-touch";
break;
default:
pr_err("%s called with unknown type: %d\n",
__func__, type);
return -EINVAL;
}
vdev->vfl_type = type;
vdev->cdev = NULL;
if (vdev->dev_parent == NULL)
vdev->dev_parent = vdev->v4l2_dev->dev;
if (vdev->ctrl_handler == NULL)
vdev->ctrl_handler = vdev->v4l2_dev->ctrl_handler;
/* If the prio state pointer is NULL, then use the v4l2_device
prio state. */
if (vdev->prio == NULL)
vdev->prio = &vdev->v4l2_dev->prio;
/* Part 2: find a free minor, device node number and device index. */
#ifdef CONFIG_VIDEO_FIXED_MINOR_RANGES
/* Keep the ranges for the first four types for historical
* reasons.
* Newer devices (not yet in place) should use the range
* of 128-191 and just pick the first free minor there
* (new style). */
switch (type) {
case VFL_TYPE_VIDEO:
minor_offset = 0;
minor_cnt = 64;
break;
case VFL_TYPE_RADIO:
minor_offset = 64;
minor_cnt = 64;
break;
case VFL_TYPE_VBI:
minor_offset = 224;
minor_cnt = 32;
break;
default:
minor_offset = 128;
minor_cnt = 64;
break;
}
#endif
/* Pick a device node number */
mutex_lock(&videodev_lock);
nr = devnode_find(vdev, nr == -1 ? 0 : nr, minor_cnt);
if (nr == minor_cnt)
nr = devnode_find(vdev, 0, minor_cnt);
if (nr == minor_cnt) {
pr_err("could not get a free device node number\n");
mutex_unlock(&videodev_lock);
return -ENFILE;
}
#ifdef CONFIG_VIDEO_FIXED_MINOR_RANGES
/* 1-on-1 mapping of device node number to minor number */
i = nr;
#else
/* The device node number and minor numbers are independent, so
we just find the first free minor number. */
for (i = 0; i < VIDEO_NUM_DEVICES; i++)
if (video_devices[i] == NULL)
break;
if (i == VIDEO_NUM_DEVICES) {
mutex_unlock(&videodev_lock);
pr_err("could not get a free minor\n");
return -ENFILE;
}
#endif
vdev->minor = i + minor_offset;
vdev->num = nr;
/* Should not happen since we thought this minor was free */
if (WARN_ON(video_devices[vdev->minor])) {
mutex_unlock(&videodev_lock);
pr_err("video_device not empty!\n");
return -ENFILE;
}
devnode_set(vdev);
vdev->index = get_index(vdev);
video_devices[vdev->minor] = vdev;
mutex_unlock(&videodev_lock);
if (vdev->ioctl_ops)
determine_valid_ioctls(vdev);
/* Part 3: Initialize the character device */
vdev->cdev = cdev_alloc();
if (vdev->cdev == NULL) {
ret = -ENOMEM;
goto cleanup;
}
vdev->cdev->ops = &v4l2_fops;
vdev->cdev->owner = owner;
ret = cdev_add(vdev->cdev, MKDEV(VIDEO_MAJOR, vdev->minor), 1);
if (ret < 0) {
pr_err("%s: cdev_add failed\n", __func__);
kfree(vdev->cdev);
vdev->cdev = NULL;
goto cleanup;
}
/* Part 4: register the device with sysfs */
vdev->dev.class = &video_class;
vdev->dev.devt = MKDEV(VIDEO_MAJOR, vdev->minor);
vdev->dev.parent = vdev->dev_parent;
vdev->dev.release = v4l2_device_release;
dev_set_name(&vdev->dev, "%s%d", name_base, vdev->num);
/* Increase v4l2_device refcount */
v4l2_device_get(vdev->v4l2_dev);
mutex_lock(&videodev_lock);
ret = device_register(&vdev->dev);
if (ret < 0) {
mutex_unlock(&videodev_lock);
pr_err("%s: device_register failed\n", __func__);
put_device(&vdev->dev);
return ret;
}
if (nr != -1 && nr != vdev->num && warn_if_nr_in_use)
pr_warn("%s: requested %s%d, got %s\n", __func__,
name_base, nr, video_device_node_name(vdev));
/* Part 5: Register the entity. */
ret = video_register_media_controller(vdev);
/* Part 6: Activate this minor. The char device can now be used. */
set_bit(V4L2_FL_REGISTERED, &vdev->flags);
mutex_unlock(&videodev_lock);
return 0;
cleanup:
mutex_lock(&videodev_lock);
if (vdev->cdev)
cdev_del(vdev->cdev);
video_devices[vdev->minor] = NULL;
devnode_clear(vdev);
mutex_unlock(&videodev_lock);
/* Mark this video device as never having been registered. */
vdev->minor = -1;
return ret;
}
EXPORT_SYMBOL(__video_register_device);
/**
* video_unregister_device - unregister a video4linux device
* @vdev: the device to unregister
*
* This unregisters the passed device. Future open calls will
* be met with errors.
*/
void video_unregister_device(struct video_device *vdev)
{
/* Check if vdev was ever registered at all */
if (!vdev || !video_is_registered(vdev))
return;
mutex_lock(&videodev_lock);
/* This must be in a critical section to prevent a race with v4l2_open.
* Once this bit has been cleared video_get may never be called again.
*/
clear_bit(V4L2_FL_REGISTERED, &vdev->flags);
mutex_unlock(&videodev_lock);
v4l2_event_wake_all(vdev);
device_unregister(&vdev->dev);
}
EXPORT_SYMBOL(video_unregister_device);
#ifdef CONFIG_DEBUG_FS
struct dentry *v4l2_debugfs_root(void)
{
if (!v4l2_debugfs_root_dir)
v4l2_debugfs_root_dir = debugfs_create_dir("v4l2", NULL);
return v4l2_debugfs_root_dir;
}
EXPORT_SYMBOL_GPL(v4l2_debugfs_root);
#endif
#if defined(CONFIG_MEDIA_CONTROLLER)
__must_check int video_device_pipeline_start(struct video_device *vdev,
struct media_pipeline *pipe)
{
struct media_entity *entity = &vdev->entity;
if (entity->num_pads != 1)
return -ENODEV;
return media_pipeline_start(&entity->pads[0], pipe);
}
EXPORT_SYMBOL_GPL(video_device_pipeline_start);
__must_check int __video_device_pipeline_start(struct video_device *vdev,
struct media_pipeline *pipe)
{
struct media_entity *entity = &vdev->entity;
if (entity->num_pads != 1)
return -ENODEV;
return __media_pipeline_start(&entity->pads[0], pipe);
}
EXPORT_SYMBOL_GPL(__video_device_pipeline_start);
void video_device_pipeline_stop(struct video_device *vdev)
{
struct media_entity *entity = &vdev->entity;
if (WARN_ON(entity->num_pads != 1))
return;
return media_pipeline_stop(&entity->pads[0]);
}
EXPORT_SYMBOL_GPL(video_device_pipeline_stop);
void __video_device_pipeline_stop(struct video_device *vdev)
{
struct media_entity *entity = &vdev->entity;
if (WARN_ON(entity->num_pads != 1))
return;
return __media_pipeline_stop(&entity->pads[0]);
}
EXPORT_SYMBOL_GPL(__video_device_pipeline_stop);
__must_check int video_device_pipeline_alloc_start(struct video_device *vdev)
{
struct media_entity *entity = &vdev->entity;
if (entity->num_pads != 1)
return -ENODEV;
return media_pipeline_alloc_start(&entity->pads[0]);
}
EXPORT_SYMBOL_GPL(video_device_pipeline_alloc_start);
struct media_pipeline *video_device_pipeline(struct video_device *vdev)
{
struct media_entity *entity = &vdev->entity;
if (WARN_ON(entity->num_pads != 1))
return NULL;
return media_pad_pipeline(&entity->pads[0]);
}
EXPORT_SYMBOL_GPL(video_device_pipeline);
#endif /* CONFIG_MEDIA_CONTROLLER */
/*
* Initialise video for linux
*/
static int __init videodev_init(void)
{
dev_t dev = MKDEV(VIDEO_MAJOR, 0);
int ret;
pr_info("Linux video capture interface: v2.00\n");
ret = register_chrdev_region(dev, VIDEO_NUM_DEVICES, VIDEO_NAME);
if (ret < 0) {
pr_warn("videodev: unable to get major %d\n",
VIDEO_MAJOR);
return ret;
}
ret = class_register(&video_class);
if (ret < 0) {
unregister_chrdev_region(dev, VIDEO_NUM_DEVICES);
pr_warn("video_dev: class_register failed\n");
return -EIO;
}
return 0;
}
static void __exit videodev_exit(void)
{
dev_t dev = MKDEV(VIDEO_MAJOR, 0);
class_unregister(&video_class);
unregister_chrdev_region(dev, VIDEO_NUM_DEVICES);
debugfs_remove_recursive(v4l2_debugfs_root_dir);
v4l2_debugfs_root_dir = NULL;
}
subsys_initcall(videodev_init);
module_exit(videodev_exit)
MODULE_AUTHOR("Alan Cox, Mauro Carvalho Chehab <mchehab@kernel.org>, Bill Dirks, Justin Schoeman, Gerd Knorr");
MODULE_DESCRIPTION("Video4Linux2 core driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(VIDEO_MAJOR);
]
|
| 8/2 |
2026/02/06 10:39 |
tool |
read-file |
0m
Args: map[File:drivers/media/usb/hackrf/hackrf.c]
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0-or-later
/*
* HackRF driver
*
* Copyright (C) 2014 Antti Palosaari <crope@iki.fi>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-event.h>
#include <media/videobuf2-v4l2.h>
#include <media/videobuf2-vmalloc.h>
/*
* Used Avago MGA-81563 RF amplifier could be destroyed pretty easily with too
* strong signal or transmitting to bad antenna.
* Set RF gain control to 'grabbed' state by default for sure.
*/
static bool hackrf_enable_rf_gain_ctrl;
module_param_named(enable_rf_gain_ctrl, hackrf_enable_rf_gain_ctrl, bool, 0644);
MODULE_PARM_DESC(enable_rf_gain_ctrl, "enable RX/TX RF amplifier control (warn: could damage amplifier)");
/* HackRF USB API commands (from HackRF Library) */
enum {
CMD_SET_TRANSCEIVER_MODE = 0x01,
CMD_SAMPLE_RATE_SET = 0x06,
CMD_BASEBAND_FILTER_BANDWIDTH_SET = 0x07,
CMD_BOARD_ID_READ = 0x0e,
CMD_VERSION_STRING_READ = 0x0f,
CMD_SET_FREQ = 0x10,
CMD_AMP_ENABLE = 0x11,
CMD_SET_LNA_GAIN = 0x13,
CMD_SET_VGA_GAIN = 0x14,
CMD_SET_TXVGA_GAIN = 0x15,
};
/*
* bEndpointAddress 0x81 EP 1 IN
* Transfer Type Bulk
* wMaxPacketSize 0x0200 1x 512 bytes
*/
#define MAX_BULK_BUFS (6)
#define BULK_BUFFER_SIZE (128 * 512)
static const struct v4l2_frequency_band bands_adc_dac[] = {
{
.tuner = 0,
.type = V4L2_TUNER_SDR,
.index = 0,
.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
.rangelow = 200000,
.rangehigh = 24000000,
},
};
static const struct v4l2_frequency_band bands_rx_tx[] = {
{
.tuner = 1,
.type = V4L2_TUNER_RF,
.index = 0,
.capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS,
.rangelow = 1,
.rangehigh = 4294967294LL, /* max u32, hw goes over 7GHz */
},
};
/* stream formats */
struct hackrf_format {
u32 pixelformat;
u32 buffersize;
};
/* format descriptions for capture and preview */
static struct hackrf_format formats[] = {
{
.pixelformat = V4L2_SDR_FMT_CS8,
.buffersize = BULK_BUFFER_SIZE,
},
};
static const unsigned int NUM_FORMATS = ARRAY_SIZE(formats);
/* intermediate buffers with raw data from the USB device */
struct hackrf_buffer {
struct vb2_v4l2_buffer vb;
struct list_head list;
};
struct hackrf_dev {
#define USB_STATE_URB_BUF 1 /* XXX: set manually */
#define RX_ON 4
#define TX_ON 5
#define RX_ADC_FREQUENCY 11
#define TX_DAC_FREQUENCY 12
#define RX_BANDWIDTH 13
#define TX_BANDWIDTH 14
#define RX_RF_FREQUENCY 15
#define TX_RF_FREQUENCY 16
#define RX_RF_GAIN 17
#define TX_RF_GAIN 18
#define RX_IF_GAIN 19
#define RX_LNA_GAIN 20
#define TX_LNA_GAIN 21
unsigned long flags;
struct usb_interface *intf;
struct device *dev;
struct usb_device *udev;
struct video_device rx_vdev;
struct video_device tx_vdev;
struct v4l2_device v4l2_dev;
/* videobuf2 queue and queued buffers list */
struct vb2_queue rx_vb2_queue;
struct vb2_queue tx_vb2_queue;
struct list_head rx_buffer_list;
struct list_head tx_buffer_list;
spinlock_t buffer_list_lock; /* Protects buffer_list */
unsigned int sequence; /* Buffer sequence counter */
unsigned int vb_full; /* vb is full and packets dropped */
unsigned int vb_empty; /* vb is empty and packets dropped */
/* Note if taking both locks v4l2_lock must always be locked first! */
struct mutex v4l2_lock; /* Protects everything else */
struct mutex vb_queue_lock; /* Protects vb_queue */
struct urb *urb_list[MAX_BULK_BUFS];
int buf_num;
unsigned long buf_size;
u8 *buf_list[MAX_BULK_BUFS];
dma_addr_t dma_addr[MAX_BULK_BUFS];
int urbs_initialized;
int urbs_submitted;
/* USB control message buffer */
#define BUF_SIZE 24
u8 buf[BUF_SIZE];
/* Current configuration */
unsigned int f_adc;
unsigned int f_dac;
unsigned int f_rx;
unsigned int f_tx;
u32 pixelformat;
u32 buffersize;
/* Controls */
struct v4l2_ctrl_handler rx_ctrl_handler;
struct v4l2_ctrl *rx_bandwidth_auto;
struct v4l2_ctrl *rx_bandwidth;
struct v4l2_ctrl *rx_rf_gain;
struct v4l2_ctrl *rx_lna_gain;
struct v4l2_ctrl *rx_if_gain;
struct v4l2_ctrl_handler tx_ctrl_handler;
struct v4l2_ctrl *tx_bandwidth_auto;
struct v4l2_ctrl *tx_bandwidth;
struct v4l2_ctrl *tx_rf_gain;
struct v4l2_ctrl *tx_lna_gain;
/* Sample rate calc */
unsigned long jiffies_next;
unsigned int sample;
unsigned int sample_measured;
};
#define hackrf_dbg_usb_control_msg(_dev, _r, _t, _v, _i, _b, _l) { \
char *_direction; \
if (_t & USB_DIR_IN) \
_direction = "<<<"; \
else \
_direction = ">>>"; \
dev_dbg(_dev, "%02x %02x %02x %02x %02x %02x %02x %02x %s %*ph\n", \
_t, _r, _v & 0xff, _v >> 8, _i & 0xff, \
_i >> 8, _l & 0xff, _l >> 8, _direction, _l, _b); \
}
/* execute firmware command */
static int hackrf_ctrl_msg(struct hackrf_dev *dev, u8 request, u16 value,
u16 index, u8 *data, u16 size)
{
int ret;
unsigned int pipe;
u8 requesttype;
switch (request) {
case CMD_SET_TRANSCEIVER_MODE:
case CMD_SET_FREQ:
case CMD_AMP_ENABLE:
case CMD_SAMPLE_RATE_SET:
case CMD_BASEBAND_FILTER_BANDWIDTH_SET:
pipe = usb_sndctrlpipe(dev->udev, 0);
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
break;
case CMD_BOARD_ID_READ:
case CMD_VERSION_STRING_READ:
case CMD_SET_LNA_GAIN:
case CMD_SET_VGA_GAIN:
case CMD_SET_TXVGA_GAIN:
pipe = usb_rcvctrlpipe(dev->udev, 0);
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
break;
default:
dev_err(dev->dev, "Unknown command %02x\n", request);
ret = -EINVAL;
goto err;
}
/* write request */
if (!(requesttype & USB_DIR_IN))
memcpy(dev->buf, data, size);
ret = usb_control_msg(dev->udev, pipe, request, requesttype, value,
index, dev->buf, size, 1000);
hackrf_dbg_usb_control_msg(dev->dev, request, requesttype, value,
index, dev->buf, size);
if (ret < 0) {
dev_err(dev->dev, "usb_control_msg() failed %d request %02x\n",
ret, request);
goto err;
}
/* read request */
if (requesttype & USB_DIR_IN)
memcpy(data, dev->buf, size);
return 0;
err:
return ret;
}
static int hackrf_set_params(struct hackrf_dev *dev)
{
struct usb_interface *intf = dev->intf;
int ret, i;
u8 buf[8], u8tmp;
unsigned int uitmp, uitmp1, uitmp2;
const bool rx = test_bit(RX_ON, &dev->flags);
const bool tx = test_bit(TX_ON, &dev->flags);
static const struct {
u32 freq;
} bandwidth_lut[] = {
{ 1750000}, /* 1.75 MHz */
{ 2500000}, /* 2.5 MHz */
{ 3500000}, /* 3.5 MHz */
{ 5000000}, /* 5 MHz */
{ 5500000}, /* 5.5 MHz */
{ 6000000}, /* 6 MHz */
{ 7000000}, /* 7 MHz */
{ 8000000}, /* 8 MHz */
{ 9000000}, /* 9 MHz */
{10000000}, /* 10 MHz */
{12000000}, /* 12 MHz */
{14000000}, /* 14 MHz */
{15000000}, /* 15 MHz */
{20000000}, /* 20 MHz */
{24000000}, /* 24 MHz */
{28000000}, /* 28 MHz */
};
if (!rx && !tx) {
dev_dbg(&intf->dev, "device is sleeping\n");
return 0;
}
/* ADC / DAC frequency */
if (rx && test_and_clear_bit(RX_ADC_FREQUENCY, &dev->flags)) {
dev_dbg(&intf->dev, "RX ADC frequency=%u Hz\n", dev->f_adc);
uitmp1 = dev->f_adc;
uitmp2 = 1;
set_bit(TX_DAC_FREQUENCY, &dev->flags);
} else if (tx && test_and_clear_bit(TX_DAC_FREQUENCY, &dev->flags)) {
dev_dbg(&intf->dev, "TX DAC frequency=%u Hz\n", dev->f_dac);
uitmp1 = dev->f_dac;
uitmp2 = 1;
set_bit(RX_ADC_FREQUENCY, &dev->flags);
} else {
uitmp1 = uitmp2 = 0;
}
if (uitmp1 || uitmp2) {
buf[0] = (uitmp1 >> 0) & 0xff;
buf[1] = (uitmp1 >> 8) & 0xff;
buf[2] = (uitmp1 >> 16) & 0xff;
buf[3] = (uitmp1 >> 24) & 0xff;
buf[4] = (uitmp2 >> 0) & 0xff;
buf[5] = (uitmp2 >> 8) & 0xff;
buf[6] = (uitmp2 >> 16) & 0xff;
buf[7] = (uitmp2 >> 24) & 0xff;
ret = hackrf_ctrl_msg(dev, CMD_SAMPLE_RATE_SET, 0, 0, buf, 8);
if (ret)
goto err;
}
/* bandwidth */
if (rx && test_and_clear_bit(RX_BANDWIDTH, &dev->flags)) {
if (dev->rx_bandwidth_auto->val == true)
uitmp = dev->f_adc;
else
uitmp = dev->rx_bandwidth->val;
for (i = 0; i < ARRAY_SIZE(bandwidth_lut); i++) {
if (uitmp <= bandwidth_lut[i].freq) {
uitmp = bandwidth_lut[i].freq;
break;
}
}
dev->rx_bandwidth->val = uitmp;
dev->rx_bandwidth->cur.val = uitmp;
dev_dbg(&intf->dev, "RX bandwidth selected=%u\n", uitmp);
set_bit(TX_BANDWIDTH, &dev->flags);
} else if (tx && test_and_clear_bit(TX_BANDWIDTH, &dev->flags)) {
if (dev->tx_bandwidth_auto->val == true)
uitmp = dev->f_dac;
else
uitmp = dev->tx_bandwidth->val;
for (i = 0; i < ARRAY_SIZE(bandwidth_lut); i++) {
if (uitmp <= bandwidth_lut[i].freq) {
uitmp = bandwidth_lut[i].freq;
break;
}
}
dev->tx_bandwidth->val = uitmp;
dev->tx_bandwidth->cur.val = uitmp;
dev_dbg(&intf->dev, "TX bandwidth selected=%u\n", uitmp);
set_bit(RX_BANDWIDTH, &dev->flags);
} else {
uitmp = 0;
}
if (uitmp) {
uitmp1 = uitmp2 = 0;
uitmp1 |= ((uitmp >> 0) & 0xff) << 0;
uitmp1 |= ((uitmp >> 8) & 0xff) << 8;
uitmp2 |= ((uitmp >> 16) & 0xff) << 0;
uitmp2 |= ((uitmp >> 24) & 0xff) << 8;
ret = hackrf_ctrl_msg(dev, CMD_BASEBAND_FILTER_BANDWIDTH_SET,
uitmp1, uitmp2, NULL, 0);
if (ret)
goto err;
}
/* RX / TX RF frequency */
if (rx && test_and_clear_bit(RX_RF_FREQUENCY, &dev->flags)) {
dev_dbg(&intf->dev, "RX RF frequency=%u Hz\n", dev->f_rx);
uitmp1 = dev->f_rx / 1000000;
uitmp2 = dev->f_rx % 1000000;
set_bit(TX_RF_FREQUENCY, &dev->flags);
} else if (tx && test_and_clear_bit(TX_RF_FREQUENCY, &dev->flags)) {
dev_dbg(&intf->dev, "TX RF frequency=%u Hz\n", dev->f_tx);
uitmp1 = dev->f_tx / 1000000;
uitmp2 = dev->f_tx % 1000000;
set_bit(RX_RF_FREQUENCY, &dev->flags);
} else {
uitmp1 = uitmp2 = 0;
}
if (uitmp1 || uitmp2) {
buf[0] = (uitmp1 >> 0) & 0xff;
buf[1] = (uitmp1 >> 8) & 0xff;
buf[2] = (uitmp1 >> 16) & 0xff;
buf[3] = (uitmp1 >> 24) & 0xff;
buf[4] = (uitmp2 >> 0) & 0xff;
buf[5] = (uitmp2 >> 8) & 0xff;
buf[6] = (uitmp2 >> 16) & 0xff;
buf[7] = (uitmp2 >> 24) & 0xff;
ret = hackrf_ctrl_msg(dev, CMD_SET_FREQ, 0, 0, buf, 8);
if (ret)
goto err;
}
/* RX RF gain */
if (rx && test_and_clear_bit(RX_RF_GAIN, &dev->flags)) {
dev_dbg(&intf->dev, "RX RF gain val=%d->%d\n",
dev->rx_rf_gain->cur.val, dev->rx_rf_gain->val);
u8tmp = (dev->rx_rf_gain->val) ? 1 : 0;
ret = hackrf_ctrl_msg(dev, CMD_AMP_ENABLE, u8tmp, 0, NULL, 0);
if (ret)
goto err;
set_bit(TX_RF_GAIN, &dev->flags);
}
/* TX RF gain */
if (tx && test_and_clear_bit(TX_RF_GAIN, &dev->flags)) {
dev_dbg(&intf->dev, "TX RF gain val=%d->%d\n",
dev->tx_rf_gain->cur.val, dev->tx_rf_gain->val);
u8tmp = (dev->tx_rf_gain->val) ? 1 : 0;
ret = hackrf_ctrl_msg(dev, CMD_AMP_ENABLE, u8tmp, 0, NULL, 0);
if (ret)
goto err;
set_bit(RX_RF_GAIN, &dev->flags);
}
/* RX LNA gain */
if (rx && test_and_clear_bit(RX_LNA_GAIN, &dev->flags)) {
dev_dbg(dev->dev, "RX LNA gain val=%d->%d\n",
dev->rx_lna_gain->cur.val, dev->rx_lna_gain->val);
ret = hackrf_ctrl_msg(dev, CMD_SET_LNA_GAIN, 0,
dev->rx_lna_gain->val, &u8tmp, 1);
if (ret)
goto err;
}
/* RX IF gain */
if (rx && test_and_clear_bit(RX_IF_GAIN, &dev->flags)) {
dev_dbg(&intf->dev, "IF gain val=%d->%d\n",
dev->rx_if_gain->cur.val, dev->rx_if_gain->val);
ret = hackrf_ctrl_msg(dev, CMD_SET_VGA_GAIN, 0,
dev->rx_if_gain->val, &u8tmp, 1);
if (ret)
goto err;
}
/* TX LNA gain */
if (tx && test_and_clear_bit(TX_LNA_GAIN, &dev->flags)) {
dev_dbg(&intf->dev, "TX LNA gain val=%d->%d\n",
dev->tx_lna_gain->cur.val, dev->tx_lna_gain->val);
ret = hackrf_ctrl_msg(dev, CMD_SET_TXVGA_GAIN, 0,
dev->tx_lna_gain->val, &u8tmp, 1);
if (ret)
goto err;
}
return 0;
err:
dev_dbg(&intf->dev, "failed=%d\n", ret);
return ret;
}
/* Private functions */
static struct hackrf_buffer *hackrf_get_next_buffer(struct hackrf_dev *dev,
struct list_head *buffer_list)
{
unsigned long flags;
struct hackrf_buffer *buffer = NULL;
spin_lock_irqsave(&dev->buffer_list_lock, flags);
if (list_empty(buffer_list))
goto leave;
buffer = list_entry(buffer_list->next, struct hackrf_buffer, list);
list_del(&buffer->list);
leave:
spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
return buffer;
}
static void hackrf_copy_stream(struct hackrf_dev *dev, void *dst, void *src,
unsigned int src_len)
{
memcpy(dst, src, src_len);
/* calculate sample rate and output it in 10 seconds intervals */
if (unlikely(time_is_before_jiffies(dev->jiffies_next))) {
#define MSECS 10000UL
unsigned int msecs = jiffies_to_msecs(jiffies -
dev->jiffies_next + msecs_to_jiffies(MSECS));
unsigned int samples = dev->sample - dev->sample_measured;
dev->jiffies_next = jiffies + msecs_to_jiffies(MSECS);
dev->sample_measured = dev->sample;
dev_dbg(dev->dev, "slen=%u samples=%u msecs=%u sample rate=%lu\n",
src_len, samples, msecs,
samples * 1000UL / msecs);
}
/* total number of samples */
dev->sample += src_len / 2;
}
/*
* This gets called for the bulk stream pipe. This is done in interrupt
* time, so it has to be fast, not crash, and not stall. Neat.
*/
static void hackrf_urb_complete_in(struct urb *urb)
{
struct hackrf_dev *dev = urb->context;
struct usb_interface *intf = dev->intf;
struct hackrf_buffer *buffer;
unsigned int len;
dev_dbg_ratelimited(&intf->dev, "status=%d length=%u/%u\n", urb->status,
urb->actual_length, urb->transfer_buffer_length);
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
return;
default: /* error */
dev_err_ratelimited(&intf->dev, "URB failed %d\n", urb->status);
goto exit_usb_submit_urb;
}
/* get buffer to write */
buffer = hackrf_get_next_buffer(dev, &dev->rx_buffer_list);
if (unlikely(buffer == NULL)) {
dev->vb_full++;
dev_notice_ratelimited(&intf->dev,
"buffer is full - %u packets dropped\n",
dev->vb_full);
goto exit_usb_submit_urb;
}
len = min_t(unsigned long, vb2_plane_size(&buffer->vb.vb2_buf, 0),
urb->actual_length);
hackrf_copy_stream(dev, vb2_plane_vaddr(&buffer->vb.vb2_buf, 0),
urb->transfer_buffer, len);
vb2_set_plane_payload(&buffer->vb.vb2_buf, 0, len);
buffer->vb.sequence = dev->sequence++;
buffer->vb.vb2_buf.timestamp = ktime_get_ns();
vb2_buffer_done(&buffer->vb.vb2_buf, VB2_BUF_STATE_DONE);
exit_usb_submit_urb:
usb_submit_urb(urb, GFP_ATOMIC);
}
static void hackrf_urb_complete_out(struct urb *urb)
{
struct hackrf_dev *dev = urb->context;
struct usb_interface *intf = dev->intf;
struct hackrf_buffer *buffer;
unsigned int len;
dev_dbg_ratelimited(&intf->dev, "status=%d length=%u/%u\n", urb->status,
urb->actual_length, urb->transfer_buffer_length);
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
return;
default: /* error */
dev_err_ratelimited(&intf->dev, "URB failed %d\n", urb->status);
}
/* get buffer to read */
buffer = hackrf_get_next_buffer(dev, &dev->tx_buffer_list);
if (unlikely(buffer == NULL)) {
dev->vb_empty++;
dev_notice_ratelimited(&intf->dev,
"buffer is empty - %u packets dropped\n",
dev->vb_empty);
urb->actual_length = 0;
goto exit_usb_submit_urb;
}
len = min_t(unsigned long, urb->transfer_buffer_length,
vb2_get_plane_payload(&buffer->vb.vb2_buf, 0));
hackrf_copy_stream(dev, urb->transfer_buffer,
vb2_plane_vaddr(&buffer->vb.vb2_buf, 0), len);
urb->actual_length = len;
buffer->vb.sequence = dev->sequence++;
buffer->vb.vb2_buf.timestamp = ktime_get_ns();
vb2_buffer_done(&buffer->vb.vb2_buf, VB2_BUF_STATE_DONE);
exit_usb_submit_urb:
usb_submit_urb(urb, GFP_ATOMIC);
}
static int hackrf_kill_urbs(struct hackrf_dev *dev)
{
int i;
for (i = dev->urbs_submitted - 1; i >= 0; i--) {
dev_dbg(dev->dev, "kill urb=%d\n", i);
/* stop the URB */
usb_kill_urb(dev->urb_list[i]);
}
dev->urbs_submitted = 0;
return 0;
}
static int hackrf_submit_urbs(struct hackrf_dev *dev)
{
int i, ret;
for (i = 0; i < dev->urbs_initialized; i++) {
dev_dbg(dev->dev, "submit urb=%d\n", i);
ret = usb_submit_urb(dev->urb_list[i], GFP_KERNEL);
if (ret) {
dev_err(dev->dev, "Could not submit URB no. %d - get them all back\n",
i);
hackrf_kill_urbs(dev);
return ret;
}
dev->urbs_submitted++;
}
return 0;
}
static int hackrf_free_stream_bufs(struct hackrf_dev *dev)
{
if (dev->flags & USB_STATE_URB_BUF) {
while (dev->buf_num) {
dev->buf_num--;
dev_dbg(dev->dev, "free buf=%d\n", dev->buf_num);
usb_free_coherent(dev->udev, dev->buf_size,
dev->buf_list[dev->buf_num],
dev->dma_addr[dev->buf_num]);
}
}
dev->flags &= ~USB_STATE_URB_BUF;
return 0;
}
static int hackrf_alloc_stream_bufs(struct hackrf_dev *dev)
{
dev->buf_num = 0;
dev->buf_size = BULK_BUFFER_SIZE;
dev_dbg(dev->dev, "all in all I will use %u bytes for streaming\n",
MAX_BULK_BUFS * BULK_BUFFER_SIZE);
for (dev->buf_num = 0; dev->buf_num < MAX_BULK_BUFS; dev->buf_num++) {
dev->buf_list[dev->buf_num] = usb_alloc_coherent(dev->udev,
BULK_BUFFER_SIZE, GFP_KERNEL,
&dev->dma_addr[dev->buf_num]);
if (!dev->buf_list[dev->buf_num]) {
dev_dbg(dev->dev, "alloc buf=%d failed\n",
dev->buf_num);
hackrf_free_stream_bufs(dev);
return -ENOMEM;
}
dev_dbg(dev->dev, "alloc buf=%d %p (dma %llu)\n", dev->buf_num,
dev->buf_list[dev->buf_num],
(long long)dev->dma_addr[dev->buf_num]);
dev->flags |= USB_STATE_URB_BUF;
}
return 0;
}
static int hackrf_free_urbs(struct hackrf_dev *dev)
{
int i;
hackrf_kill_urbs(dev);
for (i = dev->urbs_initialized - 1; i >= 0; i--) {
if (dev->urb_list[i]) {
dev_dbg(dev->dev, "free urb=%d\n", i);
/* free the URBs */
usb_free_urb(dev->urb_list[i]);
}
}
dev->urbs_initialized = 0;
return 0;
}
static int hackrf_alloc_urbs(struct hackrf_dev *dev, bool rcv)
{
int i, j;
unsigned int pipe;
usb_complete_t complete;
if (rcv) {
pipe = usb_rcvbulkpipe(dev->udev, 0x81);
complete = &hackrf_urb_complete_in;
} else {
pipe = usb_sndbulkpipe(dev->udev, 0x02);
complete = &hackrf_urb_complete_out;
}
/* allocate the URBs */
for (i = 0; i < MAX_BULK_BUFS; i++) {
dev_dbg(dev->dev, "alloc urb=%d\n", i);
dev->urb_list[i] = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->urb_list[i]) {
for (j = 0; j < i; j++)
usb_free_urb(dev->urb_list[j]);
return -ENOMEM;
}
usb_fill_bulk_urb(dev->urb_list[i],
dev->udev,
pipe,
dev->buf_list[i],
BULK_BUFFER_SIZE,
complete, dev);
dev->urb_list[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
dev->urb_list[i]->transfer_dma = dev->dma_addr[i];
dev->urbs_initialized++;
}
return 0;
}
/* The user yanked out the cable... */
static void hackrf_disconnect(struct usb_interface *intf)
{
struct v4l2_device *v = usb_get_intfdata(intf);
struct hackrf_dev *dev = container_of(v, struct hackrf_dev, v4l2_dev);
dev_dbg(dev->dev, "\n");
mutex_lock(&dev->vb_queue_lock);
mutex_lock(&dev->v4l2_lock);
/* No need to keep the urbs around after disconnection */
dev->udev = NULL;
v4l2_device_disconnect(&dev->v4l2_dev);
video_unregister_device(&dev->tx_vdev);
video_unregister_device(&dev->rx_vdev);
mutex_unlock(&dev->v4l2_lock);
mutex_unlock(&dev->vb_queue_lock);
v4l2_device_put(&dev->v4l2_dev);
}
/* Videobuf2 operations */
static void hackrf_return_all_buffers(struct vb2_queue *vq,
enum vb2_buffer_state state)
{
struct hackrf_dev *dev = vb2_get_drv_priv(vq);
struct usb_interface *intf = dev->intf;
struct hackrf_buffer *buffer, *node;
struct list_head *buffer_list;
unsigned long flags;
dev_dbg(&intf->dev, "\n");
if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
buffer_list = &dev->rx_buffer_list;
else
buffer_list = &dev->tx_buffer_list;
spin_lock_irqsave(&dev->buffer_list_lock, flags);
list_for_each_entry_safe(buffer, node, buffer_list, list) {
dev_dbg(&intf->dev, "list_for_each_entry_safe\n");
vb2_buffer_done(&buffer->vb.vb2_buf, state);
list_del(&buffer->list);
}
spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
}
static int hackrf_queue_setup(struct vb2_queue *vq,
unsigned int *nbuffers,
unsigned int *nplanes, unsigned int sizes[], struct device *alloc_devs[])
{
struct hackrf_dev *dev = vb2_get_drv_priv(vq);
unsigned int q_num_bufs = vb2_get_num_buffers(vq);
dev_dbg(dev->dev, "nbuffers=%d\n", *nbuffers);
/* Need at least 8 buffers */
if (q_num_bufs + *nbuffers < 8)
*nbuffers = 8 - q_num_bufs;
*nplanes = 1;
sizes[0] = PAGE_ALIGN(dev->buffersize);
dev_dbg(dev->dev, "nbuffers=%d sizes[0]=%d\n", *nbuffers, sizes[0]);
return 0;
}
static void hackrf_buf_queue(struct vb2_buffer *vb)
{
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
struct vb2_queue *vq = vb->vb2_queue;
struct hackrf_dev *dev = vb2_get_drv_priv(vq);
struct hackrf_buffer *buffer = container_of(vbuf, struct hackrf_buffer, vb);
struct list_head *buffer_list;
unsigned long flags;
dev_dbg_ratelimited(&dev->intf->dev, "\n");
if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
buffer_list = &dev->rx_buffer_list;
else
buffer_list = &dev->tx_buffer_list;
spin_lock_irqsave(&dev->buffer_list_lock, flags);
list_add_tail(&buffer->list, buffer_list);
spin_unlock_irqrestore(&dev->buffer_list_lock, flags);
}
static int hackrf_start_streaming(struct vb2_queue *vq, unsigned int count)
{
struct hackrf_dev *dev = vb2_get_drv_priv(vq);
struct usb_interface *intf = dev->intf;
int ret;
unsigned int mode;
dev_dbg(&intf->dev, "count=%i\n", count);
mutex_lock(&dev->v4l2_lock);
/* Allow only RX or TX, not both same time */
if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE) {
if (test_bit(TX_ON, &dev->flags)) {
ret = -EBUSY;
goto err_hackrf_return_all_buffers;
}
mode = 1;
set_bit(RX_ON, &dev->flags);
} else {
if (test_bit(RX_ON, &dev->flags)) {
ret = -EBUSY;
goto err_hackrf_return_all_buffers;
}
mode = 2;
set_bit(TX_ON, &dev->flags);
}
dev->sequence = 0;
ret = hackrf_alloc_stream_bufs(dev);
if (ret)
goto err;
ret = hackrf_alloc_urbs(dev, (mode == 1));
if (ret)
goto err;
ret = hackrf_submit_urbs(dev);
if (ret)
goto err;
ret = hackrf_set_params(dev);
if (ret)
goto err;
/* start hardware streaming */
ret = hackrf_ctrl_msg(dev, CMD_SET_TRANSCEIVER_MODE, mode, 0, NULL, 0);
if (ret)
goto err;
mutex_unlock(&dev->v4l2_lock);
return 0;
err:
hackrf_kill_urbs(dev);
hackrf_free_urbs(dev);
hackrf_free_stream_bufs(dev);
clear_bit(RX_ON, &dev->flags);
clear_bit(TX_ON, &dev->flags);
err_hackrf_return_all_buffers:
hackrf_return_all_buffers(vq, VB2_BUF_STATE_QUEUED);
mutex_unlock(&dev->v4l2_lock);
dev_dbg(&intf->dev, "failed=%d\n", ret);
return ret;
}
static void hackrf_stop_streaming(struct vb2_queue *vq)
{
struct hackrf_dev *dev = vb2_get_drv_priv(vq);
struct usb_interface *intf = dev->intf;
dev_dbg(&intf->dev, "\n");
mutex_lock(&dev->v4l2_lock);
/* stop hardware streaming */
hackrf_ctrl_msg(dev, CMD_SET_TRANSCEIVER_MODE, 0, 0, NULL, 0);
hackrf_kill_urbs(dev);
hackrf_free_urbs(dev);
hackrf_free_stream_bufs(dev);
hackrf_return_all_buffers(vq, VB2_BUF_STATE_ERROR);
if (vq->type == V4L2_BUF_TYPE_SDR_CAPTURE)
clear_bit(RX_ON, &dev->flags);
else
clear_bit(TX_ON, &dev->flags);
mutex_unlock(&dev->v4l2_lock);
}
static const struct vb2_ops hackrf_vb2_ops = {
.queue_setup = hackrf_queue_setup,
.buf_queue = hackrf_buf_queue,
.start_streaming = hackrf_start_streaming,
.stop_streaming = hackrf_stop_streaming,
};
static int hackrf_querycap(struct file *file, void *fh,
struct v4l2_capability *cap)
{
struct hackrf_dev *dev = video_drvdata(file);
struct usb_interface *intf = dev->intf;
dev_dbg(&intf->dev, "\n");
cap->capabilities = V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER |
V4L2_CAP_SDR_OUTPUT | V4L2_CAP_MODULATOR |
V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
V4L2_CAP_DEVICE_CAPS;
strscpy(cap->driver, KBUILD_MODNAME, sizeof(cap->driver));
strscpy(cap->card, dev->rx_vdev.name, sizeof(cap->card));
usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
return 0;
}
static int hackrf_s_fmt_sdr(struct file *file, void *priv,
struct v4l2_format *f)
{
struct hackrf_dev *dev = video_drvdata(file);
struct video_device *vdev = video_devdata(file);
struct vb2_queue *q;
int i;
dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
(char *)&f->fmt.sdr.pixelformat);
if (vdev->vfl_dir == VFL_DIR_RX)
q = &dev->rx_vb2_queue;
else
q = &dev->tx_vb2_queue;
if (vb2_is_busy(q))
return -EBUSY;
for (i = 0; i < NUM_FORMATS; i++) {
if (f->fmt.sdr.pixelformat == formats[i].pixelformat) {
dev->pixelformat = formats[i].pixelformat;
dev->buffersize = formats[i].buffersize;
f->fmt.sdr.buffersize = formats[i].buffersize;
return 0;
}
}
dev->pixelformat = formats[0].pixelformat;
dev->buffersize = formats[0].buffersize;
f->fmt.sdr.pixelformat = formats[0].pixelformat;
f->fmt.sdr.buffersize = formats[0].buffersize;
return 0;
}
static int hackrf_g_fmt_sdr(struct file *file, void *priv,
struct v4l2_format *f)
{
struct hackrf_dev *dev = video_drvdata(file);
dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
(char *)&dev->pixelformat);
f->fmt.sdr.pixelformat = dev->pixelformat;
f->fmt.sdr.buffersize = dev->buffersize;
return 0;
}
static int hackrf_try_fmt_sdr(struct file *file, void *priv,
struct v4l2_format *f)
{
struct hackrf_dev *dev = video_drvdata(file);
int i;
dev_dbg(dev->dev, "pixelformat fourcc %4.4s\n",
(char *)&f->fmt.sdr.pixelformat);
for (i = 0; i < NUM_FORMATS; i++) {
if (formats[i].pixelformat == f->fmt.sdr.pixelformat) {
f->fmt.sdr.buffersize = formats[i].buffersize;
return 0;
}
}
f->fmt.sdr.pixelformat = formats[0].pixelformat;
f->fmt.sdr.buffersize = formats[0].buffersize;
return 0;
}
static int hackrf_enum_fmt_sdr(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct hackrf_dev *dev = video_drvdata(file);
dev_dbg(dev->dev, "index=%d\n", f->index);
if (f->index >= NUM_FORMATS)
return -EINVAL;
f->pixelformat = formats[f->index].pixelformat;
return 0;
}
static int hackrf_s_tuner(struct file *file, void *priv,
const struct v4l2_tuner *v)
{
struct hackrf_dev *dev = video_drvdata(file);
int ret;
dev_dbg(dev->dev, "index=%d\n", v->index);
if (v->index == 0)
ret = 0;
else if (v->index == 1)
ret = 0;
else
ret = -EINVAL;
return ret;
}
static int hackrf_g_tuner(struct file *file, void *priv, struct v4l2_tuner *v)
{
struct hackrf_dev *dev = video_drvdata(file);
int ret;
dev_dbg(dev->dev, "index=%d\n", v->index);
if (v->index == 0) {
strscpy(v->name, "HackRF ADC", sizeof(v->name));
v->type = V4L2_TUNER_SDR;
v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
v->rangelow = bands_adc_dac[0].rangelow;
v->rangehigh = bands_adc_dac[0].rangehigh;
ret = 0;
} else if (v->index == 1) {
strscpy(v->name, "HackRF RF", sizeof(v->name));
v->type = V4L2_TUNER_RF;
v->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
v->rangelow = bands_rx_tx[0].rangelow;
v->rangehigh = bands_rx_tx[0].rangehigh;
ret = 0;
} else {
ret = -EINVAL;
}
return ret;
}
static int hackrf_s_modulator(struct file *file, void *fh,
const struct v4l2_modulator *a)
{
struct hackrf_dev *dev = video_drvdata(file);
dev_dbg(dev->dev, "index=%d\n", a->index);
return a->index > 1 ? -EINVAL : 0;
}
static int hackrf_g_modulator(struct file *file, void *fh,
struct v4l2_modulator *a)
{
struct hackrf_dev *dev = video_drvdata(file);
int ret;
dev_dbg(dev->dev, "index=%d\n", a->index);
if (a->index == 0) {
strscpy(a->name, "HackRF DAC", sizeof(a->name));
a->type = V4L2_TUNER_SDR;
a->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
a->rangelow = bands_adc_dac[0].rangelow;
a->rangehigh = bands_adc_dac[0].rangehigh;
ret = 0;
} else if (a->index == 1) {
strscpy(a->name, "HackRF RF", sizeof(a->name));
a->type = V4L2_TUNER_RF;
a->capability = V4L2_TUNER_CAP_1HZ | V4L2_TUNER_CAP_FREQ_BANDS;
a->rangelow = bands_rx_tx[0].rangelow;
a->rangehigh = bands_rx_tx[0].rangehigh;
ret = 0;
} else {
ret = -EINVAL;
}
return ret;
}
static int hackrf_s_frequency(struct file *file, void *priv,
const struct v4l2_frequency *f)
{
struct hackrf_dev *dev = video_drvdata(file);
struct usb_interface *intf = dev->intf;
struct video_device *vdev = video_devdata(file);
int ret;
unsigned int uitmp;
dev_dbg(&intf->dev, "tuner=%d type=%d frequency=%u\n",
f->tuner, f->type, f->frequency);
if (f->tuner == 0) {
uitmp = clamp(f->frequency, bands_adc_dac[0].rangelow,
bands_adc_dac[0].rangehigh);
if (vdev->vfl_dir == VFL_DIR_RX) {
dev->f_adc = uitmp;
set_bit(RX_ADC_FREQUENCY, &dev->flags);
} else {
dev->f_dac = uitmp;
set_bit(TX_DAC_FREQUENCY, &dev->flags);
}
} else if (f->tuner == 1) {
uitmp = clamp(f->frequency, bands_rx_tx[0].rangelow,
bands_rx_tx[0].rangehigh);
if (vdev->vfl_dir == VFL_DIR_RX) {
dev->f_rx = uitmp;
set_bit(RX_RF_FREQUENCY, &dev->flags);
} else {
dev->f_tx = uitmp;
set_bit(TX_RF_FREQUENCY, &dev->flags);
}
} else {
ret = -EINVAL;
goto err;
}
ret = hackrf_set_params(dev);
if (ret)
goto err;
return 0;
err:
dev_dbg(&intf->dev, "failed=%d\n", ret);
return ret;
}
static int hackrf_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct hackrf_dev *dev = video_drvdata(file);
struct usb_interface *intf = dev->intf;
struct video_device *vdev = video_devdata(file);
int ret;
dev_dbg(dev->dev, "tuner=%d type=%d\n", f->tuner, f->type);
if (f->tuner == 0) {
f->type = V4L2_TUNER_SDR;
if (vdev->vfl_dir == VFL_DIR_RX)
f->frequency = dev->f_adc;
else
f->frequency = dev->f_dac;
} else if (f->tuner == 1) {
f->type = V4L2_TUNER_RF;
if (vdev->vfl_dir == VFL_DIR_RX)
f->frequency = dev->f_rx;
else
f->frequency = dev->f_tx;
} else {
ret = -EINVAL;
goto err;
}
return 0;
err:
dev_dbg(&intf->dev, "failed=%d\n", ret);
return ret;
}
static int hackrf_enum_freq_bands(struct file *file, void *priv,
struct v4l2_frequency_band *band)
{
struct hackrf_dev *dev = video_drvdata(file);
int ret;
dev_dbg(dev->dev, "tuner=%d type=%d index=%d\n",
band->tuner, band->type, band->index);
if (band->tuner == 0) {
if (band->index >= ARRAY_SIZE(bands_adc_dac)) {
ret = -EINVAL;
} else {
*band = bands_adc_dac[band->index];
ret = 0;
}
} else if (band->tuner == 1) {
if (band->index >= ARRAY_SIZE(bands_rx_tx)) {
ret = -EINVAL;
} else {
*band = bands_rx_tx[band->index];
ret = 0;
}
} else {
ret = -EINVAL;
}
return ret;
}
static const struct v4l2_ioctl_ops hackrf_ioctl_ops = {
.vidioc_querycap = hackrf_querycap,
.vidioc_s_fmt_sdr_cap = hackrf_s_fmt_sdr,
.vidioc_g_fmt_sdr_cap = hackrf_g_fmt_sdr,
.vidioc_enum_fmt_sdr_cap = hackrf_enum_fmt_sdr,
.vidioc_try_fmt_sdr_cap = hackrf_try_fmt_sdr,
.vidioc_s_fmt_sdr_out = hackrf_s_fmt_sdr,
.vidioc_g_fmt_sdr_out = hackrf_g_fmt_sdr,
.vidioc_enum_fmt_sdr_out = hackrf_enum_fmt_sdr,
.vidioc_try_fmt_sdr_out = hackrf_try_fmt_sdr,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_create_bufs = vb2_ioctl_create_bufs,
.vidioc_prepare_buf = vb2_ioctl_prepare_buf,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_expbuf = vb2_ioctl_expbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_s_tuner = hackrf_s_tuner,
.vidioc_g_tuner = hackrf_g_tuner,
.vidioc_s_modulator = hackrf_s_modulator,
.vidioc_g_modulator = hackrf_g_modulator,
.vidioc_s_frequency = hackrf_s_frequency,
.vidioc_g_frequency = hackrf_g_frequency,
.vidioc_enum_freq_bands = hackrf_enum_freq_bands,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
.vidioc_log_status = v4l2_ctrl_log_status,
};
static const struct v4l2_file_operations hackrf_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = vb2_fop_release,
.read = vb2_fop_read,
.write = vb2_fop_write,
.poll = vb2_fop_poll,
.mmap = vb2_fop_mmap,
.unlocked_ioctl = video_ioctl2,
};
static const struct video_device hackrf_template = {
.name = "HackRF One",
.release = video_device_release_empty,
.fops = &hackrf_fops,
.ioctl_ops = &hackrf_ioctl_ops,
};
static void hackrf_video_release(struct v4l2_device *v)
{
struct hackrf_dev *dev = container_of(v, struct hackrf_dev, v4l2_dev);
dev_dbg(dev->dev, "\n");
v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);
v4l2_ctrl_handler_free(&dev->tx_ctrl_handler);
v4l2_device_unregister(&dev->v4l2_dev);
kfree(dev);
}
static int hackrf_s_ctrl_rx(struct v4l2_ctrl *ctrl)
{
struct hackrf_dev *dev = container_of(ctrl->handler,
struct hackrf_dev, rx_ctrl_handler);
struct usb_interface *intf = dev->intf;
int ret;
switch (ctrl->id) {
case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
case V4L2_CID_RF_TUNER_BANDWIDTH:
set_bit(RX_BANDWIDTH, &dev->flags);
break;
case V4L2_CID_RF_TUNER_RF_GAIN:
set_bit(RX_RF_GAIN, &dev->flags);
break;
case V4L2_CID_RF_TUNER_LNA_GAIN:
set_bit(RX_LNA_GAIN, &dev->flags);
break;
case V4L2_CID_RF_TUNER_IF_GAIN:
set_bit(RX_IF_GAIN, &dev->flags);
break;
default:
dev_dbg(&intf->dev, "unknown ctrl: id=%d name=%s\n",
ctrl->id, ctrl->name);
ret = -EINVAL;
goto err;
}
ret = hackrf_set_params(dev);
if (ret)
goto err;
return 0;
err:
dev_dbg(&intf->dev, "failed=%d\n", ret);
return ret;
}
static int hackrf_s_ctrl_tx(struct v4l2_ctrl *ctrl)
{
struct hackrf_dev *dev = container_of(ctrl->handler,
struct hackrf_dev, tx_ctrl_handler);
struct usb_interface *intf = dev->intf;
int ret;
switch (ctrl->id) {
case V4L2_CID_RF_TUNER_BANDWIDTH_AUTO:
case V4L2_CID_RF_TUNER_BANDWIDTH:
set_bit(TX_BANDWIDTH, &dev->flags);
break;
case V4L2_CID_RF_TUNER_LNA_GAIN:
set_bit(TX_LNA_GAIN, &dev->flags);
break;
case V4L2_CID_RF_TUNER_RF_GAIN:
set_bit(TX_RF_GAIN, &dev->flags);
break;
default:
dev_dbg(&intf->dev, "unknown ctrl: id=%d name=%s\n",
ctrl->id, ctrl->name);
ret = -EINVAL;
goto err;
}
ret = hackrf_set_params(dev);
if (ret)
goto err;
return 0;
err:
dev_dbg(&intf->dev, "failed=%d\n", ret);
return ret;
}
static const struct v4l2_ctrl_ops hackrf_ctrl_ops_rx = {
.s_ctrl = hackrf_s_ctrl_rx,
};
static const struct v4l2_ctrl_ops hackrf_ctrl_ops_tx = {
.s_ctrl = hackrf_s_ctrl_tx,
};
static int hackrf_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct hackrf_dev *dev;
int ret;
u8 u8tmp, buf[BUF_SIZE];
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
ret = -ENOMEM;
goto err;
}
mutex_init(&dev->v4l2_lock);
mutex_init(&dev->vb_queue_lock);
spin_lock_init(&dev->buffer_list_lock);
INIT_LIST_HEAD(&dev->rx_buffer_list);
INIT_LIST_HEAD(&dev->tx_buffer_list);
dev->intf = intf;
dev->dev = &intf->dev;
dev->udev = interface_to_usbdev(intf);
dev->pixelformat = formats[0].pixelformat;
dev->buffersize = formats[0].buffersize;
dev->f_adc = bands_adc_dac[0].rangelow;
dev->f_dac = bands_adc_dac[0].rangelow;
dev->f_rx = bands_rx_tx[0].rangelow;
dev->f_tx = bands_rx_tx[0].rangelow;
set_bit(RX_ADC_FREQUENCY, &dev->flags);
set_bit(TX_DAC_FREQUENCY, &dev->flags);
set_bit(RX_RF_FREQUENCY, &dev->flags);
set_bit(TX_RF_FREQUENCY, &dev->flags);
/* Detect device */
ret = hackrf_ctrl_msg(dev, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
if (ret == 0)
ret = hackrf_ctrl_msg(dev, CMD_VERSION_STRING_READ, 0, 0,
buf, BUF_SIZE);
if (ret) {
dev_err(dev->dev, "Could not detect board\n");
goto err_kfree;
}
buf[BUF_SIZE - 1] = '\0';
dev_info(dev->dev, "Board ID: %02x\n", u8tmp);
dev_info(dev->dev, "Firmware version: %s\n", buf);
/* Init vb2 queue structure for receiver */
dev->rx_vb2_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
dev->rx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
VB2_READ;
dev->rx_vb2_queue.ops = &hackrf_vb2_ops;
dev->rx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
dev->rx_vb2_queue.drv_priv = dev;
dev->rx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
dev->rx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
dev->rx_vb2_queue.lock = &dev->vb_queue_lock;
ret = vb2_queue_init(&dev->rx_vb2_queue);
if (ret) {
dev_err(dev->dev, "Could not initialize rx vb2 queue\n");
goto err_kfree;
}
/* Init vb2 queue structure for transmitter */
dev->tx_vb2_queue.type = V4L2_BUF_TYPE_SDR_OUTPUT;
dev->tx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
VB2_WRITE;
dev->tx_vb2_queue.ops = &hackrf_vb2_ops;
dev->tx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
dev->tx_vb2_queue.drv_priv = dev;
dev->tx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
dev->tx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
dev->tx_vb2_queue.lock = &dev->vb_queue_lock;
ret = vb2_queue_init(&dev->tx_vb2_queue);
if (ret) {
dev_err(dev->dev, "Could not initialize tx vb2 queue\n");
goto err_kfree;
}
/* Register controls for receiver */
v4l2_ctrl_handler_init(&dev->rx_ctrl_handler, 5);
dev->rx_bandwidth_auto = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
0, 1, 0, 1);
dev->rx_bandwidth = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH,
1750000, 28000000, 50000, 1750000);
v4l2_ctrl_auto_cluster(2, &dev->rx_bandwidth_auto, 0, false);
dev->rx_rf_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 12, 12, 0);
dev->rx_lna_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 40, 8, 0);
dev->rx_if_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
&hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_IF_GAIN, 0, 62, 2, 0);
if (dev->rx_ctrl_handler.error) {
ret = dev->rx_ctrl_handler.error;
dev_err(dev->dev, "Could not initialize controls\n");
goto err_v4l2_ctrl_handler_free_rx;
}
v4l2_ctrl_grab(dev->rx_rf_gain, !hackrf_enable_rf_gain_ctrl);
v4l2_ctrl_handler_setup(&dev->rx_ctrl_handler);
/* Register controls for transmitter */
v4l2_ctrl_handler_init(&dev->tx_ctrl_handler, 4);
dev->tx_bandwidth_auto = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
0, 1, 0, 1);
dev->tx_bandwidth = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH,
1750000, 28000000, 50000, 1750000);
v4l2_ctrl_auto_cluster(2, &dev->tx_bandwidth_auto, 0, false);
dev->tx_lna_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 47, 1, 0);
dev->tx_rf_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
&hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 15, 15, 0);
if (dev->tx_ctrl_handler.error) {
ret = dev->tx_ctrl_handler.error;
dev_err(dev->dev, "Could not initialize controls\n");
goto err_v4l2_ctrl_handler_free_tx;
}
v4l2_ctrl_grab(dev->tx_rf_gain, !hackrf_enable_rf_gain_ctrl);
v4l2_ctrl_handler_setup(&dev->tx_ctrl_handler);
/* Register the v4l2_device structure */
dev->v4l2_dev.release = hackrf_video_release;
ret = v4l2_device_register(&intf->dev, &dev->v4l2_dev);
if (ret) {
dev_err(dev->dev, "Failed to register v4l2-device (%d)\n", ret);
goto err_v4l2_ctrl_handler_free_tx;
}
/* Init video_device structure for receiver */
dev->rx_vdev = hackrf_template;
dev->rx_vdev.queue = &dev->rx_vb2_queue;
dev->rx_vdev.v4l2_dev = &dev->v4l2_dev;
dev->rx_vdev.ctrl_handler = &dev->rx_ctrl_handler;
dev->rx_vdev.lock = &dev->v4l2_lock;
dev->rx_vdev.vfl_dir = VFL_DIR_RX;
dev->rx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER;
video_set_drvdata(&dev->rx_vdev, dev);
ret = video_register_device(&dev->rx_vdev, VFL_TYPE_SDR, -1);
if (ret) {
dev_err(dev->dev,
"Failed to register as video device (%d)\n", ret);
goto err_v4l2_device_unregister;
}
dev_info(dev->dev, "Registered as %s\n",
video_device_node_name(&dev->rx_vdev));
/* Init video_device structure for transmitter */
dev->tx_vdev = hackrf_template;
dev->tx_vdev.queue = &dev->tx_vb2_queue;
dev->tx_vdev.v4l2_dev = &dev->v4l2_dev;
dev->tx_vdev.ctrl_handler = &dev->tx_ctrl_handler;
dev->tx_vdev.lock = &dev->v4l2_lock;
dev->tx_vdev.vfl_dir = VFL_DIR_TX;
dev->tx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
V4L2_CAP_SDR_OUTPUT | V4L2_CAP_MODULATOR;
video_set_drvdata(&dev->tx_vdev, dev);
ret = video_register_device(&dev->tx_vdev, VFL_TYPE_SDR, -1);
if (ret) {
dev_err(dev->dev,
"Failed to register as video device (%d)\n", ret);
goto err_video_unregister_device_rx;
}
dev_info(dev->dev, "Registered as %s\n",
video_device_node_name(&dev->tx_vdev));
dev_notice(dev->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
return 0;
err_video_unregister_device_rx:
video_unregister_device(&dev->rx_vdev);
err_v4l2_device_unregister:
v4l2_device_unregister(&dev->v4l2_dev);
err_v4l2_ctrl_handler_free_tx:
v4l2_ctrl_handler_free(&dev->tx_ctrl_handler);
err_v4l2_ctrl_handler_free_rx:
v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);
err_kfree:
kfree(dev);
err:
dev_dbg(&intf->dev, "failed=%d\n", ret);
return ret;
}
/* USB device ID list */
static const struct usb_device_id hackrf_id_table[] = {
{ USB_DEVICE(0x1d50, 0x6089) }, /* HackRF One */
{ }
};
MODULE_DEVICE_TABLE(usb, hackrf_id_table);
/* USB subsystem interface */
static struct usb_driver hackrf_driver = {
.name = KBUILD_MODNAME,
.probe = hackrf_probe,
.disconnect = hackrf_disconnect,
.id_table = hackrf_id_table,
};
module_usb_driver(hackrf_driver);
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
MODULE_DESCRIPTION("HackRF");
MODULE_LICENSE("GPL");
]
|
| 9/2 |
2026/02/06 10:39 |
llm |
expert |
0m
Model:
Tokens:
input: 43430
output: 21
thoughts: 1181
Thoughts: **Analyzing a KASAN Slab-Use-After-Free in v4l2_ioctl**
Okay, so I'm looking at a KASAN report indicating a slab-use-after-free error within the `v4l2_ioctl` function, specifically at line 364 of `drivers/media/v4l2-core/v4l2-dev.c`. The trace points to a read of size 8 at address `ffff888053a040c8` by the `v4l_id` task.
The initial report mentioned that the allocation is in `hackrf_probe`, at `hackrf_probe+0xda/0x1390 drivers/media/usb/hackrf/hackrf.c:1351`, and the corresponding free is at `hackrf_probe+0xd98/0x1390 drivers/media/usb/hackrf/hackrf.c:1523`. I verified the lines numbers: Line 1351 indeed contains the `kzalloc` for `dev` and line 1523 the `kfree`. The `read-file` output doesn't give line numbers, so I have to verify using the `codesearch-definition-source` tool.
The `hackrf_probe` function is the USB probe function for the HackRF device, and the code shows that it allocates a `hackrf_dev` structure. I need to understand how `hackrf_dev` relates to the `video_device` struct. It looks like there's an instance of `struct video_device` embedded within the `hackrf_dev` struct, `dev->tx_vdev` and `dev->rx_vdev`. This is a critical clue.
My immediate thought is that `dev` is being freed prematurely, leading to the use-after-free error. I need to trace the error paths in `hackrf_probe`. From the provided code snippet, it looks like there are several error paths in `hackrf_probe` that could lead to the `kfree(dev)` call, and some of them may not be correctly cleaning up the associated `video_device` structures. The code suggests several points where device registration or handler initialization could fail, triggering a cascade of unregistration and free operations.
The KASAN report indicates that the fault is happening within `v4l2_ioctl`. Specifically, the code attempts to access `vdev->fops`, where `vdev` is the video device data structure. The address `ffff888053a040c8` seems to be an offset from the `vdev` pointer. Given that `vdev` is at `ffff888053a04000`, accessing `vdev->fops` means accessing the memory at that offset. Since I'm dealing with a use-after-free, `dev` is likely getting freed and the memory region being reused by something else. Therefore, the contents that should belong to the `vdev->fops` pointer are corrupted.
My next step is to examine the `hackrf_dev` structure more closely and verify how it interacts with the `video_device` structures, paying particular attention to their lifecycles within `hackrf_probe` and any other relevant functions. I need to check the code that's calling the IOCTL and pinpoint exactly *when* and *why* this IOCTL is being called after the allocation. I'll need to look for any race conditions, improper error handling, or missing synchronization that might be contributing to the use-after-free. I'll also check if all the `video_unregister_device` and related operations are happening in the correct order in all the error paths within `hackrf_probe`. A possible race condition within the error paths can lead to the scenario that a particular `video_device` gets unregistered earlier than it is expected to be.
|
| 10/2 |
2026/02/06 10:40 |
tool |
codesearch-struct-layout |
0m
Args:
Results: map[Fields:[map[Name:entity OffsetBits:0 SizeBits:960] map[Name:intf_devnode OffsetBits:960 SizeBits:64] map[Name:pipe OffsetBits:1024 SizeBits:320] map[Name:fops OffsetBits:1344 SizeBits:64] map[Name:device_caps OffsetBits:1408 SizeBits:32] map[Name:dev OffsetBits:1472 SizeBits:9088] map[Name:cdev OffsetBits:10560 SizeBits:64] map[Name:v4l2_dev OffsetBits:10624 SizeBits:64] map[Name:dev_parent OffsetBits:10688 SizeBits:64] map[Name:ctrl_handler OffsetBits:10752 SizeBits:64] map[Name:queue OffsetBits:10816 SizeBits:64] map[Name:prio OffsetBits:10880 SizeBits:64] map[Name:name OffsetBits:10944 SizeBits:512] map[Name:vfl_type OffsetBits:11456 SizeBits:32] map[Name:vfl_dir OffsetBits:11488 SizeBits:32] map[Name:minor OffsetBits:11520 SizeBits:32] map[Name:num OffsetBits:11552 SizeBits:16] map[Name:flags OffsetBits:11584 SizeBits:64] map[Name:index OffsetBits:11648 SizeBits:32] map[Name:fh_lock OffsetBits:11712 SizeBits:512] map[Name:fh_list OffsetBits:12224 SizeBits:128] map[Name:dev_debug OffsetBits:12352 SizeBits:32] map[Name:tvnorms OffsetBits:12416 SizeBits:64] map[Name:release OffsetBits:12480 SizeBits:64] map[Name:ioctl_ops OffsetBits:12544 SizeBits:64] map[Name:valid_ioctls OffsetBits:12608 SizeBits:192] map[Name:lock OffsetBits:12800 SizeBits:64]]]
|
| 11/2 |
2026/02/06 10:40 |
llm |
expert |
0m
Model:
Tokens:
input: 46107
output: 22
thoughts: 687
Thoughts: **Analyzing a Potential Kernel Bug**
Okay, so I'm looking at this crash report, and the first thing I see is that `fops` is supposedly at an offset of 168 bytes. The buggy address is `ffff888053a040c8`, and the object's base address is `ffff888053a04000`. So, that means the offset from the base is `0xc8`, or 200 bytes. Something doesn't quite line up here. Wait, `fops` is at 168 bytes, while 200 bytes are being accessed, not 168.
Let's see what's at 200 bytes. Ah, `device_caps` is at 176 bytes, and `dev` is at 184 bytes. Okay, time to go back to `struct video_device`. I remember `dev` is a `struct device`. Now, looking at that offset of 200, that's only 16 bytes into `struct device`.
Now, the report points to `v4l2_ioctl+0xc7/0x1e0` in `v4l2-dev.c` at line 364. I check my source of `v4l2-dev.c`, line 364 is empty. I should probably adjust for potential line number differences. Let me assume it's actually line 365, which is `if (vdev->fops->unlocked_ioctl) {`.
Okay, the report says the crash is related to `vdev->fops`, and `vdev` is a `video_device`. Based on the offset calculations, `vdev->fops` should be at offset 168. To dereference this it would be read first, but the access is happening at offset 200. I need to understand that mismatch.
Let's double-check how `vdev` is obtained. The code says: `video_devdata(filp)`. Okay, that calls `video_devices[iminor(file_inode(file))]`. So, it's returning a `struct video_device *`.
Aha! Now I remember, in the `hackrf_dev` struct, there are `video_device` members: `rx_vdev` and `tx_vdev`. It looks like the allocation that happened was for a `struct hackrf_dev`. And it was a `kzalloc` with `GFP_KERNEL` and the size of `dev`. I remember seeing that this `dev` object is 8k (kmalloc-8k) in size. So, `struct hackrf_dev` must be quite large. I need to understand this layout and how the members relate to one another. I need to look at the layout of `struct hackrf_dev` now, and how the `video_device` structs are embedded within it.
|
| 12/2 |
2026/02/06 10:40 |
tool |
codesearch-struct-layout |
0m
Args:
Results: map[Fields:[map[Name:flags OffsetBits:0 SizeBits:64] map[Name:intf OffsetBits:64 SizeBits:64] map[Name:dev OffsetBits:128 SizeBits:64] map[Name:udev OffsetBits:192 SizeBits:64] map[Name:rx_vdev OffsetBits:256 SizeBits:12864] map[Name:tx_vdev OffsetBits:13120 SizeBits:12864] map[Name:v4l2_dev OffsetBits:25984 SizeBits:1472] map[Name:rx_vb2_queue OffsetBits:27456 SizeBits:4672] map[Name:tx_vb2_queue OffsetBits:32128 SizeBits:4672] map[Name:rx_buffer_list OffsetBits:36800 SizeBits:128] map[Name:tx_buffer_list OffsetBits:36928 SizeBits:128] map[Name:buffer_list_lock OffsetBits:37056 SizeBits:512] map[Name:sequence OffsetBits:37568 SizeBits:32] map[Name:vb_full OffsetBits:37600 SizeBits:32] map[Name:vb_empty OffsetBits:37632 SizeBits:32] map[Name:v4l2_lock OffsetBits:37696 SizeBits:1152] map[Name:vb_queue_lock OffsetBits:38848 SizeBits:1152] map[Name:urb_list OffsetBits:40000 SizeBits:384] map[Name:buf_num OffsetBits:40384 SizeBits:32] map[Name:buf_size OffsetBits:40448 SizeBits:64] map[Name:buf_list OffsetBits:40512 SizeBits:384] map[Name:dma_addr OffsetBits:40896 SizeBits:384] map[Name:urbs_initialized OffsetBits:41280 SizeBits:32] map[Name:urbs_submitted OffsetBits:41312 SizeBits:32] map[Name:buf OffsetBits:41344 SizeBits:192] map[Name:f_adc OffsetBits:41536 SizeBits:32] map[Name:f_dac OffsetBits:41568 SizeBits:32] map[Name:f_rx OffsetBits:41600 SizeBits:32] map[Name:f_tx OffsetBits:41632 SizeBits:32] map[Name:pixelformat OffsetBits:41664 SizeBits:32] map[Name:buffersize OffsetBits:41696 SizeBits:32] map[Name:rx_ctrl_handler OffsetBits:41728 SizeBits:2496] map[Name:rx_bandwidth_auto OffsetBits:44224 SizeBits:64] map[Name:rx_bandwidth OffsetBits:44288 SizeBits:64] map[Name:rx_rf_gain OffsetBits:44352 SizeBits:64] map[Name:rx_lna_gain OffsetBits:44416 SizeBits:64] map[Name:rx_if_gain OffsetBits:44480 SizeBits:64] map[Name:tx_ctrl_handler OffsetBits:44544 SizeBits:2496] map[Name:tx_bandwidth_auto OffsetBits:47040 SizeBits:64] map[Name:tx_bandwidth OffsetBits:47104 SizeBits:64] map[Name:tx_rf_gain OffsetBits:47168 SizeBits:64] map[Name:tx_lna_gain OffsetBits:47232 SizeBits:64] map[Name:jiffies_next OffsetBits:47296 SizeBits:64] map[Name:sample OffsetBits:47360 SizeBits:32] map[Name:sample_measured OffsetBits:47392 SizeBits:32]]]
|
| 13/2 |
2026/02/06 10:40 |
llm |
expert |
0m
Model:
Tokens:
input: 48559
output: 27
thoughts: 1089
Thoughts: **Analyzing the Bug: A Dive into the HackRF Driver**
Okay, let's break this down. The faulty access is at address `ffff888053a040c8`, and the object's start is at `ffff888053a04000`. That's an offset of 200 bytes. I see that `rx_vdev` (the receiver video device) is located at an offset of 32 bytes within the `hackrf_dev` structure, and `tx_vdev` (the transmitter video device) is at 1640 bytes, but I think the issue is with `rx_vdev`.
If we're hitting `rx_vdev`, the target is 200 bytes into the `hackrf_dev` object, or 168 bytes into the `rx_vdev` object (`200 - 32 = 168`). Hah! That means we're accessing `vdev->fops`, and I recall that `fops` in the `video_device` structure is at offset 168 bytes. This confirms that the access is indeed `vdev->fops`, perfectly fitting the pattern.
Looking at `v4l2_ioctl`, the code fetches the `video_device` struct `vdev`. Then, if `vdev->fops->unlocked_ioctl` exists, it is called. Since `vdev` is `&dev->rx_vdev`, and `fops` is at offset 168, that means the offset from the `hackrf_dev` object is indeed 200 bytes. This all fits like a glove.
Now, the debugger pointed out that the `hackrf_dev` object was freed. I remember that the `hackrf_dev` object is allocated and freed within the `hackrf_probe` function. The allocation uses `kzalloc`, and the free uses `kfree`. The trace shows that the free happened inside the `hackrf_probe` function, at line 1523 in `hackrf.c`. The free stack trace points to `hackrf_probe`, which indicates this is an error path.
Looking at the code around line 1523, it is in the `err_*` labels, so this is definitely an error path. Line 1523, in my read-file output is `v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);`. That's not a free!
This is where I need to take a closer look at the actual source to confirm those line numbers, but my thinking is now: this all seems to be a case of use-after-free, triggered when an error occurs during device initialization. I need to figure out which error specifically, but I think the culprit is the freeing of `dev` in the error handling. I'll use `codesearch-definition-source` to get line number details, and find the real root cause.
|
| 14/2 |
2026/02/06 10:40 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[IncludeLines:true Name:hackrf_probe]
|
| 15/2 |
2026/02/06 10:40 |
llm |
expert |
0m
Model:
Tokens:
input: 50354
output: 46
thoughts: 8
Thoughts: Okay, here's the summary, rendered as a first-person thought process, assuming the user is an expert who would understand "ContextFile" as a specific, relevant term:
**The Crucial Oversight**
Ugh, I had a mental lapse. I just realized I completely forgot to consider `ContextFile` in this analysis. That's a critical piece of the puzzle! I was so focused on [insert relevant field-specific details the expert would be focusing on, e.g., the core algorithm, the user behavior model, the specific data structure], I completely missed the implications that `ContextFile` brings. It's not just a minor detail; its presence (or absence) drastically changes the expected outcomes. I need to backtrack and factor in the `ContextFile` data. This is going to significantly alter my assumptions about [the relevant process, e.g., the resource allocation, the user segmentation, the model's accuracy]. Time to re-evaluate everything. This could be a game changer, for better or worse, and I should have caught this earlier. I am so glad I caught this before I published my findings.
|
| 16/2 |
2026/02/06 10:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/media/usb/hackrf/hackrf.c IncludeLines:true Name:hackrf_probe]
Results: map[SourceCode:1344: static int hackrf_probe(struct usb_interface *intf,
1345: const struct usb_device_id *id)
1346: {
1347: struct hackrf_dev *dev;
1348: int ret;
1349: u8 u8tmp, buf[BUF_SIZE];
1350:
1351: dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1352: if (!dev) {
1353: ret = -ENOMEM;
1354: goto err;
1355: }
1356:
1357: mutex_init(&dev->v4l2_lock);
1358: mutex_init(&dev->vb_queue_lock);
1359: spin_lock_init(&dev->buffer_list_lock);
1360: INIT_LIST_HEAD(&dev->rx_buffer_list);
1361: INIT_LIST_HEAD(&dev->tx_buffer_list);
1362: dev->intf = intf;
1363: dev->dev = &intf->dev;
1364: dev->udev = interface_to_usbdev(intf);
1365: dev->pixelformat = formats[0].pixelformat;
1366: dev->buffersize = formats[0].buffersize;
1367: dev->f_adc = bands_adc_dac[0].rangelow;
1368: dev->f_dac = bands_adc_dac[0].rangelow;
1369: dev->f_rx = bands_rx_tx[0].rangelow;
1370: dev->f_tx = bands_rx_tx[0].rangelow;
1371: set_bit(RX_ADC_FREQUENCY, &dev->flags);
1372: set_bit(TX_DAC_FREQUENCY, &dev->flags);
1373: set_bit(RX_RF_FREQUENCY, &dev->flags);
1374: set_bit(TX_RF_FREQUENCY, &dev->flags);
1375:
1376: /* Detect device */
1377: ret = hackrf_ctrl_msg(dev, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1);
1378: if (ret == 0)
1379: ret = hackrf_ctrl_msg(dev, CMD_VERSION_STRING_READ, 0, 0,
1380: buf, BUF_SIZE);
1381: if (ret) {
1382: dev_err(dev->dev, "Could not detect board\n");
1383: goto err_kfree;
1384: }
1385:
1386: buf[BUF_SIZE - 1] = '\0';
1387: dev_info(dev->dev, "Board ID: %02x\n", u8tmp);
1388: dev_info(dev->dev, "Firmware version: %s\n", buf);
1389:
1390: /* Init vb2 queue structure for receiver */
1391: dev->rx_vb2_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE;
1392: dev->rx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
1393: VB2_READ;
1394: dev->rx_vb2_queue.ops = &hackrf_vb2_ops;
1395: dev->rx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
1396: dev->rx_vb2_queue.drv_priv = dev;
1397: dev->rx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
1398: dev->rx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1399: dev->rx_vb2_queue.lock = &dev->vb_queue_lock;
1400: ret = vb2_queue_init(&dev->rx_vb2_queue);
1401: if (ret) {
1402: dev_err(dev->dev, "Could not initialize rx vb2 queue\n");
1403: goto err_kfree;
1404: }
1405:
1406: /* Init vb2 queue structure for transmitter */
1407: dev->tx_vb2_queue.type = V4L2_BUF_TYPE_SDR_OUTPUT;
1408: dev->tx_vb2_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF |
1409: VB2_WRITE;
1410: dev->tx_vb2_queue.ops = &hackrf_vb2_ops;
1411: dev->tx_vb2_queue.mem_ops = &vb2_vmalloc_memops;
1412: dev->tx_vb2_queue.drv_priv = dev;
1413: dev->tx_vb2_queue.buf_struct_size = sizeof(struct hackrf_buffer);
1414: dev->tx_vb2_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
1415: dev->tx_vb2_queue.lock = &dev->vb_queue_lock;
1416: ret = vb2_queue_init(&dev->tx_vb2_queue);
1417: if (ret) {
1418: dev_err(dev->dev, "Could not initialize tx vb2 queue\n");
1419: goto err_kfree;
1420: }
1421:
1422: /* Register controls for receiver */
1423: v4l2_ctrl_handler_init(&dev->rx_ctrl_handler, 5);
1424: dev->rx_bandwidth_auto = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1425: &hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1426: 0, 1, 0, 1);
1427: dev->rx_bandwidth = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1428: &hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_BANDWIDTH,
1429: 1750000, 28000000, 50000, 1750000);
1430: v4l2_ctrl_auto_cluster(2, &dev->rx_bandwidth_auto, 0, false);
1431: dev->rx_rf_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1432: &hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 12, 12, 0);
1433: dev->rx_lna_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1434: &hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 40, 8, 0);
1435: dev->rx_if_gain = v4l2_ctrl_new_std(&dev->rx_ctrl_handler,
1436: &hackrf_ctrl_ops_rx, V4L2_CID_RF_TUNER_IF_GAIN, 0, 62, 2, 0);
1437: if (dev->rx_ctrl_handler.error) {
1438: ret = dev->rx_ctrl_handler.error;
1439: dev_err(dev->dev, "Could not initialize controls\n");
1440: goto err_v4l2_ctrl_handler_free_rx;
1441: }
1442: v4l2_ctrl_grab(dev->rx_rf_gain, !hackrf_enable_rf_gain_ctrl);
1443: v4l2_ctrl_handler_setup(&dev->rx_ctrl_handler);
1444:
1445: /* Register controls for transmitter */
1446: v4l2_ctrl_handler_init(&dev->tx_ctrl_handler, 4);
1447: dev->tx_bandwidth_auto = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1448: &hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH_AUTO,
1449: 0, 1, 0, 1);
1450: dev->tx_bandwidth = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1451: &hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_BANDWIDTH,
1452: 1750000, 28000000, 50000, 1750000);
1453: v4l2_ctrl_auto_cluster(2, &dev->tx_bandwidth_auto, 0, false);
1454: dev->tx_lna_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1455: &hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 47, 1, 0);
1456: dev->tx_rf_gain = v4l2_ctrl_new_std(&dev->tx_ctrl_handler,
1457: &hackrf_ctrl_ops_tx, V4L2_CID_RF_TUNER_RF_GAIN, 0, 15, 15, 0);
1458: if (dev->tx_ctrl_handler.error) {
1459: ret = dev->tx_ctrl_handler.error;
1460: dev_err(dev->dev, "Could not initialize controls\n");
1461: goto err_v4l2_ctrl_handler_free_tx;
1462: }
1463: v4l2_ctrl_grab(dev->tx_rf_gain, !hackrf_enable_rf_gain_ctrl);
1464: v4l2_ctrl_handler_setup(&dev->tx_ctrl_handler);
1465:
1466: /* Register the v4l2_device structure */
1467: dev->v4l2_dev.release = hackrf_video_release;
1468: ret = v4l2_device_register(&intf->dev, &dev->v4l2_dev);
1469: if (ret) {
1470: dev_err(dev->dev, "Failed to register v4l2-device (%d)\n", ret);
1471: goto err_v4l2_ctrl_handler_free_tx;
1472: }
1473:
1474: /* Init video_device structure for receiver */
1475: dev->rx_vdev = hackrf_template;
1476: dev->rx_vdev.queue = &dev->rx_vb2_queue;
1477: dev->rx_vdev.v4l2_dev = &dev->v4l2_dev;
1478: dev->rx_vdev.ctrl_handler = &dev->rx_ctrl_handler;
1479: dev->rx_vdev.lock = &dev->v4l2_lock;
1480: dev->rx_vdev.vfl_dir = VFL_DIR_RX;
1481: dev->rx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
1482: V4L2_CAP_SDR_CAPTURE | V4L2_CAP_TUNER;
1483: video_set_drvdata(&dev->rx_vdev, dev);
1484: ret = video_register_device(&dev->rx_vdev, VFL_TYPE_SDR, -1);
1485: if (ret) {
1486: dev_err(dev->dev,
1487: "Failed to register as video device (%d)\n", ret);
1488: goto err_v4l2_device_unregister;
1489: }
1490: dev_info(dev->dev, "Registered as %s\n",
1491: video_device_node_name(&dev->rx_vdev));
1492:
1493: /* Init video_device structure for transmitter */
1494: dev->tx_vdev = hackrf_template;
1495: dev->tx_vdev.queue = &dev->tx_vb2_queue;
1496: dev->tx_vdev.v4l2_dev = &dev->v4l2_dev;
1497: dev->tx_vdev.ctrl_handler = &dev->tx_ctrl_handler;
1498: dev->tx_vdev.lock = &dev->v4l2_lock;
1499: dev->tx_vdev.vfl_dir = VFL_DIR_TX;
1500: dev->tx_vdev.device_caps = V4L2_CAP_STREAMING | V4L2_CAP_READWRITE |
1501: V4L2_CAP_SDR_OUTPUT | V4L2_CAP_MODULATOR;
1502: video_set_drvdata(&dev->tx_vdev, dev);
1503: ret = video_register_device(&dev->tx_vdev, VFL_TYPE_SDR, -1);
1504: if (ret) {
1505: dev_err(dev->dev,
1506: "Failed to register as video device (%d)\n", ret);
1507: goto err_video_unregister_device_rx;
1508: }
1509: dev_info(dev->dev, "Registered as %s\n",
1510: video_device_node_name(&dev->tx_vdev));
1511:
1512: dev_notice(dev->dev, "SDR API is still slightly experimental and functionality changes may follow\n");
1513: return 0;
1514: err_video_unregister_device_rx:
1515: video_unregister_device(&dev->rx_vdev);
1516: err_v4l2_device_unregister:
1517: v4l2_device_unregister(&dev->v4l2_dev);
1518: err_v4l2_ctrl_handler_free_tx:
1519: v4l2_ctrl_handler_free(&dev->tx_ctrl_handler);
1520: err_v4l2_ctrl_handler_free_rx:
1521: v4l2_ctrl_handler_free(&dev->rx_ctrl_handler);
1522: err_kfree:
1523: kfree(dev);
1524: err:
1525: dev_dbg(&intf->dev, "failed=%d\n", ret);
1526: return ret;
1527: }
SourceFile:drivers/media/usb/hackrf/hackrf.c]
|
| 17/2 |
2026/02/06 10:40 |
llm |
expert |
0m
Model:
Tokens:
input: 54782
output: 56
thoughts: 4045
Thoughts: **Deep Dive into a V4L2 Driver Vulnerability**
Alright, let's break this down. We've got a classic use-after-free scenario in the `hackrf` driver, specifically triggered when the registration of the transmit video device (`tx_vdev`) fails. The crux of the issue boils down to improper reference counting and an error path that aggressively frees resources without respecting potential outstanding references from userspace.
First, we see the allocation of the `hackrf_dev` structure using `kzalloc`. The critical sequence occurs when `video_register_device` fails for the `tx_vdev`, which triggers an error path. This path then proceeds to unregister both receive and transmit video devices, unregister the V4L2 device, free the control handlers, and *then* call `kfree(dev)`. This `dev` is the `hackrf_dev` struct.
The core problem stems from the fact that `video_register_device` makes the device visible to userspace. If registration of the receive device (`rx_vdev`) succeeds *before* the transmit registration fails, userspace might open the device and begin issuing ioctls. This sets up a race condition. When `video_unregister_device` is called, it clears the `V4L2_FL_REGISTERED` flag. However, if an ioctl is attempted *after* unregistration but *before* the V4L2 device release fully completes, there's a window where `video_devdata` can still return the now-freed `rx_vdev` structure.
The call to `v4l2_ioctl` within the kernel is the trigger. `v4l2_ioctl` uses the `video_devdata` function, which retrieves the `video_device` struct based on the file descriptor's minor number. If the unregistration is incomplete, it's possible for the driver to be in this state. The `v4l2_ioctl` routine then attempts to call the `fops` (file operations) on the device, causing a use-after-free because the `hackrf_dev` structure containing the `video_device` has already been freed. In this case, the `vdev->fops->unlocked_ioctl` call, at a specific offset within the freed memory, leads to the crash. The offset confirms the memory location of the fops.
The kernel correctly increases the refcount of `vdev->dev` in `v4l2_open` via `video_get`, ensuring release is done properly. But, in this error path, `kfree` is called directly, ignoring this refcount, and the refcount of `v4l2_dev` itself. We can confirm this is incorrect.
Digging further, the `hackrf_dev` itself contains a `v4l2_dev` which is also refcounted. The driver *does* have a release callback, `hackrf_video_release`. It correctly calls `v4l2_device_unregister` *and then* `kfree(dev)`. The error path is trying to do both, which is doubly problematic.
In the correct path, the `v4l2_dev` refcount is used to manage the lifetime of the `hackrf_dev`, and then unregistration unregisters subdevs and clears the `v4l2_dev->dev` pointer. The references to the devices will be dropped, and `v4l2_device_release` will be called, in turn calling the custom `hackrf_video_release` function, which would then call `v4l2_device_unregister` and ultimately `kfree(dev)`.
The fix is clear: the error path *must* utilize `v4l2_device_put(&dev->v4l2_dev)` instead of directly calling `kfree(dev)`. We need to ensure that the lifetime of the `hackrf_dev` structure is tied to the reference count maintained by the V4L2 device and its associated sub-devices.
|
| 18/2 |
2026/02/06 10:40 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:drivers/media/v4l2-core/v4l2-device.c IncludeLines:true Name:v4l2_device_register]
Results: map[SourceCode: 17: int v4l2_device_register(struct device *dev, struct v4l2_device *v4l2_dev)
18: {
19: if (v4l2_dev == NULL)
20: return -EINVAL;
21:
22: INIT_LIST_HEAD(&v4l2_dev->subdevs);
23: spin_lock_init(&v4l2_dev->lock);
24: v4l2_prio_init(&v4l2_dev->prio);
25: kref_init(&v4l2_dev->ref);
26: get_device(dev);
27: v4l2_dev->dev = dev;
28: if (dev == NULL) {
29: /* If dev == NULL, then name must be filled in by the caller */
30: if (WARN_ON(!v4l2_dev->name[0]))
31: return -EINVAL;
32: return 0;
33: }
34:
35: /* Set name to driver name + device name if it is empty. */
36: if (!v4l2_dev->name[0])
37: snprintf(v4l2_dev->name, sizeof(v4l2_dev->name), "%s %s",
38: dev->driver->name, dev_name(dev));
39: if (!dev_get_drvdata(dev))
40: dev_set_drvdata(dev, v4l2_dev);
41: return 0;
42: }
SourceFile:drivers/media/v4l2-core/v4l2-device.c]
|
| 19/2 |
2026/02/06 10:40 |
llm |
expert |
0m
Model:
Tokens:
input: 60238
output: 19
thoughts: 1110
Thoughts: **Analysis of a Potential Use-After-Free Vulnerability in the HackRF Driver**
Okay, let's break this down. Line 25 confirms `kref_init(&v4l2_dev->ref)` is called early, indicating proper `v4l2_device_put` usage is required after `v4l2_device_register`. Now, the `hackrf_probe` function registers the V4L2 device. If registration *fails* in `hackrf_probe`, control goes to the error handling path, `err_v4l2_ctrl_handler_free_tx`. However, if it *succeeds* and the video devices are registered, it proceeds with other registration steps. If `video_register_device` fails down the line, we jump to the respective error paths such as `err_video_unregister_device_rx` or `err_v4l2_device_unregister`. Ultimately, both those error paths lead to `err_kfree`, which calls `kfree(dev)`. Here's where it gets interesting: calling `kfree(dev)` is wrong if `v4l2_device_register` was previously called. The reason is because `v4l2_device_get` might have been called, increasing the reference count.
Specifically, `video_register_device` calls `v4l2_device_get(vdev->v4l2_dev)`. If the first registration `video_register_device(&dev->rx_vdev, ...)` succeeds, the `v4l2_dev`'s refcount is 2. Then, registration of the second device `video_register_device(&dev->tx_vdev, ...)` fails. In this failing case, the error path calls `video_unregister_device(&dev->rx_vdev)`. The `video_unregister_device` in turn calls `device_unregister(&vdev->dev)`. When `vdev->dev` is finally released (maybe later by userspace), it calls `v4l2_device_put(v4l2_dev)`. The critical problem is that `hackrf_probe` calls `kfree(dev)` *immediately*. When `v4l2_device_put` *eventually* decrements the refcount to zero, it calls `hackrf_video_release`, which calls `kfree(dev)` *again* – a classic double-free – or attempts to access `dev` which is already freed, leading to a Use-After-Free (UAF).
And the report seems to show precisely this, a UAF within `v4l2_ioctl`. `v4l2_ioctl` is called from userspace. It obtains `vdev` from `video_devdata`. Here, `vdev` is `&dev->rx_vdev`. Now, `dev` has been freed by the `kfree(dev)` call in `hackrf_probe`. So, when the code attempts to access `vdev->fops`, it's a UAF.
The report's details are consistent and confirm the issue.
The KASAN details about page allocation and reuse are just normal artifacts of how large objects (8k is two pages) are handled. The pages were likely used for something else first, but it doesn't contradict the slab UAF. The report specifies the buggy address is 200 bytes inside the 8192-byte object at address `ffff888053a04000`, which is consistent with the access to `vdev->fops`.
Let's confirm the call stacks, to be certain:
* **Access:** `v4l2_ioctl` -> `vdev->fops` (offset 200 in `hackrf_dev`).
* **Allocation:** `hackrf_probe` -> `kzalloc(sizeof(*dev), ...)` (line 1351).
* **Free:** `hackrf_probe` -> `kfree(dev)` (line 1523).
All three stacks are within the same subsystems (media/usb/hackrf and v4l2-core), and the object type is `struct hackrf_dev`. The report is self-consistent and valid.
One more thing. The report is triggered by `v4l_id`.
`v4l_id` is part of `udev` and runs when a new device is added. So when `hackrf_probe` registers the first video device, `udev` triggers `v4l_id`. It opens the device and calls ioctls. Meanwhile, `hackrf_probe` tries to register the second video device.
|
| 20/2 |
2026/02/06 10:41 |
tool |
set-results |
0m
Args: map[Actionable:true Confident:true]
Results: map[Actionable:true Confident:true]
|
| 21/2 |
2026/02/06 10:41 |
llm |
expert |
0m
Model:
Tokens:
input: 62409
output: 722
thoughts: 13
Thoughts: Okay, here's the summary, framed as your thoughts after analyzing the text, targeted at an expert:
**Finalizing the Response**
Alright, the deep dive is done. I've processed the entire analysis. Now, I'm at the point where I synthesize everything and formulate the final response. There's no more grinding through the data, no more refinement of the logic. It's time to package the findings into a clear and concise presentation. Time to deliver the goods.
|