[PATCH 7/9] mtd: Unbind the block device when removing a master
Daniel Golle
daniel at makrotopia.org
Fri Nov 13 16:11:56 PST 2026
Removing an MTD master leaves its block device bound, so each SPI
flash re-probe adds another block device and leaks its pointer storage.
Unbind the block device and free the storage when deleting the master.
Share the condition used to identify masters which have block devices.
Fixes: e8a7453824b7 ("mtd: bind an mtd_blk device for non-NAND MTD masters")
Signed-off-by: Daniel Golle <daniel at makrotopia.org>
---
drivers/mtd/mtdcore.c | 48 ++++++++++++++++++++++++++++++++++++++++---
1 file changed, 45 insertions(+), 3 deletions(-)
diff --git a/drivers/mtd/mtdcore.c b/drivers/mtd/mtdcore.c
index 3d3a84df0a6..34009f997f8 100644
--- a/drivers/mtd/mtdcore.c
+++ b/drivers/mtd/mtdcore.c
@@ -30,6 +30,7 @@
#include <linux/bug.h>
#include <linux/err.h>
#include <ubi_uboot.h>
+#include <dm/device-internal.h>
#endif
#include <linux/log2.h>
@@ -396,6 +397,44 @@ static struct device_type mtd_devtype = {
};
#endif
+static bool mtd_is_blk_master(struct mtd_info *mtd)
+{
+ return IS_ENABLED(CONFIG_MTD_BLOCK) && mtd->dev &&
+ !mtd_is_partition(mtd) && !mtd_type_is_nand(mtd);
+}
+
+static void mtd_blk_unbind(struct mtd_info *mtd, struct udevice *blk)
+{
+ struct mtd_info **mtdp;
+ int ret;
+
+ if (strcmp(blk->driver->name, "mtd_blk"))
+ return;
+
+ mtdp = dev_get_priv(blk);
+ if (!mtdp || *mtdp != mtd)
+ return;
+
+ ret = device_remove(blk, DM_REMOVE_NORMAL);
+ if (!ret)
+ ret = device_unbind(blk);
+ if (ret) {
+ pr_warn("mtd: %s: cannot unbind the block device: %d\n",
+ mtd->name, ret);
+ return;
+ }
+
+ kfree(mtdp);
+}
+
+static void mtd_blk_unbind_master(struct mtd_info *mtd)
+{
+ struct udevice *blk, *next;
+
+ list_for_each_entry_safe(blk, next, &mtd->dev->child_head, sibling_node)
+ mtd_blk_unbind(mtd, blk);
+}
+
static void mtd_blk_bind_master(struct mtd_info *mtd)
{
struct mtd_info **mtdp;
@@ -403,7 +442,7 @@ static void mtd_blk_bind_master(struct mtd_info *mtd)
/*
* mtd_bind() keeps the passed pointer, so it needs storage that lives
- * as long as the block device; an MTD master is never removed.
+ * as long as the block device.
*/
mtdp = kmalloc(sizeof(*mtdp), GFP_KERNEL);
if (!mtdp) {
@@ -520,8 +559,7 @@ int add_mtd_device(struct mtd_info *mtd)
mutex_unlock(&mtd_table_mutex);
- if (IS_ENABLED(CONFIG_MTD_BLOCK) && mtd->dev &&
- !mtd_is_partition(mtd) && !mtd_type_is_nand(mtd)) {
+ if (mtd_is_blk_master(mtd)) {
/*
* Expose a non-NAND MTD master (parallel NOR, SPI-NOR, ...) as
* a mtd_blk block device, so its partitions are reachable
@@ -596,6 +634,10 @@ int del_mtd_device(struct mtd_info *mtd)
device_unregister(&mtd->dev);
#endif
+ if (CONFIG_IS_ENABLED(DM_DEVICE_REMOVE) &&
+ mtd_is_blk_master(mtd))
+ mtd_blk_unbind_master(mtd);
+
idr_remove(&mtd_idr, mtd->index);
module_put(THIS_MODULE);
--
2.56.0
More information about the openwrt-devel
mailing list