[PATCH] scsi: sd: call device_del() if device_add_disk() fails

From: Fabio M. De Francesco
Date: Tue Mar 29 2022 - 11:50:04 EST


In sd_probe(), if device_add_disk() fails it simply calls put_device()
and jumps to the "out" label but the device is never deleted from system.
This leads to a memory leak as reported by Syzbot.[1]

Fix this bug by calling device_del() soon before put_device() when
device_add_disk() fails.

[1] [syzbot] memory leak in blk_mq_init_tags
https://lore.kernel.org/lkml/000000000000c341cc05db38c1b0@xxxxxxxxxx/

Reported-by: syzbot+f08c77040fa163a75a46@xxxxxxxxxxxxxxxxxxxxxxxxx
Suggested-by: Dan Carpenter <dan.carpenter@xxxxxxxxxx>
Fixes: 2a7a891f4c40 ("scsi: sd: Add error handling support for add_disk()")
Signed-off-by: Fabio M. De Francesco <fmdefrancesco@xxxxxxxxx>
---

This patch replace the previous attempt to fix the bug reported by
Syzbot. Therefore, the previous wrong patch at
https://lore.kernel.org/lkml/20220328084452.11479-1-fmdefrancesco@xxxxxxxxx/
must be discarded.

Many thanks to Dan Carpenter.

drivers/scsi/sd.c | 1 +
1 file changed, 1 insertion(+)

diff --git a/drivers/scsi/sd.c b/drivers/scsi/sd.c
index a390679cf458..13d96d0f9dde 100644
--- a/drivers/scsi/sd.c
+++ b/drivers/scsi/sd.c
@@ -3474,6 +3474,7 @@ static int sd_probe(struct device *dev)

error = device_add_disk(dev, gd, NULL);
if (error) {
+ device_del(&sdkp->disk_dev);
put_device(&sdkp->disk_dev);
goto out;
}
--
2.34.1