[PATCH v4 5/5] iio: accel: mma8452: use guard() to release mutexes

From: Sanjay Chitroda

Date: Tue Jun 02 2026 - 09:41:28 EST


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>

---
changes in v4:
- add blank line with input from Andy
- v3 link -> https://lore.kernel.org/all/20260505174640.3998281-11-sanjayembedded@xxxxxxxxx/
changes in v3:
- Following input from Jonathan extended mutex scope for
IIO_CHAN_INFO_RAW case to include math operation under lock
- v2 link -> https://lore.kernel.org/all/20260422165643.2148195-7-sanjayembedded@xxxxxxxxx/
---
drivers/iio/accel/mma8452.c | 30 ++++++++++++------------------
1 file changed, 12 insertions(+), 18 deletions(-)

diff --git a/drivers/iio/accel/mma8452.c b/drivers/iio/accel/mma8452.c
index 85dfd854e2b6..7d0b4560ba2a 100644
--- a/drivers/iio/accel/mma8452.c
+++ b/drivers/iio/accel/mma8452.c
@@ -19,6 +19,7 @@
*/

#include <linux/array_size.h>
+#include <linux/cleanup.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/mod_devicetable.h>
@@ -479,9 +480,9 @@ static int mma8452_read_raw(struct iio_dev *indio_dev,
if (IIO_DEV_ACQUIRE_FAILED(claim))
return -EBUSY;

- mutex_lock(&data->lock);
+ guard(mutex)(&data->lock);
+
ret = mma8452_read(data, buffer);
- mutex_unlock(&data->lock);
if (ret < 0)
return ret;

@@ -579,36 +580,30 @@ static int mma8452_change_config(struct mma8452_data *data, u8 reg, u8 val)
int ret;
int is_active;

- mutex_lock(&data->lock);
+ guard(mutex)(&data->lock);

is_active = mma8452_is_active(data);
- if (is_active < 0) {
- ret = is_active;
- goto fail;
- }
+ if (is_active < 0)
+ return is_active;

/* config can only be changed when in standby */
if (is_active > 0) {
ret = mma8452_standby(data);
if (ret < 0)
- goto fail;
+ return ret;
}

ret = i2c_smbus_write_byte_data(data->client, reg, val);
if (ret < 0)
- goto fail;
+ return ret;

if (is_active > 0) {
ret = mma8452_active(data);
if (ret < 0)
- goto fail;
+ return ret;
}

- ret = 0;
-fail:
- mutex_unlock(&data->lock);
-
- return ret;
+ return 0;
}

static int mma8452_set_power_mode(struct mma8452_data *data, u8 mode)
@@ -1754,9 +1749,8 @@ static int mma8452_runtime_suspend(struct device *dev)
struct mma8452_data *data = iio_priv(indio_dev);
int ret;

- mutex_lock(&data->lock);
- ret = mma8452_standby(data);
- mutex_unlock(&data->lock);
+ scoped_guard(mutex, &data->lock)
+ ret = mma8452_standby(data);
if (ret < 0) {
dev_err(dev, "powering off device failed\n");
return -EAGAIN;

--
2.34.1