[PATCH 5.16 0334/1039] block: fix error unwinding in device_add_disk

From: Greg Kroah-Hartman
Date: Mon Jan 24 2022 - 16:48:00 EST


From: Christoph Hellwig <hch@xxxxxx>

[ Upstream commit 99d8690aae4b2f0d1d90075de355ac087f820a66 ]

One device_add is called disk->ev will be freed by disk_release, so we
should free it twice. Fix this by allocating disk->ev after device_add
so that the extra local unwinding can be removed entirely.

Based on an earlier patch from Tetsuo Handa.

Reported-by: syzbot <syzbot+28a66a9fbc621c939000@xxxxxxxxxxxxxxxxxxxxxxxxx>
Tested-by: syzbot <syzbot+28a66a9fbc621c939000@xxxxxxxxxxxxxxxxxxxxxxxxx>
Fixes: 83cbce9574462c6b ("block: add error handling for device_add_disk / add_disk")
Signed-off-by: Christoph Hellwig <hch@xxxxxx>
Link: https://lore.kernel.org/r/20211221161851.788424-1-hch@xxxxxx
Signed-off-by: Jens Axboe <axboe@xxxxxxxxx>
Signed-off-by: Sasha Levin <sashal@xxxxxxxxxx>
---
block/genhd.c | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/block/genhd.c b/block/genhd.c
index 30362aeacac4b..596e43764846b 100644
--- a/block/genhd.c
+++ b/block/genhd.c
@@ -437,10 +437,6 @@ int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
disk->flags |= GENHD_FL_EXT_DEVT;
}

- ret = disk_alloc_events(disk);
- if (ret)
- goto out_free_ext_minor;
-
/* delay uevents, until we scanned partition table */
dev_set_uevent_suppress(ddev, 1);

@@ -451,7 +447,12 @@ int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
ddev->devt = MKDEV(disk->major, disk->first_minor);
ret = device_add(ddev);
if (ret)
- goto out_disk_release_events;
+ goto out_free_ext_minor;
+
+ ret = disk_alloc_events(disk);
+ if (ret)
+ goto out_device_del;
+
if (!sysfs_deprecated) {
ret = sysfs_create_link(block_depr, &ddev->kobj,
kobject_name(&ddev->kobj));
@@ -539,8 +540,6 @@ out_del_block_link:
sysfs_remove_link(block_depr, dev_name(ddev));
out_device_del:
device_del(ddev);
-out_disk_release_events:
- disk_release_events(disk);
out_free_ext_minor:
if (disk->major == BLOCK_EXT_MAJOR)
blk_free_ext_minor(disk->first_minor);
--
2.34.1