Linux Modules
 help / color / mirror / Atom feed
* [PATCH v3] module: drain external refs before freeing a failed-init module
@ 2026-12-04 10:41 Mahanta Jambigi
  2026-12-04 11:02 ` sashiko-bot
  0 siblings, 1 reply; 2+ messages in thread
From: Mahanta Jambigi @ 2026-12-04 10:41 UTC (permalink / raw)
  To: mcgrof, petr.pavlu, da.gomez, samitolvanen, atomlin
  Cc: linux-modules, linux-kernel, linux-s390, pasic, wintera,
	Mahanta Jambigi

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@linux.ibm.com/
Signed-off-by: Mahanta Jambigi <mjambigi@linux.ibm.com>
---
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)


^ permalink raw reply related	[flat|nested] 2+ messages in thread

* Re: [PATCH v3] module: drain external refs before freeing a failed-init module
  2026-12-04 10:41 [PATCH v3] module: drain external refs before freeing a failed-init module Mahanta Jambigi
@ 2026-12-04 11:02 ` sashiko-bot
  0 siblings, 0 replies; 2+ messages in thread
From: sashiko-bot @ 2026-12-04 11:02 UTC (permalink / raw)
  To: Mahanta Jambigi
  Cc: linux-modules, linux-s390, Petr Pavlu, Heiko Carstens,
	Vasily Gorbik, Alexander Gordeev, Christian Borntraeger

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [Medium] module: non-freezable fixed msleep(20) drain loop in
  do_init_module()
- [Medium] module: premature idempotent_complete() before drain check
  and free_module()
- [Medium] module: atomic_sub_return() underflow re-enables
  try_module_get()
- [Medium] module: missing acquire ordering in do_init_module() refcnt
  drain loop
--

commit 996c0173d26a483c9d16420ac5d9f3674b09cd43
Author: Mahanta Jambigi <mjambigi@linux.ibm.com>

module: drain external refs before freeing a failed-init module

This commit drains external module references on init failure in
do_init_module() before running MODULE_STATE_GOING teardown and
free_module(), while completing idempotent finit_module() waiters before
the wait.

Link: https://lore.kernel.org/linux-modules/85cb4573-32dd-44fd-a034-12372a362aa0@linux.ibm.com/

> diff --git a/kernel/module/main.c b/kernel/module/main.c
> index 6052baf1be891..d3744f17dd098 100644
> --- a/kernel/module/main.c
> +++ b/kernel/module/main.c

[ ... ]

> @@ -3230,6 +3236,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);

[Severity: Medium]
Should idempotent_complete() only run when references actually need to
be drained?

Calling it unconditionally here wakes and unhashes coalesced
finit_module() waiters before MODULE_STATE_GOING teardown and
free_module() finish, even in the common zero-reference failure case and
when CONFIG_MODULE_UNLOAD is disabled.  An immediate retry of
finit_module() can then hit module_patient_check_exists() and fail with
-EBUSY while the module is still linked.

Concurrent finit_module() calls arriving during teardown also miss
idem_hash coalescing and repeat file loading and validation before
failing with -EBUSY, and delete_module() on a dependency can fail with
-EWOULDBLOCK until module_unload_free() runs.  Moving
idempotent_complete() inside the CONFIG_MODULE_UNLOAD drain branch would
keep the previous post-free_module() ordering whenever no wait occurs.

> +
> +#ifdef CONFIG_MODULE_UNLOAD

[ ... ]

> +	if (atomic_sub_return(MODULE_REF_BASE, &mod->refcnt) > 0) {

[Severity: Medium]
Can atomic_sub_return() underflow mod->refcnt from 0 to -1 and allow a
racing try_module_get() to succeed?

If a buggy mod->init() calls an extra module_put(), the module_put(mod)
above drops mod->refcnt to 0 without warning, and atomic_sub_return()
then sets it to -1.

Because try_module_get() uses atomic_inc_not_zero(), a non-RCU caller
such as bpf_get_raw_tracepoint_module() (unlinked later in the
MODULE_STATE_GOING notifier) can increment -1 back to 0 and return true
while the module is freed:

CPU0                                  CPU1
do_init_module()                      bpf_get_raw_tracepoint_module()
  mod->init() (extra module_put)
                                        try_module_get(mod)
                                          module_is_live(mod) -> true
  mod->state = MODULE_STATE_GOING
  synchronize_rcu()
  module_put(mod)          (refcnt=0)
  atomic_sub_return(...)   (refcnt=-1)
                                          atomic_inc_not_zero() -> true
  free_module(mod)
                                        use mod  <-- use-after-free

Using atomic_dec_if_positive(&mod->refcnt) keeps refcnt clamped at 0 so
atomic_inc_not_zero() stays closed, while still returning -1 to skip
the drain loop.

> +		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) {

[Severity: Medium]
Does atomic_read(&mod->refcnt) need acquire ordering here to pair with
atomic_dec_if_positive() in module_put()?

On weakly ordered architectures, a control dependency after a relaxed
atomic_read() does not order subsequent loads.  Teardown right after the
loop, such as srcu_module_going() reading srcu_readers_active(ssp), can
observe stale pre-put state and trigger a spurious WARN_ON() or leak
per-CPU memory.

Using atomic_read_acquire(&mod->refcnt) in the loop condition would
provide the needed acquire barrier.

> +			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);
> +		}

[Severity: Medium]
Can polling indefinitely with msleep(20) block system suspend and
hibernation?

msleep() sleeps in TASK_UNINTERRUPTIBLE without TASK_FREEZABLE, so
try_to_freeze_tasks() times out and aborts suspend with -EBUSY.  A
userspace holder frozen first cannot release the reference while the
loader waits, and a leaked reference blocks suspend until reboot.

Sleeping without TASK_NOLOAD also inflates the load average by 1 during
the wait, and fixed 20 ms polling without backoff generates 50 Hz
wakeups indefinitely.  Sleeping in TASK_IDLE | TASK_FREEZABLE with
schedule_timeout() and backing off the interval would avoid all three.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204104104.1711861-1-mjambigi@linux.ibm.com?part=1

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-12-04 11:02 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04 10:41 [PATCH v3] module: drain external refs before freeing a failed-init module Mahanta Jambigi
2026-12-04 11:02 ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox