Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

mtd: Clean refcounting with MTD_PARTITIONED_MASTER

The logic is way too convoluted, let's clean the kref_get/put section to
clarify what this block does when using CONFIG_MTD_PARTITIONED_MASTER:
- Iterate through all the parent mtd devices
- Grab a reference over them all but the master
- Only grab the master whith CONFIG_MTD_PARTITIONED_MASTER
Same logic must apply in the put path, otherwise it would be broken.

Cc: Tomas Winkler <tomas.winkler@intel.com>
Cc: Alexander Usyskin <alexander.usyskin@intel.com>
Cc: Zhang Xiaoxu <zhangxiaoxu5@huawei.com>
Fixes: 19bfa9ebebb5 ("mtd: use refcount to prevent corruption")
Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
Tested-by: Alexander Usyskin <alexander.usyskin@intel.com>
Link: https://lore.kernel.org/linux-mtd/20230731090903.770277-1-miquel.raynal@bootlin.com

+10 -7
+10 -7
drivers/mtd/mtdcore.c
··· 1247 1247 return -ENODEV; 1248 1248 } 1249 1249 1250 - kref_get(&mtd->refcnt); 1251 - 1252 - while (mtd->parent) { 1253 - if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER) || mtd->parent != master) 1254 - kref_get(&mtd->parent->refcnt); 1250 + while (mtd) { 1251 + if (mtd != master) 1252 + kref_get(&mtd->refcnt); 1255 1253 mtd = mtd->parent; 1256 1254 } 1255 + 1256 + if (IS_ENABLED(CONFIG_MTD_PARTITIONED_MASTER)) 1257 + kref_get(&master->refcnt); 1257 1258 1258 1259 return 0; 1259 1260 } ··· 1339 1338 { 1340 1339 struct mtd_info *master = mtd_get_master(mtd); 1341 1340 1342 - while (mtd != master) { 1341 + while (mtd) { 1342 + /* kref_put() can relese mtd, so keep a reference mtd->parent */ 1343 1343 struct mtd_info *parent = mtd->parent; 1344 1344 1345 - kref_put(&mtd->refcnt, mtd_device_release); 1345 + if (mtd != master) 1346 + kref_put(&mtd->refcnt, mtd_device_release); 1346 1347 mtd = parent; 1347 1348 } 1348 1349