mtd: call external _get and _put in right order
authorAlexander Usyskin <alexander.usyskin@intel.com>
Tue, 20 Jun 2023 13:19:05 +0000 (16:19 +0300)
committerMiquel Raynal <miquel.raynal@bootlin.com>
Wed, 12 Jul 2023 11:30:10 +0000 (13:30 +0200)
MTD provider provides mtd_info object to mtd subsystem.
With kref patch the mtd_info object can be alive after
provider released mtd device.
Fix calling order in _get and _put functions to allow
mtd provider to safely alloc and release mtd object.

Execute:
1) call external _get
2) get_module
3) add internal kref
in the get function and opposite order in the put one.

The _put_device callback should be the last in put
as the master struct memory may be freed in this callback.

Signed-off-by: Alexander Usyskin <alexander.usyskin@intel.com>
Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
Link: https://lore.kernel.org/linux-mtd/20230620131905.648089-3-alexander.usyskin@intel.com
drivers/mtd/mtdcore.c

index 6dbd596a1129360e5dd1c0277d9e44e44f026f6e..2466ea4664668ef0a3aa0875f1e20d5c13c21e3e 100644 (file)
@@ -1229,21 +1229,20 @@ int __get_mtd_device(struct mtd_info *mtd)
        struct mtd_info *master = mtd_get_master(mtd);
        int err;
 
-       if (!try_module_get(master->owner))
-               return -ENODEV;
-
-       kref_get(&mtd->refcnt);
-
        if (master->_get_device) {
                err = master->_get_device(mtd);
-
-               if (err) {
-                       kref_put(&mtd->refcnt, mtd_device_release);
-                       module_put(master->owner);
+               if (err)
                        return err;
-               }
        }
 
+       if (!try_module_get(master->owner)) {
+               if (master->_put_device)
+                       master->_put_device(master);
+               return -ENODEV;
+       }
+
+       kref_get(&mtd->refcnt);
+
        while (mtd->parent) {
                if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER) || mtd->parent != master)
                        kref_get(&mtd->parent->refcnt);
@@ -1340,13 +1339,14 @@ void __put_mtd_device(struct mtd_info *mtd)
                mtd = parent;
        }
 
-       if (master->_put_device)
-               master->_put_device(master);
+       if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER))
+               kref_put(&master->refcnt, mtd_device_release);
 
        module_put(master->owner);
 
-       if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER))
-               kref_put(&master->refcnt, mtd_device_release);
+       /* must be the last as master can be freed in the _put_device */
+       if (master->_put_device)
+               master->_put_device(master);
 }
 EXPORT_SYMBOL_GPL(__put_mtd_device);