From: Yang Yingliang Date: Mon, 5 Dec 2022 03:49:04 +0000 (+0800) Subject: driver core: fix potential null-ptr-deref in device_add() X-Git-Tag: v6.1.21~1026 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=7cf515bf9e8c2908dc170ecf2df117162a16c9c5;p=platform%2Fkernel%2Flinux-starfive.git driver core: fix potential null-ptr-deref in device_add() [ Upstream commit f6837f34a34973ef6600c08195ed300e24e97317 ] I got the following null-ptr-deref report while doing fault injection test: BUG: kernel NULL pointer dereference, address: 0000000000000058 CPU: 2 PID: 278 Comm: 37-i2c-ds2482 Tainted: G B W N 6.1.0-rc3+ RIP: 0010:klist_put+0x2d/0xd0 Call Trace: klist_remove+0xf1/0x1c0 device_release_driver_internal+0x196/0x210 bus_remove_device+0x1bd/0x240 device_add+0xd3d/0x1100 w1_add_master_device+0x476/0x490 [wire] ds2482_probe+0x303/0x3e0 [ds2482] This is how it happened: w1_alloc_dev() // The dev->driver is set to w1_master_driver. memcpy(&dev->dev, device, sizeof(struct device)); device_add() bus_add_device() dpm_sysfs_add() // It fails, calls bus_remove_device. // error path bus_remove_device() // The dev->driver is not null, but driver is not bound. __device_release_driver() klist_remove(&dev->p->knode_driver) <-- It causes null-ptr-deref. // normal path bus_probe_device() // It's not called yet. device_bind_driver() If dev->driver is set, in the error path after calling bus_add_device() in device_add(), bus_remove_device() is called, then the device will be detached from driver. But device_bind_driver() is not called yet, so it causes null-ptr-deref while access the 'knode_driver'. To fix this, set dev->driver to null in the error path before calling bus_remove_device(). Fixes: 57eee3d23e88 ("Driver core: Call device_pm_add() after bus_add_device() in device_add()") Signed-off-by: Yang Yingliang Link: https://lore.kernel.org/r/20221205034904.2077765-1-yangyingliang@huawei.com Signed-off-by: Greg Kroah-Hartman Signed-off-by: Sasha Levin --- diff --git a/drivers/base/core.c b/drivers/base/core.c index d02501933467..e5c15061070b 100644 --- a/drivers/base/core.c +++ b/drivers/base/core.c @@ -3551,6 +3551,7 @@ done: device_pm_remove(dev); dpm_sysfs_remove(dev); DPMError: + dev->driver = NULL; bus_remove_device(dev); BusError: device_remove_attrs(dev);