[PATCH-next v2 1/2] driver core: introduce get_device_unless_zero()

From: Zhong Jinghua
Date: Sat Jan 28 2023 - 04:18:01 EST


When the dev reference count is 0, calling get_device will go from 0 to 1,
which will cause errors in some place of the kernel. So introduce a
get_devcie_unless_zero method that returns NULL when the dev reference
count is 0.

Signed-off-by: Zhong Jinghua <zhongjinghua@xxxxxxxxxx>
---
drivers/base/core.c | 8 ++++++++
include/linux/device.h | 1 +
2 files changed, 9 insertions(+)

diff --git a/drivers/base/core.c b/drivers/base/core.c
index d02501933467..6f17a93a3443 100644
--- a/drivers/base/core.c
+++ b/drivers/base/core.c
@@ -3613,6 +3613,14 @@ struct device *get_device(struct device *dev)
}
EXPORT_SYMBOL_GPL(get_device);

+struct device __must_check *get_device_unless_zero(struct device *dev)
+{
+ if (!dev || !kobject_get_unless_zero(&dev->kobj))
+ return NULL;
+ return dev;
+}
+EXPORT_SYMBOL_GPL(get_device_unless_zero);
+
/**
* put_device - decrement reference count.
* @dev: device in question.
diff --git a/include/linux/device.h b/include/linux/device.h
index 424b55df0272..c63bac6d51c8 100644
--- a/include/linux/device.h
+++ b/include/linux/device.h
@@ -1069,6 +1069,7 @@ extern int (*platform_notify_remove)(struct device *dev);
*
*/
struct device *get_device(struct device *dev);
+struct device __must_check *get_device_unless_zero(struct device *dev);
void put_device(struct device *dev);
bool kill_device(struct device *dev);

--
2.31.1