[PATCH v3 1/2] mtd: core: drop the module reference after ->_put_device()

tze.yee.ng at altera.com tze.yee.ng at altera.com
Wed Oct 21 20:53:51 PDT 2026


From: Tze Yee Ng <tze.yee.ng at altera.com>

__put_mtd_device() calls module_put() on the MTD owner and then calls
->_put_device(). If ->_put_device() frees the object that embeds the
mtd_info, it is still running code from the owner module after the
module reference is gone, so the module can be unloaded underneath it.

Call ->_put_device() first and module_put() last. ->_put_device() may
free master, so read master->owner beforehand.

The spi-nor fix that follows needs this: its ->_put_device() frees
struct spi_nor on the last put.

Signed-off-by: Tze Yee Ng <tze.yee.ng at altera.com>
---
Changes in v3:
- Reduced to the module_put() reorder. The core _free/removed hooks from
  v2 are gone; spi-nor manages its own lifetime again (patch 2).
- __put_mtd_device() now reads master->owner first, calls ->_put_device()
  and drops the module reference last (v2 left master->owner and
  ->_put_device() reachable after the core could free master).

Changes in v2:
- New.
- Drop the spi-nor-local kref and nor->removed.
- Add mtd->_free and mtd->removed in the core so the backing
  object outlives unbind and later ops return -ENODEV.
---
 drivers/mtd/mtdcore.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/drivers/mtd/mtdcore.c b/drivers/mtd/mtdcore.c
index 491a27d0315f..1cf402e07b13 100644
--- a/drivers/mtd/mtdcore.c
+++ b/drivers/mtd/mtdcore.c
@@ -1435,6 +1435,8 @@ EXPORT_SYMBOL_GPL(put_mtd_device);
 void __put_mtd_device(struct mtd_info *mtd)
 {
 	struct mtd_info *master = mtd_get_master(mtd);
+	/* master can be freed in _put_device */
+	struct module *owner = master->owner;
 
 	while (mtd) {
 		/* kref_put() can relese mtd, so keep a reference mtd->parent */
@@ -1448,11 +1450,12 @@ void __put_mtd_device(struct mtd_info *mtd)
 	if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER))
 		kref_put(&master->refcnt, mtd_device_release);
 
-	module_put(master->owner);
-
-	/* must be the last as master can be freed in the _put_device */
+	/* must be the last use of master */
 	if (master->_put_device)
 		master->_put_device(master);
+
+	/* _put_device() runs code from @owner, so drop the module last */
+	module_put(owner);
 }
 EXPORT_SYMBOL_GPL(__put_mtd_device);
 
-- 
2.43.7




More information about the linux-mtd mailing list