diff mbox series

[-nect,RFC,v2,1/2] block: add helpers for bd_holder_dir refcount management

Message ID 20221020132049.3947415-2-yukuai3@huawei.com (mailing list archive)
State New, archived
Headers show
Series block: fix uaf in bd_link_disk_holder() | expand

Commit Message

Yu Kuai Oct. 20, 2022, 1:20 p.m. UTC
Currently the lifecycle of bd_holder_dir is problematic, it can be freed
in del_gendisk() while it can still be accessed before disk_release().
And there in no way to know if the kobject if freed by kobject_put() for
now, thus add a new field in bloce_device to manage refcount of
bd_holder_dir seperately.

Prepare to fix the problem in following patch.

Signed-off-by: Yu Kuai <yukuai3@huawei.com>
---
 block/blk.h               |  3 +++
 block/genhd.c             | 27 +++++++++++++++++++++++++++
 include/linux/blk_types.h |  1 +
 3 files changed, 31 insertions(+)
diff mbox series

Patch

diff --git a/block/blk.h b/block/blk.h
index d6ea0d1a6db0..fef868b4169c 100644
--- a/block/blk.h
+++ b/block/blk.h
@@ -458,6 +458,9 @@  extern const struct address_space_operations def_blk_aops;
 int disk_register_independent_access_ranges(struct gendisk *disk);
 void disk_unregister_independent_access_ranges(struct gendisk *disk);
 
+bool bd_try_get_holder_dir(struct block_device *bdev);
+void bd_put_holder_dir(struct block_device *bdev);
+
 #ifdef CONFIG_FAIL_MAKE_REQUEST
 bool should_fail_request(struct block_device *part, unsigned int bytes);
 #else /* CONFIG_FAIL_MAKE_REQUEST */
diff --git a/block/genhd.c b/block/genhd.c
index 17b33c62423d..53f9c8b2690a 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -375,6 +375,33 @@  int disk_scan_partitions(struct gendisk *disk, fmode_t mode)
 	return 0;
 }
 
+bool bd_try_get_holder_dir(struct block_device *bdev)
+{
+	mutex_lock(&bdev->bd_disk->open_mutex);
+	if (!bdev->holder_dir_ref) {
+		mutex_unlock(&bdev->bd_disk->open_mutex);
+		return false;
+	}
+
+	bdev->holder_dir_ref++;
+	mutex_unlock(&bdev->bd_disk->open_mutex);
+	return true;
+}
+
+void bd_put_holder_dir(struct block_device *bdev)
+{
+	mutex_lock(&bdev->bd_disk->open_mutex);
+	if (WARN_ON(bdev->holder_dir_ref <= 0))
+		goto out;
+
+	if (!(--bdev->holder_dir_ref)) {
+		kobject_put(bdev->bd_holder_dir);
+		bdev->bd_holder_dir = NULL;
+	}
+out:
+	mutex_unlock(&bdev->bd_disk->open_mutex);
+}
+
 /**
  * device_add_disk - add disk information to kernel list
  * @parent: parent device for the disk
diff --git a/include/linux/blk_types.h b/include/linux/blk_types.h
index e0b098089ef2..550c8e15af49 100644
--- a/include/linux/blk_types.h
+++ b/include/linux/blk_types.h
@@ -53,6 +53,7 @@  struct block_device {
 	int			bd_holders;
 	bool			bd_write_holder;
 	struct kobject		*bd_holder_dir;
+	int			holder_dir_ref;
 	u8			bd_partno;
 	spinlock_t		bd_size_lock; /* for bd_inode->i_size updates */
 	struct gendisk *	bd_disk;