[PATCH v3] module: drain external refs before freeing a failed-init module
From: Mahanta Jambigi
Date: Fri Dec 04 2026 - 05:41:25 EST
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 and wait for the remaining ones to be put before
the GOING teardown and free_module() run, as the unload path does; a
getter that raced the state change is either counted and waited for, or
finds a zero count. Idempotent loads of the failed module are released
before 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; after 10 seconds the loader warns once with the remaining count
and keeps waiting. A module that loads successfully and then leaks a
reference like this cannot be unloaded either, where rmmod returns
-EWOULDBLOCK. A dependent load waiting for a symbol from the failed
module does not wait indefinitely: resolve_symbol_wait() gives up after
30 seconds, so a long drain shows up as that error.
The missing check predates the git history, so there is no Fixes: tag.
Link: https://lore.kernel.org/linux-modules/85cb4573-32dd-44fd-a034-12372a362aa0@xxxxxxxxxxxxx/
Signed-off-by: Mahanta Jambigi <mjambigi@xxxxxxxxxxxxx>
---
Changes in v3:
- Drain the references before the GOING notifier chain, klp_module_going()
and ftrace_release_mod(), the order try_stop_module() establishes on the
unload path. kprobes, SRCU, livepatch and ftrace teardown run there and
assume no task is still executing module code. v2 drained after the
notifiers so that a consumer torn down there could drop its reference
first, but such a consumer would already hold up try_stop_module() and
make rmmod fail with -EWOULDBLOCK before the notifiers run.
- Poll the count instead of waking it from module_put(). module_put() runs
with interrupts disabled under a raw spinlock from the clockevents
path, where a regular wait queue cannot be used, and the rare failure
path adds no wake-up cost to that hot path; a reference still held
after 10 seconds is reported once.
- Log when a reference held past the 10 second warning finally drains,
so a slow but legitimate holder is distinguishable from a leak.
- Drop the early module_wq wake. Waking while the module is still listed
in MODULE_STATE_GOING makes resolve_symbol_wait() return -ENOENT for a
symbol it found, which bypasses the weak-symbol fallback in
simplify_symbols(). A duplicate load that was already waiting on
module_wq now sleeps until the trailing wake-up; one that arrives
during the drain sees MODULE_STATE_GOING and returns -EBUSY through
module_patient_check_exists().
- Keep the idempotent completion before the drain.
- Follows the reply to Petr's review of v1 (Link). The three answers still
stand: struct module is unchanged, module_put() takes no part in the
drain, and duplicate finit_module() loads are completed before the wait.
Only the wait queue named in that reply is replaced by the poll above.
- Note that the trace_module_put() window between the decrement and its
use of mod->name is unchanged and also present on the unload path.
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.
- 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 | 77 +++++++++++++++++++++++++++++++++++++++++++++-----
1 file changed, 70 insertions(+), 7 deletions(-)
diff --git a/kernel/module/main.c b/kernel/module/main.c
index 34e0204ea37c..92f84d9965b1 100644
--- a/kernel/module/main.c
+++ b/kernel/module/main.c
@@ -29,6 +29,8 @@
#include <linux/rcupdate.h>
#include <linux/capability.h>
#include <linux/cpu.h>
+#include <linux/delay.h>
+#include <linux/jiffies.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/err.h>
@@ -3095,13 +3097,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;
@@ -3229,6 +3235,52 @@ static noinline int do_init_module(struct module *mod)
mod->state = MODULE_STATE_GOING;
synchronize_rcu();
module_put(mod);
+
+ /*
+ * Release idempotent loads before waiting below, so a failed init
+ * delays only the task that ran it.
+ */
+ if (idem)
+ idempotent_complete(idem, ret);
+
+#ifdef CONFIG_MODULE_UNLOAD
+ /*
+ * The state change refuses new references. Dropping the base
+ * reference lets the count reach zero, so a getter that raced the
+ * state change is either counted and waited for here, or finds
+ * zero. Wait for the remaining references to go before the GOING
+ * teardown, which assumes that no reference is held, as
+ * try_stop_module() guarantees on the unload path. Until then
+ * module_refcount() reports one less than the references held.
+ *
+ * module_put() can run under a raw spinlock with interrupts
+ * disabled, so a regular wait queue cannot be used and the rare
+ * failure path should not add a wake-up to that hot path. Poll the
+ * count instead, and warn once if a reference is still held after
+ * 10 seconds.
+ *
+ * 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) {
+ unsigned long start = jiffies;
+ unsigned long warn_at = start + msecs_to_jiffies(10 * 1000);
+ bool warned = false;
+ int refs;
+
+ while ((refs = atomic_read(&mod->refcnt)) > 0) {
+ if (!warned && time_after(jiffies, warn_at)) {
+ pr_warn("%s: init failed but %d reference(s) are still held after 10s\n",
+ mod->name, refs);
+ warned = true;
+ }
+ msleep(20);
+ }
+ if (warned)
+ pr_info("%s: init failed, references drained after %lu s\n",
+ mod->name, (jiffies - start) / HZ);
+ }
+#endif
blocking_notifier_call_chain(&module_notify_list,
MODULE_STATE_GOING, mod);
klp_module_going(mod);
@@ -3450,7 +3498,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 +3658,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 +3735,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 +3743,7 @@ struct idempotent {
struct hlist_node entry;
struct completion complete;
int ret;
+ bool completed;
};
#define IDEM_HASH_BITS 8
@@ -3710,6 +3759,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 +3781,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 +3794,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 +3805,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 +3832,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 +3869,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 +3881,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);
}
--
2.50.1 (Apple Git-155)