devres: warn about managed memory still held by open files at unbind
Subsystems (3)
cover devres: warn about managed memory still held by open files at unbind
Driver state that an open file can reach, such as a struct cdev, video_device or miscdevice embedded in it, must not be devm memory: the file outlives the unbind, and the next operation on it, typically close(), is a use-after-free. This keeps being fixed one driver at a time: commit 44f3468a0aef ("gpio: sloppy-logic-analyzer: fix use-after-free via debugfs trigger on unbind") this summer, a debugfs write racing unbind on devm private data; commit 7d6358ab0286 ("media: cx231xx: fix devres lifetime") in March, one of a sweep of the related wrong-device lifetime. In 7.4-rc1 cx231xx still has the shape: its state, with four video_devices and its mutex embedded, is devm_kzalloc()'d against the USB interface, and disconnect defers release to close() while devres frees the state at unbind; a fix is under review ("[PATCH 0/6] media: cx231xx: make USB disconnect teardown safe", Nick Faro, linux-media, 2026-08-27, changes requested). xilinx_hwicap embeds its struct cdev in devm memory the same way.
This series adds CONFIG_DEBUG_DEVRES_REFS, a runtime debug check rather than a static rule. From device_unbind_cleanup(), before devres_release_all(), it snapshots the device's managed allocations, walks every task's fd table once, and WARNs when an open file still points into an allocation about to be freed, through file->private_data, the inode's i_private, the inode's cdev for a character device, or an object a subsystem names through a small hook. Such a pointer dangles once release runs; it is a use-after-free if anything dereferences it afterwards, which for private_data is any operation, for a cdev its release on close, and for a debugfs file a new open or an unguarded release. A hit on a live debugfs file is decided after release instead, because many drivers remove their debugfs files through a devres action; debugfs_file_revoked() and debugfs_file_release_safe() (patch 1, inert until patch 2 adds the Kconfig symbol) tell the check whether debugfs has cut the file off and whether its release can still reach the data.
The walks run on a kernel thread the unbinding task waits for, and no file reference is kept across release. A reference the walk holds becomes the last one if the owner closes the file meanwhile; dropped from a user task its release would be queued behind unbind, where a devres action that waits for the close (snd_card_free()) deadlocks; dropped from a kernel thread it goes to the delayed-fput work. What remains, and I would like your view on it (question 5): that work drains one global list last-in-first-out with all its runs serialized, so a release there that needs a lock unbind holds (a usbfs close takes the USB parent lock a USB interface unbind holds) stalls every later delayed close, including one such an action is waiting for; without this option that close would have run from its owner's task work. The cross-vendor review this went through found the first of these.
Subsystems whose files do not reach the driver object through those pointers register the hook, keyed on their file_operations; V4L2 is the first (patch 3), naming the video_device; its drvdata is not named, since reaching it means dereferencing a video_device that may already be freed. The hook is a workaround. The cdev route catches a struct cdev embedded in managed memory (an open file pins the cdev's kobject, so inode->i_cdev is still there at unbind) but not these: V4L2's cdev is a separate cdev_alloc() with no kobject parent, and misc's is one shared cdev, so neither leads to the driver's allocation. Parenting V4L2's cdev to the video device, as mc-devnode and cec do with cdev_device_add(), would make the cdev hold the device whose release deletes the cdev; that is a media-core change with regression risk, not something a debug option should carry. A DRM hook is deferred: devm_drm_dev_alloc() memory is kzalloc()'d, so the expected yield is low.
Testing, one boot of an x86 KVM guest with KASAN, on the development branch (identical to this series except for two extra test vehicles): the test driver in patch 4 (a devm-backed misc node, a devm-embedded cdev node, a refcounted control node and a devres-removed debugfs file) and a cx231xx-shaped V4L2 vehicle WARN once per dangling allocation before the unbind returns (two for the test driver, one for the V4L2 vehicle), after which KASAN reports use-after-frees on close of the misc and cdev nodes and, for the V4L2 vehicle, 38 reports across a read, an ioctl and close; the gpio sloppy logic analyzer, instantiated through a fake-gpiochip glue module and unbound with four debugfs files held open, produces four info lines and no WARN, its reads return -EIO and nothing fires on close; vivid, as a negative control, is silent. The V4L2 vehicle and the glue are in the branch below, not in the series. Also compiled: the option off; DEBUG_FS=n; VIDEO_DEV=m with DEVM_REFS_TEST=m (videodev.ko and the test module through modpost); W=1 clean on devres.o, dd.o, v4l2-dev.o, debugfs/file.o and the test driver. Only the all-builtin configuration was booted. Not exercised: the two phase-2 WARN branches (a removed but unguarded, or a still-live, debugfs file) and the no-memory fallback.
Limitations, also in the Kconfig help: only files in task fd tables are seen; the check finds pointers that are dangling at that moment, not teardown races, nor whether a debugfs removal action ran before or after the free; a managed allocation whose release waits for its files to close first (an ALSA card) is not about to be freed, so a hit on it is a false positive; and the walk is linear in threads times fd tables and costs every unbind and failed probe (not deferral).
Questions for review:
1. Is driver core the right home for this, or should it be per-subsystem (misc, V4L2) with no generic walk?
2. Is a hook keyed on file_operations acceptable, or should the answer for V4L2 be the cdev_device_add() conversion despite its risk?
3. Is the info/WARN split for removed-and-guarded versus unguarded debugfs files the right call?
4. Should the test be a module plus a tools/testing/selftests script rather than a module alone? The check needs fds held in a task fd table across the unbind, which KUnit cannot do naturally.
5. The walk must hold a reference on each file it inspects, so a racing close can make it the last holder; routing that release through the delayed-fput worker avoids the task-work deadlock but leaves the serialized-worker case above. Is that acceptable for a debug option, or is there a way to look at a file's pointers without the walk ever owning the last reference?
Per Documentation/process/generated-content.rst: the code, the test vehicles and the first drafts of these messages were written with Claude (Anthropic) under my direction, from prompts that specified the mechanism, the call site, the lock context and the debugfs handling; the series was then revised through repeated model-assisted review passes against the kernel source, including one by reviewers from three other model families, with the fixes mine to judge. I have read and can answer for every line. Where I most expect to be wrong is in the Kconfig's list of limitations and in the choice to put the hook in driver core at all.
This series: https://github.com/modelmiser/linux/tree/devres-refs-v1
Development history (incl. the two extra vehicles and the review fix batches): https://github.com/modelmiser/linux/tree/devres-refs-dev
Guest harness, its logs, and the review record:
https://github.com/modelmiser/devres-refs-support
linux-media is Cc'd on the whole series because the hook API exists for V4L2; linux-doc on patch 2 for devres.rst.
.../driver-api/driver-model/devres.rst | 18 + drivers/base/Kconfig | 64 ++ drivers/base/base.h | 38 + drivers/base/dd.c | 14 +- drivers/base/devres.c | 667 ++++++++++++++++++ drivers/base/test/Kconfig | 15 + drivers/base/test/Makefile | 2 + drivers/base/test/devm_refs_test.c | 323 +++++++++ drivers/media/v4l2-core/v4l2-dev.c | 31 + fs/debugfs/file.c | 112 +++ include/linux/debugfs.h | 29 + include/linux/device/devres.h | 58 ++ 12 files changed, 1367 insertions(+), 4 deletions(-) create mode 100644 drivers/base/test/devm_refs_test.c
Signature · 1 line
2.43.0
RFC PATCH 1/4 debugfs: add debugfs_file_revoked() for debugging aids
A debugging aid that finds a stale pointer behind an open debugfs file needs to know whether debugfs itself has already cut that file off from its driver, and if so which release callback close() will still run. That knowledge is debugfs-internal: the proxy file_operations identities, the removal state of the dentry, and which of debugfs's own _unsafe helpers take the removal guard or copy their data at open.
Add debugfs_file_revoked(), built only with CONFIG_DEBUG_DEVRES_REFS (added by the next patch, its only user) and not exported, since that user is built in. It returns true for a removed file created through the full proxy, the short proxy, or one of debugfs's guarded helpers (the DEFINE_DEBUGFS_ATTRIBUTE() family, blobs, bools, strings) or one that copies its data at open (u32 arrays), and hands back the file_operations whose release callback will still run. A file created with an _unsafe variant and the driver's own file_operations gets no guard from debugfs, and the function returns false for it.
Written with Claude (Anthropic) under my direction; see the cover letter for the disclosure required by Documentation/process/generated-content.rst.
--- fs/debugfs/file.c | 112 ++++++++++++++++++++++++++++++++++++++++ include/linux/debugfs.h | 29 +++++++++++ 2 files changed, 141 insertions(+)
fs/debugfs/file.c +112 -0
@@ -11,6 +11,7 @@#include <linux/module.h> #include <linux/fs.h> +#include <linux/magic.h> #include <linux/seq_file.h> #include <linux/pagemap.h> #include <linux/debugfs.h>
@@ -1373,3 +1374,114 @@ void debugfs_create_devm_seqfile(struct device *dev, const char *name, &debugfs_devm_entry_ops); }EXPORT_SYMBOL_GPL (debugfs_create_devm_seqfile); + +#ifdef CONFIG_DEBUG_DEVRES_REFS +/* +* debugfs's own file_operations for _unsafe files on which nothing after +* open can reach the driver's data: either every operation takes the +* removal guard (debugfs_file_get()), or the data is copied at open. +*/ +static bool debugfs_unsafe_fops_safe_after_removal (const struct file_operations *fops) +{ +if (fops == &fops_blob || fops == &fops_str || + fops == &fops_bool || fops == &fops_bool_ro || fops == &fops_bool_wo) +return true; +if (fops == &u32_array_fops)/* copies the array at open */ +return true; +/* +* DEFINE_DEBUGFS_ATTRIBUTE(): read/write go through +* debugfs_file_get(), release only frees the simple_attr, and the +* macro sets no other operation at all. +*/ +return fops->read == debugfs_attr_read && + (fops->write == debugfs_attr_write || + fops->write == debugfs_attr_write_signed) && + fops->release == simple_attr_release && + !fops->llseek && !fops->read_iter && !fops->write_iter && + !fops->iopoll && !fops->iterate_shared && !fops->poll && + !fops->unlocked_ioctl && !fops->compat_ioctl && !fops->mmap && + !fops->mmap_prepare && !fops->flush && !fops->fsync && + !fops->fasync && !fops->lock && !fops->get_unmapped_area && + !fops->check_flags && !fops->flock && !fops->splice_write && + !fops->splice_read && !fops->splice_eof && !fops->setlease && + !fops->fallocate && !fops->show_fdinfo && + !fops->copy_file_range && !fops->remap_file_range && + !fops->fadvise && !fops->uring_cmd && !fops->uring_cmd_iopoll && +#ifndef CONFIG_MMU + !fops->mmap_capabilities && +#endif + !fops->init_dma_buf_io_ctx && !fops->fop_flags; +/* Keep in step with struct file_operations in include/linux/fs.h. */ +} + +/** +* debugfs_file_release_safe - will close() of a removed file leave the +* driver's data alone? +* @fops: the file_operations debugfs_file_revoked() handed back, or NULL +* +* Return: true if @fops has no release callback, or one of the generic +* ones that only free what open() allocated (seq_file, simple_attr, u32 +* array). A driver's own release may dereference i_private or +* private_data; full_proxy_release() documents that it must not, but +* nothing enforces it. +*/ +bool debugfs_file_release_safe (const struct file_operations *fops) +{ +if (!fops || !fops->release) +return true; +return fops->release == single_release || + fops->release == seq_release || + fops->release == simple_attr_release || + fops->release == u32_array_release; +} + +/** +* debugfs_file_revoked - has debugfs cut @file off from its driver? +* @file: an open file, held by the caller +* @real_fops: set to the file_operations close() will still consult, or +* NULL for a short-fops proxy; callers must still test +* ->release, which may be NULL +* +* For debugging aids that find a stale pointer behind an open debugfs file +* after the file was removed; not for use elsewhere. +* +* Return: true if @file is a removed debugfs file on which no further +* operation can reach the driver's data: one created through the full +* proxy (debugfs_create_file() and the helpers built on it), on which +* read/write/llseek/ioctl fail with -EIO and poll reports EPOLLHUP (see +* __debugfs_file_get()); or one of +* the _unsafe files whose read/write callbacks are debugfs's own guarded +* ones (the DEFINE_DEBUGFS_ATTRIBUTE() family, blobs, bools, strings) or +* which copy their data at open (u32 arrays). close() still runs the real +* release callback on such a file, through full_proxy_release() for +* proxied files and directly otherwise, so @real_fops names it. A file +* created with an _unsafe variant and the driver's own file_operations +* gets no guard from debugfs, and this returns false. +*/ +bool debugfs_file_revoked (const struct file *file, +const struct file_operations **real_fops) +{ +const struct debugfs_fsdata *fsd; + + *real_fops =NULL ; + +if (!d_unlinked (file->f_path.dentry)) +return false; + +if (file->f_op == &debugfs_full_proxy_file_operations) { +/* Populated by full_proxy_open_regular(), pinned by the file. */ + fsd =READ_ONCE (file->f_path.dentry->d_fsdata); +if (fsd) + *real_fops = fsd->real_fops; +return true; + } +if (file->f_op == &debugfs_full_short_proxy_file_operations) +return true;/* short fops: no release callback at all */ +if (file_inode (file)->i_sb->s_magic ==DEBUGFS_MAGIC && +debugfs_unsafe_fops_safe_after_removal (file->f_op)) { + *real_fops = file->f_op; +return true; + } +return false; +} +#endif /* CONFIG_DEBUG_DEVRES_REFS */
include/linux/debugfs.h +29 -0
@@ -166,6 +166,23 @@ void *debugfs_get_aux(const struct file *file);int debugfs_file_get (struct dentry *dentry);void debugfs_file_put (struct dentry *dentry); +#ifdef CONFIG_DEBUG_DEVRES_REFS +bool debugfs_file_revoked (const struct file *file, +const struct file_operations **real_fops); +bool debugfs_file_release_safe (const struct file_operations *fops); +#else +static inline bool debugfs_file_revoked (const struct file *file, +const struct file_operations **real_fops) +{ + *real_fops =NULL ; +return false; +} + +static inline bool debugfs_file_release_safe (const struct file_operations *fops) +{ +return true; +} +#endif ssize_t debugfs_attr_read (struct file *file,char __user *buf,size_t len,loff_t *ppos);
@@ -336,6 +353,18 @@ static inline int debugfs_file_get(struct dentry *dentry)static inline void debugfs_file_put (struct dentry *dentry) { } +static inline bool debugfs_file_revoked (const struct file *file, +const struct file_operations **real_fops) +{ + *real_fops =NULL ; +return false; +} + +static inline bool debugfs_file_release_safe (const struct file_operations *fops) +{ +return true; +} +static inline ssize_t debugfs_attr_read (struct file *file,char __user *buf,size_t len,loff_t *ppos) {
Signature · 1 line
2.43.0
RFC PATCH 2/4 devres: add DEBUG_DEVRES_REFS to warn about managed memory still held by open files
In reply to Chad AldredaMemory from devm_kzalloc() is freed when the driver is unbound, but a device node that user space holds open outlives the unbind. Driver state that an open file can reach, such as an embedded struct cdev, video_device or miscdevice, must therefore not be managed memory; when it is, the next file operation, typically close(), is a use-after-free. The pattern is long-standing and is still fixed driver by driver. In mainline today cx231xx allocates its state, with four video_devices and its mutex embedded, with devm_kzalloc() against the USB interface, defers its release to close() when a node is open, and devres frees the state at unbind regardless; xilinx_hwicap embeds its struct cdev in devm memory the same way.
Add a runtime debug check rather than a static rule: from device_unbind_cleanup(), with device_lock held, before devres_release_all(), snapshot the device's managed allocations, walk every thread's open files once, and warn when a file's private_data, its inode's i_private, its inode's cdev for a character device, or an object a subsystem names through a small hook still points into an allocation about to be freed. Such a pointer dangles once the memory is freed; it is a use-after-free if anything dereferences it afterwards, which for private_data is any operation, for a cdev its release on close, and for a debugfs file a new open or an unguarded release. One WARN backtrace is printed per allocation; further holders of it get one line each.
The cdev route works because an open non-O_PATH chrdev file holds a reference on its cdev's kobject from chrdev_open(), and inode->i_cdev is cleared only when that kobject is released, so the pointer is stable here even after cdev_del(); it is compared, never dereferenced. It only helps when the struct cdev itself is in managed memory: V4L2's cdev is a separate cdev_alloc() with no kobject parent and misc's is one shared cdev, so neither leads to the driver's allocation, which is what the hook is for. The next patch adds V4L2's.
debugfs files need care, because many drivers remove theirs through a devres action that runs inside devres_release_all(). A hit on a debugfs file that remove() already took down is decided at once; a hit on a live one is recorded as (pid, fd, file address) and looked up again after release. If debugfs has revoked the file by then (debugfs_file_revoked()) and its release callback is one that cannot touch the data (debugfs_file_release_safe()), it is reported at info level; if the release is the driver's own it is a WARN naming it, and so is a file still live or removed with unguarded file_operations.
The check runs only from the unbind and failed-probe paths, not on probe deferral and never from devres_release_all() itself, which is also reached from device_release() and so from any context in which a final put_device() is legal. The walks run on a kernel thread the unbinding task waits for: a file reference the walk holds becomes the last one if the owner closes the file meanwhile, and dropped from a user task its release would be queued to that task's task work, after unbind, where a devres action waiting for the close (snd_card_free()) would deadlock under device_lock; dropped from a kernel thread it goes to the delayed-fput work instead. What remains: that work drains one global list last-in-first-out with all its runs serialized, so a release there that needs a lock unbind holds (a usbfs close takes the USB parent lock a USB interface unbind holds) stalls every later delayed close, including one such an action is waiting for; without this option that close would have run from its owner's task work. No file reference is kept across release. Fd tables are walked once each, de-duplicated by (owning task, table pointer) with a reference on the task only; no reference is ever taken on another task's fd table, since dropping the last one would run that task's file releases in the walk.
Limitations, also stated in the Kconfig help: only files in task fd tables are seen; the check finds pointers that are dangling at that moment, not teardown races, nor whether a debugfs removal action ran before or after the free; a managed allocation whose release waits for its files to close first (an ALSA card) is not about to be freed, so a hit on it is a false positive; and the walk is linear in threads times fd tables and costs every unbind and failed probe.
Written with Claude (Anthropic) under my direction; see the cover letter for the disclosure required by Documentation/process/generated-content.rst.
--- .../driver-api/driver-model/devres.rst | 18 + drivers/base/Kconfig | 64 ++ drivers/base/base.h | 38 + drivers/base/dd.c | 14 +- drivers/base/devres.c | 667 ++++++++++++++++++ include/linux/device/devres.h | 58 ++ 6 files changed, 855 insertions(+), 4 deletions(-)
Documentation/driver-api/driver-model/devres.rst +18 -0
@@ -221,6 +221,24 @@ in lib/devres.c. All devres interface functions can be called without context if the right gfp mask is given. +Managed memory is freed on driver unbind regardless of whether anything +else still refers to it. In particular a device node that user space +holds open outlives the unbind, so driver state that an open file can +reach - a struct cdev, video_device or miscdevice embedded in it - must +not live in devm_kzalloc()'d memory. Allocate such state with kzalloc() +and free it from the release callback of the object that user space +holds, or from a refcount dropped on last close. debugfs private data +may be managed memory only if the file is created through +debugfs_create_file() or one of debugfs's typed helpers such as +debugfs_create_u32() or debugfs_create_blob(), not through +debugfs_create_file_unsafe() with the driver's own file_operations, so +that debugfs refuses operations on it once removed, and the file is +removed before the allocation is freed: in the remove callback, or by a +devres action registered after that allocation. +CONFIG_DEBUG_DEVRES_REFS reports, at driver unbind or after a failed +probe, open files that still point into a managed allocation about to +be freed; its Kconfig help text lists what it can and cannot see. + 5. Overhead -----------
drivers/base/Kconfig +64 -0
70 lines not on this page · raw message
drivers/base/base.h +38 -0
@@ -10,6 +10,7 @@* shared outside of the drivers/base/ directory. * */ +#include <linux/completion.h> #include <linux/notifier.h> /**
@@ -242,6 +243,43 @@ void devres_for_each_res(struct device *dev, dr_release_t release,void (*fn)(struct device *,void *,void *), void *data);int devres_release_all (struct device *dev); +/* CONFIG_DEBUG_DEVRES_REFS state carried across devres_release_all() */ +struct devres_seen_table { +struct task_struct *task; +struct files_struct *files; +}; + +struct devres_open_file_check { +#ifdef CONFIG_DEBUG_DEVRES_REFS +struct device *dev; +struct devres_region *regions; +unsigned int nr; +struct devres_open_file_hook **hooks; +unsigned int nhooks; +struct devres_seen_table *seen; +unsigned int nseen, maxseen; +struct devres_pending_ref *pending; +unsigned int npending, maxpending; +struct completion done; +#endif +}; + +#ifdef CONFIG_DEBUG_DEVRES_REFS +void devres_check_open_files (struct device *dev, +struct devres_open_file_check *chk); +void devres_finish_open_file_check (struct device *dev, +struct devres_open_file_check *chk); +#else +static inline void devres_check_open_files (struct device *dev, +struct devres_open_file_check *chk) +{ +} + +static inline void devres_finish_open_file_check (struct device *dev, +struct devres_open_file_check *chk) +{ +} +#endif void device_block_probing (void );void device_unblock_probing (void );void deferred_probe_extend_timeout (void );
drivers/base/dd.c +10 -4
@@ -591,11 +591,16 @@ static ssize_t state_synced_show(struct device *dev, }static DEVICE_ATTR_RW (state_synced); -static void device_unbind_cleanup (struct device *dev) +static void device_unbind_cleanup (struct device *dev,bool check_open_files) { +struct devres_open_file_check chk = {}; +if (dev->driver->p_cb.post_unbind_rust) dev->driver->p_cb.post_unbind_rust (dev); +if (check_open_files) +devres_check_open_files (dev, &chk);devres_release_all (dev); +devres_finish_open_file_check (dev, &chk);arch_teardown_dma_ops (dev);kfree (dev->dma_range_map); dev->dma_range_map =NULL ;
@@ -744,7 +749,7 @@ static int really_probe(struct device *dev, const struct device_driver *drv)driver_sysfs_remove (dev);if (dev->bus && dev->bus->dma_cleanup) dev->bus->dma_cleanup (dev); -device_unbind_cleanup (dev); +device_unbind_cleanup (dev, true); goto re_probe; }
@@ -770,7 +775,8 @@ static int really_probe(struct device *dev, const struct device_driver *drv) dev->bus->dma_cleanup (dev); pinctrl_bind_failed:device_links_no_driver (dev); -device_unbind_cleanup (dev); +/* A driver's own error arrives here negated (see above); either sign is a deferral. */ +device_unbind_cleanup (dev, ret != -EPROBE_DEFER && ret !=EPROBE_DEFER ); done:return ret; }
@@ -1359,7 +1365,7 @@ static void __device_release_driver(struct device *dev, struct device *parent)if (dev->bus && dev->bus->dma_cleanup) dev->bus->dma_cleanup (dev); -device_unbind_cleanup (dev); +device_unbind_cleanup (dev, true);device_links_driver_cleanup (dev);klist_remove (&dev->p->knode_driver);
drivers/base/devres.c +667 -0
679 lines not on this page · raw message
include/linux/device/devres.h +58 -0
68 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH 3/4 media: v4l2-dev: name the video_device behind an open file for DEBUG_DEVRES_REFS
In reply to Chad AldredaAn open V4L2 file points at a per-open v4l2_fh, and the driver state, with its video_device embedded, is reachable only through video_devdata(). The DEBUG_DEVRES_REFS check therefore cannot see the most common shape of the bug it looks for, a video_device embedded in devm memory, without help.
Register a devres_open_file_hook on v4l2_fops that names video_devdata(file), a lookup in video_devices[] that does not touch the video_device itself. The driver state behind video_get_drvdata() is not
named: reaching it means dereferencing the video_device, which may sit in managed memory already freed by an earlier unbind, the very thing the check reports. The hook object is defined unconditionally and the registration calls are stubs when the option is off. It is registered last in videodev_init(), so no failure can leave it registered, and unregistered first in videodev_exit(); a walk in progress pins the module.
Parenting the V4L2 cdev to the video device with cdev_device_add(), as mc-devnode and cec do, so that a generic kobject route could be used instead, was considered and rejected: V4L2 deletes its cdev from the device's own release callback, and a parent link would make the cdev hold the device and the device wait for the cdev. For V4L2 that is a media-core change with regression risk, not something a debug option should carry.
Written with Claude (Anthropic) under my direction; see the cover letter for the disclosure required by Documentation/process/generated-content.rst.
--- drivers/media/v4l2-core/v4l2-dev.c | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)
drivers/media/v4l2-core/v4l2-dev.c +31 -0
@@ -1235,6 +1235,32 @@ EXPORT_SYMBOL_GPL(video_device_pipeline);/* * Initialise video for linux */ +/* +* For CONFIG_DEBUG_DEVRES_REFS: an open V4L2 file keeps its struct +* video_device alive via video_get(), and reaches it only through +* video_devdata(), a lookup in video_devices[] that does not touch the +* video_device itself. The driver's state behind video_get_drvdata() is +* not named: reaching it means dereferencing the video_device, which +* may itself sit in managed memory already freed by an earlier unbind. +* Defined unconditionally; the registration calls are stubs when the +* option is off. +*/ +static const void *v4l2_devres_open_file_holder (struct file *file, +unsigned int idx, +const char **what) +{ +if (idx) +return NULL ; + *what ="video_devdata" ; +return video_devdata (file); +} + +static struct devres_open_file_hook v4l2_devres_open_file_hook = { + .fops = &v4l2_fops, + .owner =THIS_MODULE , + .holder = v4l2_devres_open_file_holder, +}; +static int __init videodev_init (void ) {dev_t dev =MKDEV (VIDEO_MAJOR ,0 );
@@ -1255,6 +1281,9 @@ static int __init videodev_init(void)return -EIO ; } +/* Last, so no failure above can leave the hook registered. */ +WARN_ON (devres_register_open_file_hook (&v4l2_devres_open_file_hook)); +return 0 ; }
@@ -1262,6 +1291,8 @@ static void __exit videodev_exit(void) {dev_t dev =MKDEV (VIDEO_MAJOR ,0 ); +devres_unregister_open_file_hook (&v4l2_devres_open_file_hook); +class_unregister (&video_class);unregister_chrdev_region (dev,VIDEO_NUM_DEVICES );debugfs_remove_recursive (v4l2_debugfs_root_dir);
Signature · 1 line
2.43.0
RFC PATCH 4/4 drivers: base: test: add a vehicle for DEBUG_DEVRES_REFS
In reply to Chad AldredaRegister a platform device whose driver exposes two misc devices, one character device and one debugfs file: /dev/devm_refs_bad keeps its state, with the miscdevice embedded, in devm memory; /dev/devm_refs_good keeps refcounted state freed on last close; /dev/devm_refs_cdev is a struct cdev embedded in devm memory; the debugfs file bad_magic points into the devm state and is removed by a devres action registered after that allocation. The driver depends on DEBUG_FS for that file.
Unbinding the device with all four held open must warn exactly twice, for the devm-backed misc node and for the cdev, and report the debugfs file at info level after release; closing the bad node and the cdev node afterwards are use-after-frees that KASAN reports independently (the cdev close reads the freed cdev in cdev_put() and then writes its kobject refcount in kobject_put(), so run this under KASAN only). Rebinding and unbinding with nothing open must be silent.
Written with Claude (Anthropic) under my direction; see the cover letter for the disclosure required by Documentation/process/generated-content.rst.
--- drivers/base/test/Kconfig | 15 ++ drivers/base/test/Makefile | 2 + drivers/base/test/devm_refs_test.c | 323 +++++++++++++++++++++++++++++ 3 files changed, 340 insertions(+) create mode 100644 drivers/base/test/devm_refs_test.c
drivers/base/test/Kconfig +15 -0
@@ -23,3 +23,18 @@ config DRIVER_SWNODE_KUNIT_TEST tristate "KUnit Tests for software node fw_devlink links" if !KUNIT_ALL_TESTS depends on KUNIT default KUNIT_ALL_TESTS + +config DEVM_REFS_TEST + tristate "Test driver for DEBUG_DEVRES_REFS" + depends on DEBUG_DEVRES_REFS && DEBUG_FS + help + Registers a platform device whose driver exposes /dev/devm_refs_bad + (state in devm memory, freed on unbind while open), + /dev/devm_refs_good (refcounted state), /dev/devm_refs_cdev (a + struct cdev embedded in devm memory) and a debugfs file bad_magic + whose data is that devm memory and whose removal is a devres + action. Unbinding with all four open must warn once for the bad + node and once for the cdev, and report the debugfs file at info + level after release. See drivers/base/test/devm_refs_test.c. + + If unsure say N.
drivers/base/test/Makefile +2 -0
@@ -8,3 +8,5 @@ obj-$(CONFIG_DRIVER_PE_KUNIT_TEST) += property-entry-test.o CFLAGS_property-entry-test.o += $(DISABLE_STRUCTLEAK_PLUGIN) obj-$(CONFIG_DRIVER_SWNODE_KUNIT_TEST) += swnode-devlink-test.o + +obj-$(CONFIG_DEVM_REFS_TEST) += devm_refs_test.o
drivers/base/test/devm_refs_test.c new file +323 -0
323 lines not on this page · raw message
Signature · 1 line
2.43.0
Quoted 106 lines · Chad Aldreda
Driver state that an open file can reach, such as a struct cdev,
video_deviceor miscdevice embedded in it, must not be devm memory: the file outlives the unbind, and the next operation on it, typicallyclose(), is a use-after-free. This keeps being fixed one driver at a time: commit44f3468a0aef("gpio: sloppy-logic-analyzer: fix use-after-free via debugfs trigger on unbind") this summer, a debugfs write racing unbind on devm private data; commit7d6358ab0286("media: cx231xx: fix devres lifetime") in March, one of a sweep of the related wrong-device lifetime. In 7.4-rc1 cx231xx still has the shape: its state, with fourvideo_devicesand its mutex embedded, is devm_kzalloc()'d against the USB interface, and disconnect defers release toclose()while devres frees the state at unbind; a fix is under review ("[PATCH 0/6] media: cx231xx: make USB disconnect teardown safe", Nick Faro, linux-media, 2026-08-27, changes requested).xilinx_hwicapembeds its struct cdev in devm memory the same way.This series adds
CONFIG_DEBUG_DEVRES_REFS, a runtime debug check rather than a static rule. Fromdevice_unbind_cleanup(), beforedevres_release_all(), it snapshots the device's managed allocations, walks every task's fd table once, and WARNs when an open file still points into an allocation about to be freed, throughfile->private_data, the inode'si_private, the inode's cdev for a character device, or an object a subsystem names through a small hook. Such a pointer dangles once release runs; it is a use-after-free if anything dereferences it afterwards, which forprivate_datais any operation, for a cdev its release on close, and for a debugfs file a new open or an unguarded release. A hit on a live debugfs file is decided after release instead, because many drivers remove their debugfs files through a devres action;debugfs_file_revoked()anddebugfs_file_release_safe()(patch 1, inert until patch 2 adds theKconfigsymbol) tell the check whether debugfs has cut the file off and whether its release can still reach the data.The walks run on a kernel thread the unbinding task waits for, and no file reference is kept across release. A reference the walk holds becomes the last one if the owner closes the file meanwhile; dropped from a user task its release would be queued behind unbind, where a devres action that waits for the close (
snd_card_free()) deadlocks; dropped from a kernel thread it goes to the delayed-fput work. What remains, and I would like your view on it (question 5): that work drains one global list last-in-first-out with all its runs serialized, so a release there that needs a lock unbind holds (a usbfs close takes the USB parent lock a USB interface unbind holds) stalls every later delayed close, including one such an action is waiting for; without this option that close would have run from its owner's task work. The cross-vendor review this went through found the first of these.Subsystems whose files do not reach the driver object through those pointers register the hook, keyed on their
file_operations; V4L2 is the first (patch 3), naming thevideo_device; its drvdata is not named, since reaching it means dereferencing avideo_devicethat may already be freed. The hook is a workaround. The cdev route catches a struct cdev embedded in managed memory (an open file pins the cdev's kobject, soinode->i_cdevis still there at unbind) but not these: V4L2's cdev is a separatecdev_alloc()with no kobject parent, and misc's is one shared cdev, so neither leads to the driver's allocation. Parenting V4L2's cdev to the video device, as mc-devnode and cec do withcdev_device_add(), would make the cdev hold the device whose release deletes the cdev; that is a media-core change with regression risk, not something a debug option should carry. A DRM hook is deferred:devm_drm_dev_alloc()memory is kzalloc()'d, so the expected yield is low.Testing, one boot of an x86 KVM guest with KASAN, on the development branch (identical to this series except for two extra test vehicles): the test driver in patch 4 (a devm-backed misc node, a devm-embedded cdev node, a refcounted control node and a devres-removed debugfs file) and a cx231xx-shaped V4L2 vehicle WARN once per dangling allocation before the unbind returns (two for the test driver, one for the V4L2 vehicle), after which KASAN reports use-after-frees on close of the misc and cdev nodes and, for the V4L2 vehicle, 38 reports across a read, an ioctl and close; the gpio sloppy logic analyzer, instantiated through a fake-gpiochip glue module and unbound with four debugfs files held open, produces four info lines and no WARN, its reads return
-EIOand nothing fires on close; vivid, as a negative control, is silent. The V4L2 vehicle and the glue are in the branch below, not in the series. Also compiled: the option off; DEBUG_FS=n; VIDEO_DEV=m with DEVM_REFS_TEST=m (videodev.ko and the test module through modpost); W=1 clean on devres.o, dd.o, v4l2-dev.o,debugfs/file.oand the test driver. Only the all-builtin configuration was booted. Not exercised: the two phase-2 WARN branches (a removed but unguarded, or a still-live, debugfs file) and the no-memory fallback.Limitations, also in the
Kconfighelp: only files in task fd tables are seen; the check finds pointers that are dangling at that moment, not teardown races, nor whether a debugfs removal action ran before or after the free; a managed allocation whose release waits for its files to close first (an ALSA card) is not about to be freed, so a hit on it is a false positive; and the walk is linear in threads times fd tables and costs every unbind and failed probe (not deferral).Questions for review:
1. Is driver core the right home for this, or should it be per-subsystem (misc, V4L2) with no generic walk?
2. Is a hook keyed onfile_operationsacceptable, or should the answer for V4L2 be thecdev_device_add()conversion despite its risk?
3. Is the info/WARN split for removed-and-guarded versus unguarded debugfs files the right call?
4. Should the test be a module plus atools/testing/selftestsscript rather than a module alone? The check needs fds held in a task fd table across the unbind, which KUnit cannot do naturally.
5. The walk must hold a reference on each file it inspects, so a racing close can make it the last holder; routing that release through the delayed-fput worker avoids the task-work deadlock but leaves the serialized-worker case above. Is that acceptable for a debug option, or is there a way to look at a file's pointers without the walk ever owning the last reference?
Quoted 9 lines
Per
Documentation/process/generated-content.rst: the code, the test vehicles and the first drafts of these messages were written with Claude (Anthropic) under my direction, from prompts that specified the mechanism, the call site, the lock context and the debugfs handling; the series was then revised through repeated model-assisted review passes against the kernel source, including one by reviewers from three other model families, with the fixes mine to judge. I have read and can answer for every line. Where I most expect to be wrong is in the Kconfig's list of limitations and in the choice to put the hook in driver core at all.
Are you really expecting anyone to read all that ?
If you feel this is an important issue, ditch your LLM and try again, this time understanding what you're doing.
Quoted 23 lines
This series: https://github.com/modelmiser/linux/tree/devres-refs-v1
Development history (incl. the two extra vehicles and the review fix batches): https://github.com/modelmiser/linux/tree/devres-refs-dev
Guest harness, its logs, and the review record:
https://github.com/modelmiser/devres-refs-supportlinux-media is Cc'd on the whole series because the hook API exists for V4L2; linux-doc on patch 2 for
devres.rst..../driver-api/driver-model/devres.rst | 18 + drivers/base/Kconfig | 64 ++ drivers/base/base.h | 38 + drivers/base/dd.c | 14 +- drivers/base/devres.c | 667 ++++++++++++++++++ drivers/base/test/Kconfig | 15 + drivers/base/test/Makefile | 2 + drivers/base/test/devm_refs_test.c | 323 +++++++++ drivers/media/v4l2-core/v4l2-dev.c | 31 + fs/debugfs/file.c | 112 +++ include/linux/debugfs.h | 29 + include/linux/device/devres.h | 58 ++ 12 files changed, 1367 insertions(+), 4 deletions(-) create mode 100644 drivers/base/test/devm_refs_test.c
Signature · 3 lines
Regards, Laurent Pinchart
Quoted 1 line
Are you really expecting anyone to read all that ?
Fair enough. The short version:
A struct cdev, miscdevice or video_device embedded in devm_kzalloc()'d driver state outlives the unbind through any open file, and the next operation on that file, usually close(), is a use-after-free. It keeps getting fixed one driver at a time (44f3468a0aef, 7d6358ab0286), and cx231xx in 7.4-rc1 still has the shape.
CONFIG_DEBUG_DEVRES_REFS, off by default: in device_unbind_cleanup(), before devres_release_all(), walk every task's fd table once and WARN when a file's private_data, i_private or i_cdev, or an object a subsystem names (patch 3: V4L2's video_device), points into an allocation about to be freed. A debugfs file still live during the walk is judged after release, since drivers often remove those through a devres action. Cost: one walk per unbind or failed probe.
Patch 4 is a test driver: unbind with its nodes open gives two WARNs, and KASAN then reports the use-after-frees on close. vivid, as a control, is silent.
The open problem (question 5 in the cover): the walk holds a reference on each file it inspects, so a racing close can leave it the last holder. It runs on a kthread so that release goes to delayed_fput rather than task work queued behind the unbind, but the delayed-fput worker is serialized, so a release there that needs a lock unbind holds stalls the ones behind it.
Quoted 3 lines · Chad Aldreda
Quoted 1 line
Are you really expecting anyone to read all that ?
Fair enough. The short version:
I think you forgot about the second part of my reply.
Quoted 24 lines
A struct cdev, miscdevice or
video_deviceembedded in devm_kzalloc()'d driver state outlives the unbind through any open file, and the next operation on that file, usuallyclose(), is a use-after-free. It keeps getting fixed one driver at a time (44f3468a0aef,7d6358ab0286), and cx231xx in 7.4-rc1 still has the shape.
CONFIG_DEBUG_DEVRES_REFS, off by default: indevice_unbind_cleanup(), beforedevres_release_all(), walk every task's fd table once and WARN when a file'sprivate_data,i_privateori_cdev, or an object a subsystem names (patch 3: V4L2'svideo_device), points into an allocation about to be freed. A debugfs file still live during the walk is judged after release, since drivers often remove those through a devres action. Cost: one walk per unbind or failed probe.Patch 4 is a test driver: unbind with its nodes open gives two WARNs, and KASAN then reports the use-after-frees on close. vivid, as a control, is silent.
The open problem (question 5 in the cover): the walk holds a reference on each file it inspects, so a racing close can leave it the last holder. It runs on a kthread so that release goes to
delayed_fputrather than task work queued behind the unbind, but the delayed-fput worker is serialized, so a release there that needs a lock unbind holds stalls the ones behind it.
Signature · 3 lines
Regards, Laurent Pinchart