Re: [PATCH v2 2/5] iio: chemical: sgp40: Replace manual locking with guard()

From: Joshua Crofts

Date: Mon Nov 02 2026 - 05:10:53 EST


On Mon, 2 Nov 2026 11:12:55 +0200
Jaakko Koivisto <jmatko@xxxxxx> wrote:

> Replace manual mutex_lock() and mutex_unlock() with RAII-style
> guard(mutex)().
>
> Extend the lock in sgp40_measure_resistance_raw() to cover the
> I2C send and receive cycle, preventing I/O-errors if the device
> is currently running a command, or clobbering the output of a previous
> command if a new command is issued during the sleep-period between
> i2c_master_send() and i2c_master_recv().
>
> Signed-off-by: Jaakko Koivisto <jmatko@xxxxxx>
> ---
> drivers/iio/chemical/sgp40.c | 33 +++++++++++++--------------------
> 1 file changed, 13 insertions(+), 20 deletions(-)
>
> diff --git a/drivers/iio/chemical/sgp40.c b/drivers/iio/chemical/sgp40.c
> index 3a239fb6847f..080d51f9f53c 100644
> --- a/drivers/iio/chemical/sgp40.c
> +++ b/drivers/iio/chemical/sgp40.c
> @@ -148,9 +148,8 @@ static int sgp40_calc_voc(struct sgp40_data *data, u16 resistance_raw, int *voc)
> u32 exp = 0;

+ #include <linux/cleanup.h>

> /* we calculate as a multiple of 16384 (2^14) */
> - mutex_lock(&data->lock);
> + guard(mutex)(&data->lock);

Blank lines around any guard() statement. You want to emphasize the fact
that guard is being utilized.

> x = ((int)resistance_raw - data->res_calibbias) * 106;
> - mutex_unlock(&data->lock);

If only a segment of the code has to hold a lock it's better to use
scoped_guard() instead of regular guard().

>
> /* voc = 500 / (1 + e^x) */
> exp = sgp40_exp(x, SGP40_CALC_POWER, 18);
> @@ -172,7 +171,7 @@ static int sgp40_measure_resistance_raw(struct sgp40_data *data, u16 *resistance
> struct sgp40_tg_measure tg = {.command = {0x26, 0x0F}};
> struct sgp40_tg_result tgres;
>

--
Kind regards,
Joshua Crofts