[PATCH 2/5] driver core: Introduce an API constify_device_find_child_helper()
From: Zijun Hu
Date: Sat Aug 10 2024 - 20:19:33 EST
From: Zijun Hu <quic_zijuhu@xxxxxxxxxxx>
Introduce constify_device_find_child_helper() to replace existing
device_find_child()'s usages whose match functions will modify
caller's match data.
Signed-off-by: Zijun Hu <quic_zijuhu@xxxxxxxxxxx>
---
drivers/base/core.c | 35 +++++++++++++++++++++++++++++++++++
include/linux/device.h | 7 +++++++
2 files changed, 42 insertions(+)
diff --git a/drivers/base/core.c b/drivers/base/core.c
index b1dd8c5590dc..3f3ebdb5aa0b 100644
--- a/drivers/base/core.c
+++ b/drivers/base/core.c
@@ -4128,6 +4128,41 @@ struct device *device_find_any_child(struct device *parent)
}
EXPORT_SYMBOL_GPL(device_find_any_child);
+struct fn_data_struct {
+ int (*match)(struct device *dev, void *data);
+ void *data;
+ struct device *target_device;
+};
+
+static int constify_device_match_fn(struct device *dev, void *data)
+{
+ struct fn_data_struct *fn_data = data;
+ int res;
+
+ res = fn_data->match(dev, fn_data->data);
+ if (res && get_device(dev)) {
+ fn_data->target_device = dev;
+ return res;
+ }
+
+ return 0;
+}
+
+/*
+ * My mission is to clean up existing match functions which will modify
+ * caller's match data for device_find_child(), so i do not introduce
+ * myself here to prevent that i am used for any other purpose.
+ */
+struct device *constify_device_find_child_helper(struct device *parent, void *data,
+ int (*match)(struct device *dev, void *data))
+{
+ struct fn_data_struct fn_data = {match, data, NULL};
+
+ device_for_each_child(parent, &fn_data, constify_device_match_fn);
+ return fn_data.target_device;
+}
+EXPORT_SYMBOL_GPL(constify_device_find_child_helper);
+
int __init devices_init(void)
{
devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
diff --git a/include/linux/device.h b/include/linux/device.h
index 34eb20f5966f..b2423fca3d45 100644
--- a/include/linux/device.h
+++ b/include/linux/device.h
@@ -1078,6 +1078,13 @@ struct device *device_find_child(struct device *dev, void *data,
struct device *device_find_child_by_name(struct device *parent,
const char *name);
struct device *device_find_any_child(struct device *parent);
+/*
+ * My mission is to clean up existing match functions which will modify
+ * caller's match data for device_find_child(), so please DO NOT use me
+ * for any other purpose.
+ */
+struct device *constify_device_find_child_helper(struct device *parent, void *data,
+ int (*match)(struct device *dev, void *data));
int device_rename(struct device *dev, const char *new_name);
int device_move(struct device *dev, struct device *new_parent,
--
2.34.1