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

Wenchao Hao
2022-03-31T12:14:58Z

On 2022/3/31 13:41, Dan Carpenter wrote:
> On Thu, Mar 31, 2022 at 11:26:22AM -0400, 'Wenchao Hao' via syzkaller-bugs wrote:
>> I do not think it's necessary to call device_del() on this path. If the device
>> has been added, put_device() would delete it from sysfs. So the origin error
>> handle is ok with me.
>>
>
> No. The original is buggy and it was detected at runtime by syzbot.
> It's not static analysis, it is an actual bug found in testing.
>
Yes, it's a bug, but the root reason is not we forget to call
device_del(sdkp->disk_dev). It's because we did not cleanup gendisk.
The leak memory is allocated in elevator_init_mq(), we should clean
this memory via blk_cleanup_queue().

I summit a patch which would fix this memory leak:

https://lore.kernel.org/linux-scsi/20220401011018.1026553-1-haowenchao@huawei.com/T/#u

> The device_put() unwinds device_initialize(). The device_del() unwinds
> device_add(). Take a look at the comments to device_add() or take a
> look at how device_register/unregister() work.
>

You may read the implement of put_device(), it is based on kobj_xxx.
If the kobj is still in sysfs, a cleanup would be performed.
And device_del() seems would not decrease the reference count of kobj,
the main aim is to make it invisibleto sysfs.