module: drain external refs before freeing a failed-init module
Subsystems (2)
PATCH v2 1/1 module: drain external refs before freeing a failed-init module
When a module's __init makes it externally reachable and a later __init step fails, do_init_module() frees the module while callers that entered through that interface and called try_module_get() may still be running module code. The normal unload path in try_stop_module() refuses to proceed while references are held; the init-failure path has no such check.
Drop the base reference so no new reference can be taken, then wait for the remaining ones to be put before calling free_module(). Duplicate and idempotent loads of the failed module are released first, so they are not blocked behind the wait.
The wait is not interruptible and has no timeout. A reference that is never put keeps the module in MODULE_STATE_GOING and the loading task waiting, which the hung task detector reports.
---
[RFC] module: init-failure path can free a module with live try_module_get() users
Changes in v2:
- Use a global wait queue instead of a completion in struct module. The new wake-up path in module_put() touches no module memory, so it cannot race with free_module() reached through delete_module().
- Drop the base reference and wait on the raw count. try_module_get() then fails once the count reaches zero, so a racing getter cannot resurrect the module, and module_put() wakes only on the last reference. module_refcount() reports one less than the held references until the module is freed.
- Release duplicate and idempotent loads before the wait, and keep the trailing module_wq wake-up so a loader that finds the module UNFORMED during free_module() is not left asleep.
- Make idempotent_complete() a no-op on the second call for the same request, so entries from a newer finit_module() during the wait are left alone.
- Run the wait after the GOING notifier chain, so a consumer that a notifier tears down drops its reference before the loader blocks on it.
- A load of the same name that starts during the wait now fails with -EBUSY instead of blocking; callers retry it.
- No change to ref_module(): strong_try_module_get() already refuses MODULE_STATE_COMING, so a failed init cannot be pinned through a module dependency.
- Without CONFIG_MODULE_UNLOAD there are no reference counts and nothing to drain; the wait is compiled out. The wait is not interruptible, since after the base reference is gone nothing else can free the module.
kernel/module/main.c | 64 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 57 insertions(+), 7 deletions(-)
kernel/module/main.c +57 -7
@@ -659,6 +659,12 @@ EXPORT_TRACEPOINT_SYMBOL(module_get);/* MODULE_REF_BASE is the base reference count by kmodule loader. */ #define MODULE_REF_BASE 1 +/* +* Wait queue for a failed init that is draining the references taken +* by other tasks before the module can be freed. +*/ +static DECLARE_WAIT_QUEUE_HEAD (module_refs_wq); +/* Init the unload section of the module. */ static int module_unload_init (struct module *mod) {
@@ -968,6 +974,13 @@ void module_put(struct module *module) ret =atomic_dec_if_positive (&module->refcnt);WARN_ON (ret <0 );/* Failed to put refcount */ trace_module_put (module, _RET_IP_); +/* +* Zero is only reached once the base reference has been +* dropped by a failed init, which then waits for the last +* reference to go. +*/ +if (!ret) +wake_up_all (&module_refs_wq); } }EXPORT_SYMBOL (module_put);
@@ -3095,13 +3108,17 @@ void flush_module_init_free_work(void)static bool async_probe;module_param (async_probe, bool,0644 ); +struct idempotent ; + +static int idempotent_complete (struct idempotent *u,int ret); +/* * This is where the real work happens. * * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb * helper command 'lx-symbols'. */ -static noinline int do_init_module(struct module *mod) +static noinline int do_init_module(struct module *mod, struct idempotent *idem) {int ret =0 ;struct mod_initfree *freeinit;
@@ -3233,6 +3250,28 @@ static noinline int do_init_module(struct module *mod) MODULE_STATE_GOING, mod);klp_module_going (mod);ftrace_release_mod (mod); + +/* +* Release duplicate and idempotent loads before waiting below, so +* a failed init delays only the task that ran it. +*/ +wake_up_all (&module_wq); +if (idem) +idempotent_complete (idem, ret); + +#ifdef CONFIG_MODULE_UNLOAD +/* +* Dropping the base reference gates new references: once the count +* reaches zero, try_module_get() fails. Wait for the remaining +* references to go before the module memory is freed. Until then +* module_refcount() reports one less than the references held. +* +* A negative count means the module dropped a reference it never +* took; puts are no-ops on it, so waiting for it would never end. +*/ +if (atomic_sub_return (MODULE_REF_BASE , &mod->refcnt) >0 ) +wait_event (module_refs_wq,atomic_read (&mod->refcnt) <=0 ); +#endif free_module (mod);wake_up_all (&module_wq);
@@ -3450,7 +3489,7 @@ static int early_mod_check(struct load_info *info, int flags)* zero, and we rely on this for optional sections. */ static int load_module (struct load_info *info,const char __user *uargs, -int flags) +int flags,struct idempotent *idem) {struct module *mod;bool module_allocated = false;
@@ -3610,7 +3649,7 @@ static int load_module(struct load_info *info, const char __user *uargs,/* Done! */ trace_module_load (mod); -return do_init_module (mod); +return do_init_module (mod, idem); livepatch_cleanup:if (is_livepatch_module (mod))
@@ -3687,7 +3726,7 @@ SYSCALL_DEFINE3(init_module, void __user *, umod,return err; } -return load_module (&info, uargs,0 ); +return load_module (&info, uargs,0 ,NULL ); }struct idempotent {
@@ -3695,6 +3734,7 @@ struct idempotent {struct hlist_node entry;struct completion complete;int ret; +bool completed; };#define IDEM_HASH_BITS 8
@@ -3710,6 +3750,7 @@ static bool idempotent(struct idempotent *u, const void *cookie) u->ret = -EINTR ; u->cookie = cookie; + u->completed = false;init_completion (&u->complete);spin_lock (&idem_lock);
@@ -3731,6 +3772,9 @@ static bool idempotent(struct idempotent *u, const void *cookie)* up completing the operation. We now need to walk the list, * remove everybody - which includes ourselves - fill in the return * value, and then complete the operation. +* +* Only the first call for a request walks the list, so entries of a +* newer request for the same file are left alone. */ static int idempotent_complete (struct idempotent *u,int ret) {
@@ -3741,6 +3785,10 @@ static int idempotent_complete(struct idempotent *u, int ret)struct idempotent *pos;spin_lock (&idem_lock); +if (u->completed) + goto out; + u->completed = true; +hlist_for_each_entry_safe (pos, next, head, entry) {if (pos->cookie != cookie)continue ;
@@ -3748,6 +3796,7 @@ static int idempotent_complete(struct idempotent *u, int ret) pos->ret = ret;complete (&pos->complete); } +out:spin_unlock (&idem_lock);return ret; }
@@ -3774,7 +3823,8 @@ static int idempotent_wait_for_completion(struct idempotent *u)return u->ret; } -static int init_module_from_file (struct file *f,const char __user * uargs,int flags) +static int init_module_from_file (struct file *f,const char __user *uargs,int flags, +struct idempotent *idem) {bool compressed = !!(flags &MODULE_INIT_COMPRESSED_FILE );struct load_info info = { };
@@ -3810,7 +3860,7 @@ static int init_module_from_file(struct file *f, const char __user * uargs, int info.len = len; } -return load_module (&info, uargs, flags); +return load_module (&info, uargs, flags, idem); }static int idempotent_init_module (struct file *f,const char __user * uargs,int flags)
@@ -3822,7 +3872,7 @@ static int idempotent_init_module(struct file *f, const char __user * uargs, int/* Are we the winners of the race and get to do this? */ if (!idempotent (&idem,file_inode (f))) { -int ret =init_module_from_file (f, uargs, flags); +int ret =init_module_from_file (f, uargs, flags, &idem);return idempotent_complete (&idem, ret); }
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] module: premature MODULE_STATE_GOING teardown before draining refs in do_init_module() - [Medium]…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] module: premature MODULE_STATE_GOING teardown before draining refs in do_init_module()
- [Medium] module: use-after-free in module_put() calling trace_module_put() after final put
- [Medium] module: premature module_wq wakeup and idempotent_complete() in do_init_module()
- [Medium] module: invalid wait context in module_put() waking spinlock_t module_refs_wq
--
commit 519bf26934925ffafd7a4badb1b58d2efcf6b1ce
Author: Mahanta Jambigi <[email protected]>
module: drain external refs before freeing a failed-init module
When module initialization fails in do_init_module(), this commit drops MODULE_REF_BASE and waits on module_refs_wq for external module references to drain before calling free_module(), after waking module_wq and completing idempotent loads.
Quoted 18 lines
kernel/module/main.c +6
-0@@ -660,6 +660,12 @@ EXPORT_TRACEPOINT_SYMBOL(module_get);/* MODULE_REF_BASE is the base reference count by kmodule loader. */ #define MODULE_REF_BASE 1 +/* +* Wait queue for a failed init that is draining the references taken +* by other tasks before the module can be freed. +*/ +static DECLARE_WAIT_QUEUE_HEAD (module_refs_wq); +/* Init the unload section of the module. */ static int module_unload_init (struct module *mod) {
kernel/module/main.c void module_put(struct module *module) · line 977
Quoted 3 lines
kernel/module/main.c +0
-0@@ -969,6 +975,13 @@ void module_put(struct module *module) ret =atomic_dec_if_positive (&module->refcnt);WARN_ON (ret <0 );/* Failed to put refcount */ trace_module_put (module, _RET_IP_);
[Severity: Medium]
Can trace_module_put() dereference module after free_module() has already freed it?
CPU0 (failing loader) CPU1 (external caller)do_init_module()
...
atomic_sub_return(MODULE_REF_BASE,
&mod->refcnt)
module_put(mod)
atomic_dec_if_positive(&mod->refcnt)
<preempted>
wait_event(module_refs_wq,
atomic_read(&mod->refcnt) <= 0)
free_module(mod)
...
free_mod_mem(mod)
trace_module_put(mod, _RET_IP_)
mod->name <-- use-after-freeOnce atomic_dec_if_positive() drops the last reference, do_init_module() can see mod->refcnt == 0 and run free_module() to completion without waiting for wake_up_all(). If CPU1 is preempted before entering the tracepoint's RCU read-side section, synchronize_rcu() in free_module() does not wait for it, and trace_module_put() reads mod->name and mod->refcnt from unmapped module memory.
kernel/module/main.c void module_put(struct module *module) · line 986
Quoted 10 lines
kernel/module/main.c +7
-0+/* +* Zero is only reached once the base reference has been +* dropped by a failed init, which then waits for the last +* reference to go. +*/ +if (!ret) +wake_up_all (&module_refs_wq); } }EXPORT_SYMBOL (module_put);
[Severity: Medium]
Does calling wake_up_all(&module_refs_wq) from module_put() violate lock nesting rules when a reference is dropped under a raw_spinlock_t?
module_refs_wq is a regular wait_queue_head_t protected by a spinlock_t, which is a sleeping lock on PREEMPT_RT. Callers such as clockevents_exchange_device() and clockevents_replace() invoke module_put(dev->owner) while holding raw_spin_lock(&clockevents_lock) with interrupts disabled (including from __clockevents_unbind() in hardirq IPI context). If the last reference is dropped in that context after MODULE_REF_BASE has been subtracted, waking module_refs_wq acquires a spinlock_t inside a raw_spinlock_t, triggering a lockdep PROVE_RAW_LOCK_NESTING splat and sleeping in atomic context on PREEMPT_RT.
[ ... ]
kernel/module/main.c static noinline int do_init_module(struct module *mod) · line 3261
Quoted 12 lines
kernel/module/main.c +8
-0@@ -3234,6 +3251,28 @@ static noinline int do_init_module(struct module *mod) MODULE_STATE_GOING, mod);klp_module_going (mod);ftrace_release_mod (mod); + +/* +* Release duplicate and idempotent loads before waiting below, so +* a failed init delays only the task that ran it. +*/ +wake_up_all (&module_wq); +if (idem) +idempotent_complete (idem, ret);
[Severity: Medium]
Does waking module_wq and completing idempotent requests before free_module() break concurrent symbol resolution and retries?
At this point mod is still linked on the modules list in MODULE_STATE_GOING and its sysfs directory is still present:
1. If another module load is waiting in resolve_symbol_wait() for a weak (STB_WEAK) symbol exported by mod, waking module_wq while mod is in MODULE_STATE_GOING causes find_symbol() to find mod and ref_module() -> strong_try_module_get() to return -ENOENT. resolve_symbol_wait() then returns ERR_PTR(-ENOENT) instead of NULL, which bypasses the weak-symbol fallback in simplify_symbols() and fails the dependent module load with -ENOENT.
2. Completing idem unhashes and returns concurrent idempotent finit_module() callers to userspace before free_module() tears down /sys/module/<mod> and unlinks mod from modules (even when no external references are held and wait_event() does not sleep). An immediate retry from userspace is no longer coalesced by idempotent(), enters module_patient_check_exists(), finds mod still on the list, and fails with -EBUSY.
Quoted 6 lines
kernel/module/main.c +6
-0+ +#ifdef CONFIG_MODULE_UNLOAD +/* +* Dropping the base reference gates new references: once the count +* reaches zero, try_module_get() fails. Wait for the remaining +* references to go before the module memory is freed. Until then
kernel/module/main.c static noinline int do_init_module(struct module *mod) · line 3276
Quoted 10 lines
kernel/module/main.c +8
-0+* module_refcount() reports one less than the references held. +* +* A negative count means the module dropped a reference it never +* took; puts are no-ops on it, so waiting for it would never end. +*/ +if (atomic_sub_return (MODULE_REF_BASE , &mod->refcnt) >0 ) +wait_event (module_refs_wq,atomic_read (&mod->refcnt) <=0 ); +#endif free_module (mod);wake_up_all (&module_wq);
[Severity: High]
Should MODULE_REF_BASE be dropped and external references drained before running the MODULE_STATE_GOING notifier chain, klp_module_going(), and ftrace_release_mod()?
In delete_module(), try_stop_module() drops MODULE_REF_BASE and ensures no external references remain before MODULE_STATE_GOING teardown runs, so GOING handlers assume no task is executing inside the module anymore. In do_init_module(), running that teardown while callers holding try_module_get() are still executing module code breaks several consumers:
- kprobes_module_callback() calls kill_kprobe(), which assumes no thread can reach the probed function and calls arch_remove_kprobe() to free p->ainsn.insn and set it to NULL without disarming the breakpoint in module text:
kernel/kprobes.c:kill_kprobe() {
...
/*
* Here, we can remove insn_slot safely, because no thread calls
* the original probed function (which will be freed soon) any more.
*/
arch_remove_kprobe(p);
...
} If the active try_module_get() caller hits that kprobe before calling module_put(), single-stepping jumps to NULL or freed slot memory and crashes the kernel.
- srcu_module_going() calls cleanup_srcu_struct() and free_percpu(ssp->sda) on the module's static srcu_struct instances while active module code may still be in an SRCU read-side critical section, either hitting WARN_ON(srcu_readers_active(ssp)) and leaking ssp->sda or causing a per-CPU use-after-free.
- klp_module_going() unpatches the module without a consistency transition and clears livepatch relocations while tasks are still running patched module functions, and ftrace_release_mod() frees the module's ftrace records while functions remain active.
In addition, keeping MODULE_REF_BASE alive across synchronize_rcu() and the GOING teardown means mod->refcnt stays at least 1 even when no external references were held when mod->init() failed, so a non-RCU try_module_get() caller that passed module_is_live(mod) just before mod->state became MODULE_STATE_GOING can still succeed in atomic_inc_not_zero(&mod->refcnt) after MODULE_STATE_GOING teardown has already run.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1