Re: [PATCH 1/2] devm-helpers: Add resource managed version of mutex init

From: andy . shevchenko
Date: Thu Feb 22 2024 - 16:42:32 EST


Thu, Feb 22, 2024 at 03:58:37PM +0100, Marek Behún kirjoitti:
> A few drivers are doing resource-managed mutex initialization by
> implementing ad-hoc one-liner mutex dropping functions and using them
> with devm_add_action_or_reset(). Help drivers avoid these repeated
> one-liners by adding managed version of mutex initialization.
>
> Use the new function devm_mutex_init() in the following drivers:
> drivers/gpio/gpio-pisosr.c
> drivers/gpio/gpio-sim.c
> drivers/gpu/drm/xe/xe_hwmon.c
> drivers/hwmon/nzxt-smart2.c
> drivers/leds/leds-is31fl319x.c
> drivers/power/supply/mt6370-charger.c
> drivers/power/supply/rt9467-charger.c

Pardon me, but why?

https://lore.kernel.org/linux-leds/20231214173614.2820929-1-gnstark@xxxxxxxxxxxxxxxxx/

Can you cooperate, folks, instead of doing something independently?


> --- a/include/linux/devm-helpers.h
> +++ b/include/linux/devm-helpers.h
> @@ -24,6 +24,8 @@
> */
>
> #include <linux/device.h>
> +#include <linux/kconfig.h>
> +#include <linux/mutex.h>
> #include <linux/workqueue.h>
>
> static inline void devm_delayed_work_drop(void *res)
> @@ -76,4 +78,34 @@ static inline int devm_work_autocancel(struct device *dev,
> return devm_add_action(dev, devm_work_drop, w);
> }
>
> +static inline void devm_mutex_drop(void *res)
> +{
> + mutex_destroy(res);
> +}
> +
> +/**
> + * devm_mutex_init - Resource managed mutex initialization
> + * @dev: Device which lifetime mutex is bound to
> + * @lock: Mutex to be initialized (and automatically destroyed)
> + *
> + * Initialize mutex which is automatically destroyed when driver is detached.
> + * A few drivers initialize mutexes which they want destroyed before driver is
> + * detached, for debugging purposes.
> + * devm_mutex_init() can be used to omit the explicit mutex_destroy() call when
> + * driver is detached.
> + */
> +static inline int devm_mutex_init(struct device *dev, struct mutex *lock)
> +{
> + mutex_init(lock);
> +
> + /*
> + * mutex_destroy() is an empty function if CONFIG_DEBUG_MUTEXES is
> + * disabled. No need to allocate an action in that case.
> + */
> + if (IS_ENABLED(CONFIG_DEBUG_MUTEXES))
> + return devm_add_action_or_reset(dev, devm_mutex_drop, lock);
> + else
> + return 0;
> +}

Cc: George Stark <gnstark@xxxxxxxxxxxxxxxxx>

--
With Best Regards,
Andy Shevchenko