Re: [PATCH v2 6/6] iio: accel: mma8452: use guard() to release mutexes

From: Jonathan Cameron

Date: Fri Apr 24 2026 - 13:30:53 EST


On Wed, 22 Apr 2026 22:26:43 +0530
Sanjay Chitroda <sanjayembeddedse@xxxxxxxxx> wrote:

> From: Sanjay Chitroda <sanjayembeddedse@xxxxxxxxx>
>
> Replace explicit mutex_lock() and mutex_unlock() with the guard() and
> scoped_guard() macro for cleaner and safer mutex handling.
>
> Signed-off-by: Sanjay Chitroda <sanjayembeddedse@xxxxxxxxx>
Hi Sanjay,

This can be taken a step further and give less churn + a cleaner end result.

> ---
> drivers/iio/accel/mma8452.c | 31 ++++++++++++-------------------
> 1 file changed, 12 insertions(+), 19 deletions(-)
>
> diff --git a/drivers/iio/accel/mma8452.c b/drivers/iio/accel/mma8452.c
> index 9983f76a8bcd..1c284bdcc44a 100644
> --- a/drivers/iio/accel/mma8452.c
> +++ b/drivers/iio/accel/mma8452.c
> @@ -18,6 +18,7 @@
> * TODO: orientation events
> */
>
> +#include <linux/cleanup.h>
> #include <linux/delay.h>
> #include <linux/i2c.h>
> #include <linux/mod_devicetable.h>
> @@ -500,9 +501,8 @@ static int mma8452_read_raw(struct iio_dev *indio_dev,
> if (!iio_device_claim_direct(indio_dev))
> return -EBUSY;
>
> - mutex_lock(&data->lock);
> - ret = mma8452_read(data, buffer);
> - mutex_unlock(&data->lock);
> + scoped_guard(mutex, &data->lock)
rest of the maths after this point is trivial an safe to do under locks,
so even better than this change might be to go directly to using
the ACQUIRE magic to handle the direct mode control claiming as well.

case IIO_CHAN_INFO_RAW: {
IIO_DEV_ACQUIRE_DIRECT_MODE(indio_dev, claim);
if (IIO_DEV_ACQUIRE_FAILED(claim))
return -EBUSY;
guard(mutex)(&data->lock);

ret = mma8452_read(data, buffer);
if (ret < 0)
return ret;

*val = sign_extend32(be16_to_cpu(
buffer[chan->scan_index]) >> chan->scan_type.shift,
chan->scan_type.realbits - 1);

return IIO_VAL_INT;
}

There is one other place where it maybe worth using IIO_DEV_ACQUIRE_DIRECT_MODE()
In that location the advantage is tiny but then we'd have all the code in here
using that approach and I think that is worth doing.

+ ret = mma8452_read(data, buffer);
> iio_device_release_direct(indio_dev);
> if (ret < 0)
> return ret;