[PATCH 01/12 v2] Platform: add a dev_groups pointer to struct platform_driver

From: Greg Kroah-Hartman
Date: Thu Jul 04 2019 - 08:14:36 EST

Platform drivers like to add sysfs groups to their device, but right now
they have to do it "by hand". The driver core should handle this for
them, but there is no way to get to the bus-default attribute groups as
all platform devices are "special and unique" one-off drivers/devices.

To combat this, add a dev_groups pointer to platform_driver which allows
a platform driver to set up a list of default attributes that will be
properly created and removed by the platform driver core when a probe()
function is successful and removed right before the device is unbound.

Cc: Richard Gong <richard.gong@xxxxxxxxxxxxxxx>
Cc: Romain Izard <romain.izard.pro@xxxxxxxxx>
Cc: "Rafael J. Wysocki" <rafael@xxxxxxxxxx>
Cc: Andy Shevchenko <andriy.shevchenko@xxxxxxxxxxxxxxx>
Cc: Mans Rullgard <mans@xxxxxxxxx>
Cc: Bartosz Golaszewski <bgolaszewski@xxxxxxxxxxxx>
Cc: Randy Dunlap <rdunlap@xxxxxxxxxxxxx>
Cc: Johan Hovold <johan@xxxxxxxxxx>
Cc: linux-kernel@xxxxxxxxxxxxxxx
Signed-off-by: Greg Kroah-Hartman <gregkh@xxxxxxxxxxxxxxxxxxx>
v2: addressed Johan's comments by reordering when we remove the files
from the device, and clean up on an error in a nicer way. Ended up
making the patch smaller overall, always nice.

drivers/base/platform.c | 16 +++++++++++++++-
include/linux/platform_device.h | 1 +
2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/drivers/base/platform.c b/drivers/base/platform.c
index 713903290385..74428a1e03f3 100644
--- a/drivers/base/platform.c
+++ b/drivers/base/platform.c
@@ -614,8 +614,20 @@ static int platform_drv_probe(struct device *_dev)

if (drv->probe) {
ret = drv->probe(dev);
- if (ret)
+ if (ret) {
+ dev_pm_domain_detach(_dev, true);
+ goto out;
+ }
+ }
+ if (drv->dev_groups) {
+ ret = device_add_groups(_dev, drv->dev_groups);
+ if (ret) {
+ if (drv->remove)
+ drv->remove(dev);
dev_pm_domain_detach(_dev, true);
+ return ret;
+ }
+ kobject_uevent(&_dev->kobj, KOBJ_CHANGE);

@@ -638,6 +650,8 @@ static int platform_drv_remove(struct device *_dev)
struct platform_device *dev = to_platform_device(_dev);
int ret = 0;

+ if (drv->dev_groups)
+ device_remove_groups(_dev, drv->dev_groups);
if (drv->remove)
ret = drv->remove(dev);
dev_pm_domain_detach(_dev, true);
diff --git a/include/linux/platform_device.h b/include/linux/platform_device.h
index cc464850b71e..027f1e1d7af8 100644
--- a/include/linux/platform_device.h
+++ b/include/linux/platform_device.h
@@ -190,6 +190,7 @@ struct platform_driver {
int (*resume)(struct platform_device *);
struct device_driver driver;
const struct platform_device_id *id_table;
+ const struct attribute_group **dev_groups;
bool prevent_deferred_probe;