Skip to contentSkip to conversation

iio: light: add support for veml6031x00 ALS series

PATCH Superseded Javier Carrasco 3 participants 14 messages Sep 1 – Sep 13

Subsystems (4)

v8 of 10 Superseded Latest is v10 →

lore
Share & tools
lore

Javier Carrasco

author maintainer
#0 lore raw

v8 cover iio: light: add support for veml6031x00 ALS series

These ambient light sensors with I2C interface provide two light channels (ALS and IR), high/low threshold alarms with configurable persistence, and a data ready signal.

The devices covered by this driver have the same resolution, and they share most of their functionality. These are the differences between them (note that the x belongs to their names, and it is not a wildcard):

- Device ID: accessible via two 8-bit registers, different values for veml6031x00/veml6031x01 and veml60311x00/veml60311x01.
- I2C address: same grouping, 0x29 and 0x10 I2C addresses.
- AEC qualification: AEC-Q100 for veml6031x00/veml60311x00 and AEC-Q101 for veml6031x01/veml60311x01.

The alarms and the data ready signals share the interrupt pin, and an interrupt status register must be accessed to identify the source. Such multiplexing is not new in IIO, and I have followed existing examples for it. The persistence setting (own attribute) to trigger the alarms uses the pattern that has already been used for the veml6030.

The device configuration is in general documented in the datasheet and the application note. There is an exception, though: the activation of the "active force" mode that is required for the data ready signal must be carried out in two steps even though the affected bits are located in the same register: first ALS_AF (active force mode enable) must be set, and then ALS_TRIG (active force trigger setting) must be enabled. I have added a brief commentary in the code to explain this behavior, which has been confirmed by the manufacturer.

The datasheet specifies the scale and integration time for the ALS channel. Although both settings also affect the measured IR value, no transfer function, accuracy, or calibration is specified for converting the IR output into a physical quantity. The IR channel is therefore intended only as a qualitative indication of the infrared content of the incident light, rather than as a precision measurement channel. Consequently, the driver does not expose scale or integration time as IR-channel attributes.

The only functionality that has not been implemented yet is the x0.66 gain (and its x0.165 counterpart when PD_DIV=1), which makes the gts helpers less usable due to the conversions required. It is indeed an uncommon gain to use (there are x0.5 and x0.125 gains) with no known use-case at the moment that justifies making adjustments to the gts helpers or adding artificial conversions to make it work.

This driver has been tested with the four supported devices separately as well as in pairs where the I2C addresses don't overlap.

To: Jonathan Cameron <[email protected]>
To: Lars-Peter Clausen <[email protected]>
To: Rob Herring <[email protected]>
To: Krzysztof Kozlowski <[email protected]>
To: Conor Dooley <[email protected]>
To: David Lechner <[email protected]>
To: Nuno Sá <[email protected]>
To: Andy Shevchenko <[email protected]>

Changes in v8:
- [2/4] declare *dev = regmap_get_device() instead of calling it in dev_warn().
- [4/4] split regmap writable ranges to avoid holes (reserved registers).
- [4/4] Use is_power_of_2() and ilog2() instead of hweight8() and ffs().
- [4/4] Minor modifications suggested by Andy Shevchenko (direct return of devm_add_action_or_reset(), unsigned where required, split regval assignment).

- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- [2..4/4] Refactor probe() (extract IIO device initialization, more logical initialization order).
- [2/4] Drop pm_runtime_get_noresume() and pm_runtime_put_autosuspend()
in the probe function and let the core handle it.
- [2/4] Rephrase unknwon ID info message.
- [2/4] Rephrase Commit message to make it independent of [3..4/4]
- [2/4] Trailing comma after last channel in iio_chan_spec.
- [2/4] Return -ENODATA if i2c_get_match_data() fails.
- [2/4] Use logical splits and local variables to make lines shorter.
- [2..4/4] Use regmap_assign_bits() instead of regmap_update_bits() where it makes sense.
- [4/4] Use pm_runtime_put_sync()
- [4/4] Explicitly include <linux/lockdep.h> for lockdep_assert_held().
- [4/4] Use helpers to refactor code without adding goto jumps within scoped guards.
- [4/4] Drop own trigger assignment.
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- [1/4] Fix dt-binding title.
- [2/4] Update headers as indicated by Andy and Uwe.
- [2/4] Macro to get selector from gain registers.
- [2/4] Use pm_runtime_get_noresume() (no devres).
- [2/4] Drop <linux/mod_devicetable.h>
- [2/4] Use regmap_update_bits() to set power state.
- [3/4] Add scan info for the non-irq variant.
- [3/4] Fix lock acquisition (direct mode and then scale_lock).
- [3/4] Zero-initialize scan buffer.
- [4/4] Store timestamp before calling iio_trigger_poll_nested().
- [4/4] Move mutex_init and regfield_init before setup_irq().
- [4/4] Add lockdep_assert_held() to veml6031x00_interrupt().
- [4/4] Avoid register read if a spurious interrupt arrives when the device is powered down.
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- [2/4] Explicit inclusion of some missing used headers.
- [2/4] Define CONF0 as volatile to account for AF_TRIG (reset by hardware).
- [2/4] Drop integration time and scale for IR channel.
- [2/4] Use unsigned int instead of int where no negative values are possible.
- [2/4] Write a helper to update the gain and use it where needed.
- [2/4] Move i2c_get_match() closer to the data allocation.
- [2/4] Move iio dev initialization out of the runtime pm region.
- [2/4] Lower log level for unknown ID part.
- [2/4] Redefine gains as _INT_MILLI.
- [2/4] Drop pointer to the device in the private structure.
- [2/4] Fix some coding-style issues.
- [4/4] Add second iio_chan_spec to avoid exposing dead sysfs attributes if no irq is available.
- [4/4] Refactor goto calls in functions with guard().
- [3/4] Use IIO_DECLARE_BUFFER_WITH_TS() instead of a custom structure.
- [4/4] Use format instead of deprecated sign for the scan type.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- [1/4] Entry in alphabetical order for MAINTAINERS.
- [2/4] Fix style for device ID tables.
- [2/4] Add missing header mod_devicetable.h and move iio/sysfs.h to
[4/4] for the persistence attribute.
- [2/4] Move IIO_DEV_ACQUIRE_DIRECT_MODE to [3/4] where buffers are
added.
- [3/4] Use test_bit() to check the active scan mask.
- [2/4] Add mutex for operations on scattered register fields.
- [2/4] Add shutdown action after turning the device on.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Move veml6030 fixes to a separate patch stack.
- Use C99 initializers for i2c_device_id.
- Split driver code into multiple patches to ease its review.
- Rework locking to get rid of atomic increment/decrement ops.
- Fix error paths in pm_runtime operations.
- Use IIO_DEV_ACQUIRE_DIRECT_MODE for single read/write ops.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Add commit to fix bug in veml6030.c (channel type when pushing
events) and remove dead code.
- Use gts helpers to simplify operations.
- Drop unused gain_idx.
- Build INT_MASK as an OR operation of the involved bits.
- Format arrays to follow the desired standard for IIO.
- Directly return function result as the last operation within another function instead of 'ret = x; if (ret) return ret; return 0;'.
- Fix some spacing (double space, tab for alignemnt in info struct).
- Use sizeof() for __le16 reg instead of 2.
- Return an error if the part ID could not be read.
- Spell out sd -> shutdown.
- Use devm_mutex_init() instead of mutex_init().
- Avoid using conditional guard, use claim/release instead.
- Access integration times from the global array to get and set the integration time instead of using a switch.
- Simplify read of available periods (persistence).
- Drop IRQF_TRIGGER_FALLING in the threaded irq request.
- Add regmap ranges.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Javier Carrasco (4):
dt-bindings: iio: light: veml6030: add veml6031x00 ALS series
iio: light: add support for veml6031x00 ALS series
iio: light: veml6031x00: add support for triggered buffers
iio: light: veml6031x00: add support for events and trigger

 .../bindings/iio/light/vishay,veml6030.yaml        |   13 +-
 MAINTAINERS                                        |    6 +
 drivers/iio/light/Kconfig                          |   14 +
 drivers/iio/light/Makefile                         |    1 +
 drivers/iio/light/veml6031x00.c                    | 1370 ++++++++++++++++++++
 5 files changed, 1403 insertions(+), 1 deletion(-)

---
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
change-id: 20241109-veml6031x00-aa9463da064a

Best regards,

Signature · 1 line
Javier Carrasco <[email protected]>
author maintainer
#1 lore raw

PATCH v8 1/4 dt-bindings: iio: light: veml6030: add veml6031x00 ALS series

These ambient light sensors share their properties with the ones from the same manufacturer that are supported by this bindings.

Note that only two datasheets are provided as every one of them covers two devices (veml6031x00/veml60311x00 and veml6031x01/veml60311x01).

---
 .../devicetree/bindings/iio/light/vishay,veml6030.yaml      | 13 ++++++++++++-
 MAINTAINERS                                                 |  5 +++++
 2 files changed, 17 insertions(+), 1 deletion(-)
Documentation/devicetree/bindings/iio/light/vishay,veml6030.yaml +12 -1
index 0041e1db6838..a44de649184a 100644
@@ -4,7 +4,8 @@
 $id: http://devicetree.org/schemas/iio/light/vishay,veml6030.yaml#
 $schema: http://devicetree.org/meta-schemas/core.yaml#
 
-title: VEML3235, VEML3328, VEML6030, VEML6035 and VEML7700 Ambient Light Sensors (ALS)
+title: VEML3235, VEML3328, VEML6030, VEML6031x00 series, VEML6035
+  and VEML7700 Ambient Light Sensors (ALS)
 
 maintainers:
   - Rishi Gupta <[email protected]>
@@ -23,6 +24,8 @@ description: |
     https://www.vishay.com/docs/80131/veml3235.pdf
     https://www.vishay.com/docs/84968/veml3328.pdf
     https://www.vishay.com/docs/84366/veml6030.pdf
+    https://www.vishay.com/docs/80007/veml6031x00.pdf
+    https://www.vishay.com/docs/80008/veml6031x01.pdf
     https://www.vishay.com/docs/84889/veml6035.pdf
     https://www.vishay.com/docs/84286/veml7700.pdf
 
@@ -32,6 +35,10 @@ properties:
       - vishay,veml3235
       - vishay,veml3328
       - vishay,veml6030
+      - vishay,veml6031x00
+      - vishay,veml6031x01
+      - vishay,veml60311x00
+      - vishay,veml60311x01
       - vishay,veml6035
       - vishay,veml7700
 
@@ -69,6 +76,8 @@ allOf:
       properties:
         compatible:
           enum:
+            - vishay,veml6031x00
+            - vishay,veml6031x01
             - vishay,veml6035
     then:
       properties:
@@ -82,6 +91,8 @@ allOf:
           enum:
             - vishay,veml3235
             - vishay,veml3328
+            - vishay,veml60311x00
+            - vishay,veml60311x01
             - vishay,veml7700
     then:
       properties:
MAINTAINERS +5 -0
index 3a19da74d00c..57202b51fb66 100644
@@ -29095,6 +29095,11 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/iio/light/vishay,veml6030.yaml
 F:	drivers/iio/light/veml6030.c
 
+VISHAY VEML6031X00 AMBIENT LIGHT SENSOR DRIVER
+M:	Javier Carrasco <[email protected]>
+S:	Maintained
+F:	Documentation/devicetree/bindings/iio/light/vishay,veml6030.yaml
+
 VISHAY VEML6046X00 RGBIR COLOR SENSOR DRIVER
 M:	Andreas Klinger <[email protected]>
 S:	Maintained
Signature · 1 line
2.43.0
author maintainer
#2 lore raw

PATCH v8 2/4 iio: light: add support for veml6031x00 ALS series

In reply to Javier Carrasco

Support device identification, raw ALS and IR readings, and configuration of the scale and integration time.

---
 MAINTAINERS                     |   1 +
 drivers/iio/light/Kconfig       |  12 +
 drivers/iio/light/Makefile      |   1 +
 drivers/iio/light/veml6031x00.c | 678 ++++++++++++++++++++++++++++++++++++++++
 4 files changed, 692 insertions(+)
MAINTAINERS +1 -0
index 57202b51fb66..c83f5af23d97 100644
@@ -29099,6 +29099,7 @@ VISHAY VEML6031X00 AMBIENT LIGHT SENSOR DRIVER
 M:	Javier Carrasco <[email protected]>
 S:	Maintained
 F:	Documentation/devicetree/bindings/iio/light/vishay,veml6030.yaml
+F:	drivers/iio/light/veml6031x00.c
 
 VISHAY VEML6046X00 RGBIR COLOR SENSOR DRIVER
 M:	Andreas Klinger <[email protected]>
drivers/iio/light/Kconfig +12 -0
index f23bbce12c72..02291abeff60 100644
@@ -741,6 +741,18 @@ config VEML6030
 	  To compile this driver as a module, choose M here: the
 	  module will be called veml6030.
 
+config VEML6031X00
+	tristate "VEML6031X00 ambient light sensor series"
+	select REGMAP_I2C
+	select IIO_GTS_HELPER
+	depends on I2C
+	help
+	  Say Y here if you want to build a driver for the Vishay VEML6031X00
+	  ambient light sensor series.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called veml6031x00.
+
 config VEML6040
 	tristate "VEML6040 RGBW light sensor"
 	select REGMAP_I2C
drivers/iio/light/Makefile +1 -0
index 64e354c49ed8..6672ed01a819 100644
@@ -68,6 +68,7 @@ obj-$(CONFIG_VCNL4035)		+= vcnl4035.o
 obj-$(CONFIG_VEML3235)		+= veml3235.o
 obj-$(CONFIG_VEML3328)		+= veml3328.o
 obj-$(CONFIG_VEML6030)		+= veml6030.o
+obj-$(CONFIG_VEML6031X00)	+= veml6031x00.o
 obj-$(CONFIG_VEML6040)		+= veml6040.o
 obj-$(CONFIG_VEML6046X00)	+= veml6046x00.o
 obj-$(CONFIG_VEML6070)		+= veml6070.o
drivers/iio/light/veml6031x00.c new file +678 -0

678 lines not on this page · raw message

Signature · 1 line
2.43.0
author maintainer
#3 lore raw

PATCH v8 3/4 iio: light: veml6031x00: add support for triggered buffers

In reply to Javier Carrasco

Add triggered buffer functionality for the two channels the device provides (ALS and IR).

---
 drivers/iio/light/Kconfig       |   2 +
 drivers/iio/light/veml6031x00.c | 113 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 115 insertions(+)
drivers/iio/light/Kconfig +2 -0
index 02291abeff60..462fff1ddef2 100644
@@ -745,6 +745,8 @@ config VEML6031X00
 	tristate "VEML6031X00 ambient light sensor series"
 	select REGMAP_I2C
 	select IIO_GTS_HELPER
+	select IIO_BUFFER
+	select IIO_TRIGGERED_BUFFER
 	depends on I2C
 	help
 	  Say Y here if you want to build a driver for the Vishay VEML6031X00
drivers/iio/light/veml6031x00.c +113 -0

168 lines not on this page · raw message

Signature · 1 line
2.43.0
#4 lore raw

Re: [PATCH v8 3/4] iio: light: veml6031x00: add support for triggered buffers

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Spurious I2C hardware read of CONF0 register in trigger handler --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Spurious I2C hardware read of CONF0 register in trigger handler --

commit bd3b6c2cea8a14ae14e9c9db625cc2c4fc898c75
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for triggered buffers

Add triggered buffer functionality for the two channels the device provides (ALS and IR).

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index f3772577a05d5..3d5a27a0baaed 100644

[ ... ]

Quoted 11 lines
drivers/iio/light/veml6031x00.c +11 -0
+static irqreturn_t veml6031x00_trig_handler(int irq, void *p)
+{
+	struct iio_poll_func *pf = p;
+	struct iio_dev *iio = pf->indio_dev;
+	struct veml6031x00_data *data = iio_priv(iio);
+	struct regmap *map = data->regmap;
+	IIO_DECLARE_BUFFER_WITH_TS(__le16, scan, 2) = { };
+	unsigned int i;
+	int ch, ret;
+
+	if (test_bit(VEML6031X00_SCAN_ALS, iio->active_scan_mask) &&

drivers/iio/light/veml6031x00.c static const struct iio_info veml6031x00_info = { · line 579

Quoted 10 lines
drivers/iio/light/veml6031x00.c +10 -0
+	    test_bit(VEML6031X00_SCAN_IR, iio->active_scan_mask)) {
+		ret = regmap_bulk_read(map, VEML6031X00_REG_ALS_L,
+				       scan, 2 * sizeof(*scan));
+		if (ret)
+			goto done;
+	} else {
+		i = 0;
+		iio_for_each_active_channel(iio, ch) {
+			ret = regmap_bulk_read(map, iio->channels[ch].address,
+					       &scan[i++], sizeof(*scan));

[Severity: Medium]
Will this loop perform a spurious I2C hardware read of the CONF0 register?

When userspace enables the timestamp channel and only one of the data channels (ALS or IR), the first if condition fails and the code falls back to this else block.

iio_for_each_active_channel() iterates over all set bits in the scan mask, including the timestamp channel. Since .address is implicitly 0 for the timestamp channel, does this mean regmap_bulk_read() will read from address 0 (VEML6031X00_REG_CONF0) when processing the timestamp channel?

Should there be a check to skip the timestamp channel before reading from the hardware, for example by checking if iio->channels[ch].type != IIO_TIMESTAMP?

Quoted 12 lines
drivers/iio/light/veml6031x00.c +12 -0
+			if (ret)
+				goto done;
+		}
+	}
+
+	iio_push_to_buffers_with_ts(iio, scan, sizeof(scan), pf->timestamp);
+
+done:
+	iio_trigger_notify_done(iio->trig);
+
+	return IRQ_HANDLED;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#5 lore raw

PATCH v8 4/4 iio: light: veml6031x00: add support for events and trigger

In reply to Javier Carrasco

The device provides a shared interrupt line to notify events and data ready.

Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

---
 drivers/iio/light/veml6031x00.c | 593 +++++++++++++++++++++++++++++++++++++++-
 1 file changed, 586 insertions(+), 7 deletions(-)
drivers/iio/light/veml6031x00.c +586 -7
index 3d5a27a0baae..7bd7975eb1a7 100644
@@ -15,6 +15,7 @@
 #include <linux/i2c.h>
 #include <linux/interrupt.h>
 #include <linux/limits.h>
+#include <linux/lockdep.h>
 #include <linux/module.h>
 #include <linux/mutex.h>
 #include <linux/pm_runtime.h>
@@ -25,6 +26,9 @@
 #include <asm/byteorder.h>
 
 #include <linux/iio/iio.h>
+#include <linux/iio/events.h>
+#include <linux/iio/sysfs.h>
+#include <linux/iio/trigger.h>
 #include <linux/iio/iio-gts-helper.h>
 #include <linux/iio/triggered_buffer.h>
 #include <linux/iio/trigger_consumer.h>
@@ -32,16 +36,28 @@
 /* Device registers */
 #define VEML6031X00_REG_CONF0       0x00
 #define VEML6031X00_REG_CONF1       0x01
+#define VEML6031X00_REG_WH_L        0x04
+#define VEML6031X00_REG_WH_H        0x05
+#define VEML6031X00_REG_WL_L        0x06
+#define VEML6031X00_REG_WL_H        0x07
 #define VEML6031X00_REG_ALS_L       0x10
 #define VEML6031X00_REG_ALS_H       0x11
 #define VEML6031X00_REG_IR_L        0x12
 #define VEML6031X00_REG_IR_H        0x13
 #define VEML6031X00_REG_ID_L        0x14
 #define VEML6031X00_REG_ID_H        0x15
+#define VEML6031X00_REG_INT         0x17
 
 /* Bit masks for specific functionality */
 #define VEML6031X00_CONF0_SD        BIT(0)
+#define VEML6031X00_CONF0_AF_TRIG   BIT(2)
+#define VEML6031X00_CONF0_AF        BIT(3)
 #define VEML6031X00_CONF1_IR_SD     BIT(7)
+#define VEML6031X00_INT_TH_H        BIT(1)
+#define VEML6031X00_INT_TH_L        BIT(2)
+#define VEML6031X00_INT_DRDY        BIT(3)
+#define VEML6031X00_INT_MASK \
+	(VEML6031X00_INT_TH_L | VEML6031X00_INT_TH_H | VEML6031X00_INT_DRDY)
 
 #define VEML6031X00_GAIN_SEL(pd_div4, gain) (((pd_div4) << 2) | (gain))
 
@@ -53,8 +69,10 @@ enum veml6031x00_scan {
 
 struct veml6031x00_rf {
 	struct regmap_field *gain;
+	struct regmap_field *int_en;
 	struct regmap_field *it;
 	struct regmap_field *pd_div4;
+	struct regmap_field *pers;
 };
 
 struct veml6031x00_chip {
@@ -65,6 +83,7 @@ struct veml6031x00_chip {
 struct veml6031x00_data {
 	struct iio_gts gts;
 	struct regmap *regmap;
+	struct iio_trigger *trig;
 	struct veml6031x00_rf rf;
 	const struct veml6031x00_chip *chip;
 	/*
@@ -73,6 +92,14 @@ struct veml6031x00_data {
 	 * consistent set.
 	 */
 	struct mutex scale_lock;
+	/*
+	 * Serialize access to irq enable/disable by events and trigger
+	 * (shared line).
+	 */
+	struct mutex irq_lock;
+	unsigned int interrupt_users;
+	bool ev_en;
+	bool trig_en;
 };
 
 static const struct iio_itime_sel_mul veml6031x00_it_sel[] = {
@@ -107,6 +134,17 @@ static const struct iio_gain_sel_pair veml6031x00_gain_sel[] = {
 	GAIN_SCALE_GAIN(16, VEML6031X00_SEL_GAIN_2_000),
 };
 
+static IIO_CONST_ATTR(in_illuminance_thresh_either_period_available, "1 2 4 8");
+
+static struct attribute *veml6031x00_event_attributes[] = {
+	&iio_const_attr_in_illuminance_thresh_either_period_available.dev_attr.attr,
+	NULL
+};
+
+static const struct attribute_group veml6031x00_event_attr_group = {
+	.attrs = veml6031x00_event_attributes,
+};
+
 /*
  * The shutdown bits (SD and ALS_IR_SD) are in different registers, and both
  * must be updated when changing the device power state.
@@ -135,6 +173,23 @@ static void veml6031x00_als_shutdown_action(void *data)
 		dev_warn(dev, "Failed to shut down device: %d\n", ret);
 }
 
+static const struct iio_event_spec veml6031x00_event_spec[] = {
+	{
+		.type = IIO_EV_TYPE_THRESH,
+		.dir = IIO_EV_DIR_RISING,
+		.mask_separate = BIT(IIO_EV_INFO_VALUE),
+	}, {
+		.type = IIO_EV_TYPE_THRESH,
+		.dir = IIO_EV_DIR_FALLING,
+		.mask_separate = BIT(IIO_EV_INFO_VALUE),
+	}, {
+		.type = IIO_EV_TYPE_THRESH,
+		.dir = IIO_EV_DIR_EITHER,
+		.mask_separate = BIT(IIO_EV_INFO_PERIOD) |
+				 BIT(IIO_EV_INFO_ENABLE),
+	},
+};
+
 static const struct iio_chan_spec veml6031x00_channels[] = {
 	{
 		.type = IIO_LIGHT,
@@ -169,9 +224,47 @@ static const struct iio_chan_spec veml6031x00_channels[] = {
 	IIO_CHAN_SOFT_TIMESTAMP(VEML6031X00_SCAN_TIMESTAMP),
 };
 
+static const struct iio_chan_spec veml6031x00_channels_irq[] = {
+	{
+		.type = IIO_LIGHT,
+		.address = VEML6031X00_REG_ALS_L,
+		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
+				      BIT(IIO_CHAN_INFO_INT_TIME) |
+				      BIT(IIO_CHAN_INFO_SCALE),
+		.info_mask_separate_available = BIT(IIO_CHAN_INFO_INT_TIME) |
+						BIT(IIO_CHAN_INFO_SCALE),
+		.event_spec = veml6031x00_event_spec,
+		.num_event_specs = ARRAY_SIZE(veml6031x00_event_spec),
+		.scan_index = VEML6031X00_SCAN_ALS,
+		.scan_type = {
+			.format = IIO_SCAN_FORMAT_UNSIGNED_INT,
+			.realbits = 16,
+			.storagebits = 16,
+			.endianness = IIO_LE,
+		},
+	},
+	{
+		.type = IIO_INTENSITY,
+		.address = VEML6031X00_REG_IR_L,
+		.modified = 1,
+		.channel2 = IIO_MOD_LIGHT_IR,
+		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
+		.scan_index = VEML6031X00_SCAN_IR,
+		.scan_type = {
+			.format = IIO_SCAN_FORMAT_UNSIGNED_INT,
+			.realbits = 16,
+			.storagebits = 16,
+			.endianness = IIO_LE,
+		},
+	},
+	IIO_CHAN_SOFT_TIMESTAMP(VEML6031X00_SCAN_TIMESTAMP),
+};
+
 static const struct regmap_range veml6031x00_readable_ranges[] = {
 	regmap_reg_range(VEML6031X00_REG_CONF0, VEML6031X00_REG_CONF1),
+	regmap_reg_range(VEML6031X00_REG_WH_L, VEML6031X00_REG_WL_H),
 	regmap_reg_range(VEML6031X00_REG_ALS_L, VEML6031X00_REG_ID_H),
+	regmap_reg_range(VEML6031X00_REG_INT, VEML6031X00_REG_INT),
 };
 
 static const struct regmap_access_table veml6031x00_readable_table = {
@@ -181,6 +274,7 @@ static const struct regmap_access_table veml6031x00_readable_table = {
 
 static const struct regmap_range veml6031x00_writable_ranges[] = {
 	regmap_reg_range(VEML6031X00_REG_CONF0, VEML6031X00_REG_CONF1),
+	regmap_reg_range(VEML6031X00_REG_WH_L, VEML6031X00_REG_WL_H),
 };
 
 static const struct regmap_access_table veml6031x00_writable_table = {
@@ -192,6 +286,7 @@ static const struct regmap_range veml6031x00_volatile_ranges[] = {
 	/* AF_TRIG in CONF0 is volatile */
 	regmap_reg_range(VEML6031X00_REG_CONF0, VEML6031X00_REG_CONF0),
 	regmap_reg_range(VEML6031X00_REG_ALS_L, VEML6031X00_REG_IR_H),
+	regmap_reg_range(VEML6031X00_REG_INT, VEML6031X00_REG_INT),
 };
 
 static const struct regmap_access_table veml6031x00_volatile_table = {
@@ -199,6 +294,15 @@ static const struct regmap_access_table veml6031x00_volatile_table = {
 	.n_yes_ranges = ARRAY_SIZE(veml6031x00_volatile_ranges),
 };
 
+static const struct regmap_range veml6031x00_precious_ranges[] = {
+	regmap_reg_range(VEML6031X00_REG_INT, VEML6031X00_REG_INT),
+};
+
+static const struct regmap_access_table veml6031x00_precious_table = {
+	.yes_ranges = veml6031x00_precious_ranges,
+	.n_yes_ranges = ARRAY_SIZE(veml6031x00_precious_ranges),
+};
+
 static const struct regmap_config veml6031x00_regmap_config = {
 	.name = "veml6031x00_regmap",
 	.reg_bits = 8,
@@ -206,13 +310,20 @@ static const struct regmap_config veml6031x00_regmap_config = {
 	.rd_table = &veml6031x00_readable_table,
 	.wr_table = &veml6031x00_writable_table,
 	.volatile_table = &veml6031x00_volatile_table,
-	.max_register = VEML6031X00_REG_ID_H,
+	.precious_table = &veml6031x00_precious_table,
+	.max_register = VEML6031X00_REG_INT,
 	.cache_type = REGCACHE_MAPLE,
 };
 
+static const struct reg_field veml6031x00_rf_int_en =
+	REG_FIELD(VEML6031X00_REG_CONF0, 1, 1);
+
 static const struct reg_field veml6031x00_rf_it =
 	REG_FIELD(VEML6031X00_REG_CONF0, 4, 6);
 
+static const struct reg_field veml6031x00_rf_pers =
+	REG_FIELD(VEML6031X00_REG_CONF1, 1, 2);
+
 static const struct reg_field veml6031x00_rf_gain =
 	REG_FIELD(VEML6031X00_REG_CONF1, 3, 4);
 
@@ -236,11 +347,21 @@ static int veml6031x00_regfield_init(struct veml6031x00_data *data)
 		return PTR_ERR(rm_field);
 	rf->it = rm_field;
 
+	rm_field = devm_regmap_field_alloc(dev, map, veml6031x00_rf_int_en);
+	if (IS_ERR(rm_field))
+		return PTR_ERR(rm_field);
+	rf->int_en = rm_field;
+
 	rm_field = devm_regmap_field_alloc(dev, map, veml6031x00_rf_pd_div4);
 	if (IS_ERR(rm_field))
 		return PTR_ERR(rm_field);
 	rf->pd_div4 = rm_field;
 
+	rm_field = devm_regmap_field_alloc(dev, map, veml6031x00_rf_pers);
+	if (IS_ERR(rm_field))
+		return PTR_ERR(rm_field);
+	rf->pers = rm_field;
+
 	return 0;
 }
 
@@ -341,6 +462,31 @@ static int veml6031x00_set_it(struct iio_dev *iio, int val, int val2)
 	return veml6031x00_write_gain(data, gain_sel);
 }
 
+static int veml6031x00_read_period(struct iio_dev *iio, int *val)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+	unsigned int regval;
+	int ret;
+
+	ret = regmap_field_read(data->rf.pers, &regval);
+	if (ret)
+		return ret;
+
+	*val = BIT(regval);
+
+	return IIO_VAL_INT;
+}
+
+static int veml6031x00_write_period(struct iio_dev *iio, int val)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+
+	if (val < 0 || val > 8 || !is_power_of_2(val))
+		return -EINVAL;
+
+	return regmap_field_write(data->rf.pers, ilog2(val));
+}
+
 static int veml6031x00_set_scale(struct iio_dev *iio, int val, int val2)
 {
 	struct veml6031x00_data *data = iio_priv(iio);
@@ -395,6 +541,55 @@ static int veml6031x00_get_scale(struct veml6031x00_data *data, int *val, int *v
 	return IIO_VAL_INT_PLUS_NANO;
 }
 
+static int veml6031x00_read_th(struct iio_dev *iio, enum iio_event_direction dir,
+			       int *val, int *val2)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+	__le16 regval;
+	int ret;
+
+	if (dir == IIO_EV_DIR_RISING)
+		ret = regmap_bulk_read(data->regmap, VEML6031X00_REG_WH_L,
+				       &regval, sizeof(regval));
+	else
+		ret = regmap_bulk_read(data->regmap, VEML6031X00_REG_WL_L,
+				       &regval, sizeof(regval));
+	if (ret)
+		return ret;
+
+	*val = le16_to_cpu(regval);
+
+	return IIO_VAL_INT;
+}
+
+static int veml6031x00_write_th(struct iio_dev *iio, enum iio_event_direction dir,
+				int val, int val2)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+	struct device *dev = regmap_get_device(data->regmap);
+	__le16 regval;
+	int ret;
+
+	if (val < 0 || val > U16_MAX || val2)
+		return -EINVAL;
+
+	regval = cpu_to_le16(val);
+
+	if (dir == IIO_EV_DIR_RISING) {
+		ret = regmap_bulk_write(data->regmap, VEML6031X00_REG_WH_L,
+					&regval, sizeof(regval));
+		if (ret)
+			dev_dbg(dev, "Failed to set high threshold %d\n", ret);
+	} else {
+		ret = regmap_bulk_write(data->regmap, VEML6031X00_REG_WL_L,
+					&regval, sizeof(regval));
+		if (ret)
+			dev_dbg(dev, "Failed to set low threshold %d\n", ret);
+	}
+
+	return ret;
+}
+
 static int veml6031x00_single_read(struct iio_dev *iio, enum iio_chan_type type,
 				   int *val)
 {
@@ -509,13 +704,240 @@ static int veml6031x00_write_raw_get_fmt(struct iio_dev *indio_dev,
 	}
 }
 
+static int veml6031x00_set_interrupt(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{
+	int ret;
+
+	lockdep_assert_held(&data->irq_lock);
+
+	if (state) {
+		data->interrupt_users++;
+		if (data->interrupt_users > 1)
+			return 0;
+	} else {
+		data->interrupt_users--;
+		if (data->interrupt_users > 0)
+			return 0;
+	}
+
+	ret = regmap_field_write(data->rf.int_en, state);
+	if (ret) {
+		if (state)
+			data->interrupt_users--;
+		else
+			data->interrupt_users++;
+	}
+
+	return ret;
+}
+
+static int veml6031x00_read_event_val(struct iio_dev *iio,
+				      const struct iio_chan_spec *chan,
+				      enum iio_event_type type,
+				      enum iio_event_direction dir,
+				      enum iio_event_info info,
+				      int *val, int *val2)
+{
+	switch (type) {
+	case IIO_EV_TYPE_THRESH:
+		if (dir == IIO_EV_DIR_EITHER && info == IIO_EV_INFO_PERIOD)
+			return veml6031x00_read_period(iio, val);
+
+		return veml6031x00_read_th(iio, dir, val, val2);
+	default:
+		return -EINVAL;
+	}
+}
+
+static int veml6031x00_write_event_val(struct iio_dev *iio,
+				       const struct iio_chan_spec *chan,
+				       enum iio_event_type type,
+				       enum iio_event_direction dir,
+				       enum iio_event_info info,
+				       int val, int val2)
+{
+	switch (info) {
+	case IIO_EV_INFO_VALUE:
+		return veml6031x00_write_th(iio, dir, val, val2);
+	case IIO_EV_INFO_PERIOD:
+		return veml6031x00_write_period(iio, val);
+	default:
+		return -EINVAL;
+	}
+}
+
+static int veml6031x00_read_event_config(struct iio_dev *iio,
+					 const struct iio_chan_spec *chan,
+					 enum iio_event_type type,
+					 enum iio_event_direction dir)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+
+	guard(mutex)(&data->irq_lock);
+
+	return data->ev_en;
+}
+
+static int veml6031x00_event_enable(struct veml6031x00_data *data)
+{
+	struct device *dev = regmap_get_device(data->regmap);
+	int ret;
+
+	ret = pm_runtime_resume_and_get(dev);
+	if (ret)
+		return ret;
+
+	ret = veml6031x00_set_interrupt(data, true);
+	if (ret) {
+		pm_runtime_put_autosuspend(dev);
+		return ret;
+	}
+
+	data->ev_en = true;
+
+	return 0;
+}
+
+static int veml6031x00_event_disable(struct veml6031x00_data *data)
+{
+	struct device *dev = regmap_get_device(data->regmap);
+	int ret;
+
+	ret = veml6031x00_set_interrupt(data, false);
+	if (ret)
+		return ret;
+
+	data->ev_en = false;
+	pm_runtime_put_autosuspend(dev);
+
+	return 0;
+}
+
+static int veml6031x00_write_event_config(struct iio_dev *iio,
+					  const struct iio_chan_spec *chan,
+					  enum iio_event_type type,
+					  enum iio_event_direction dir,
+					  bool state)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+
+	guard(mutex)(&data->irq_lock);
+
+	/* avoid multiple increments/decrements from one source */
+	if (state == data->ev_en)
+		return 0;
+
+	if (state)
+		return veml6031x00_event_enable(data);
+
+	return veml6031x00_event_disable(data);
+}
+
+static void veml6031x00_disable_event_action(void *arg)
+{
+	struct veml6031x00_data *data = arg;
+	struct device *dev = regmap_get_device(data->regmap);
+	int ret;
+
+	guard(mutex)(&data->irq_lock);
+
+	if (!data->ev_en)
+		return;
+
+	ret = veml6031x00_set_interrupt(data, false);
+	if (ret)
+		dev_err(dev, "Failed to disable events: %d\n", ret);
+	else
+		data->ev_en = false;
+
+	pm_runtime_put_sync(dev);
+}
+
 static const struct iio_info veml6031x00_info = {
 	.read_raw = veml6031x00_read_raw,
 	.read_avail = veml6031x00_read_avail,
 	.write_raw = veml6031x00_write_raw,
 	.write_raw_get_fmt = veml6031x00_write_raw_get_fmt,
+	.read_event_value = veml6031x00_read_event_val,
+	.write_event_value = veml6031x00_write_event_val,
+	.read_event_config = veml6031x00_read_event_config,
+	.write_event_config = veml6031x00_write_event_config,
+	.event_attrs = &veml6031x00_event_attr_group,
 };
 
+static const struct iio_info veml6031x00_info_no_irq = {
+	.read_raw = veml6031x00_read_raw,
+	.read_avail = veml6031x00_read_avail,
+	.write_raw = veml6031x00_write_raw,
+	.write_raw_get_fmt = veml6031x00_write_raw_get_fmt,
+};
+
+static irqreturn_t veml6031x00_irq(int irq, void *private)
+{
+	struct iio_dev *iio = private;
+	struct veml6031x00_data *data = iio_priv(iio);
+	struct device *dev = regmap_get_device(data->regmap);
+	s64 timestamp;
+	unsigned int regval;
+	int ret;
+	bool trigger_poll;
+
+	ret = pm_runtime_get_if_active(dev);
+	if (ret <= 0)
+		return IRQ_NONE;
+
+	scoped_guard(mutex, &data->irq_lock) {
+		ret = regmap_read(data->regmap, VEML6031X00_REG_INT, &regval);
+		if (ret) {
+			dev_dbg(dev, "Failed to read interrupt register %d\n", ret);
+			pm_runtime_put(dev);
+			return IRQ_NONE;
+		}
+
+		if (!(regval & VEML6031X00_INT_MASK)) {
+			pm_runtime_put(dev);
+			return IRQ_NONE;
+		}
+
+		timestamp = iio_get_time_ns(iio);
+
+		if (data->ev_en &&
+		    (regval & (VEML6031X00_INT_TH_H | VEML6031X00_INT_TH_L))) {
+			if (regval & VEML6031X00_INT_TH_H)
+				iio_push_event(iio,
+					       IIO_UNMOD_EVENT_CODE(IIO_LIGHT, 0,
+								    IIO_EV_TYPE_THRESH,
+								    IIO_EV_DIR_RISING),
+					       timestamp);
+			if (regval & VEML6031X00_INT_TH_L)
+				iio_push_event(iio,
+					       IIO_UNMOD_EVENT_CODE(IIO_LIGHT, 0,
+								    IIO_EV_TYPE_THRESH,
+								    IIO_EV_DIR_FALLING),
+					       timestamp);
+		}
+
+		trigger_poll = data->trig_en && (regval & VEML6031X00_INT_DRDY);
+	}
+
+	/*
+	 * iio_trigger_poll_nested() must be called with irq_lock released:
+	 * it runs trig_handler() synchronously in this thread, which calls
+	 * reenable() on completion, and that callback also takes irq_lock.
+	 * iio_pollfunc_store_time() is not called for our own trigger, so the
+	 * timestamp is stored here.
+	 */
+	if (trigger_poll) {
+		iio->pollfunc->timestamp = timestamp;
+		iio_trigger_poll_nested(data->trig);
+	}
+
+	pm_runtime_put(dev);
+
+	return IRQ_HANDLED;
+}
+
 static int veml6031x00_buffer_preenable(struct iio_dev *iio)
 {
 	struct veml6031x00_data *data = iio_priv(iio);
@@ -551,11 +973,83 @@ static int veml6031x00_buffer_postdisable(struct iio_dev *iio)
 	return 0;
 }
 
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{
+	int ret;
+
+	lockdep_assert_held(&data->irq_lock);
+
+	ret = veml6031x00_set_interrupt(data, state);
+	if (ret)
+		return ret;
+
+	/* The AF bit must be updated before updating AF_TRIG */
+	ret = regmap_assign_bits(data->regmap, VEML6031X00_REG_CONF0,
+				 VEML6031X00_CONF0_AF, state);
+	if (ret)
+		goto clear_interrupt;
+
+	ret = regmap_assign_bits(data->regmap, VEML6031X00_REG_CONF0,
+				 VEML6031X00_CONF0_AF_TRIG, state);
+	if (ret) {
+		regmap_assign_bits(data->regmap, VEML6031X00_REG_CONF0,
+				   VEML6031X00_CONF0_AF, !state);
+		goto clear_interrupt;
+	}
+
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}
+
+static int veml6031x00_set_trigger_state(struct iio_trigger *trig, bool state)
+{
+	struct iio_dev *iio = iio_trigger_get_drvdata(trig);
+	struct veml6031x00_data *data = iio_priv(iio);
+
+	guard(mutex)(&data->irq_lock);
+
+	if (state == data->trig_en)
+		return 0;
+
+	return __veml6031x00_set_trigger_state(data, state);
+}
+
 static const struct iio_buffer_setup_ops veml6031x00_buffer_setup_ops = {
 	.preenable = veml6031x00_buffer_preenable,
 	.postdisable = veml6031x00_buffer_postdisable,
 };
 
+static void veml6031x00_trigger_reenable(struct iio_trigger *trig)
+{
+	struct iio_dev *iio = iio_trigger_get_drvdata(trig);
+	struct veml6031x00_data *data = iio_priv(iio);
+	int ret;
+
+	guard(mutex)(&data->irq_lock);
+
+	if (!data->trig_en)
+		return;
+
+	ret = regmap_assign_bits(data->regmap, VEML6031X00_REG_CONF0,
+				 VEML6031X00_CONF0_AF_TRIG, true);
+	if (ret)
+		dev_err(regmap_get_device(data->regmap),
+			"Failed to reenable trigger: %d\n", ret);
+}
+
+static const struct iio_trigger_ops veml6031x00_trigger_ops = {
+	.validate_device = iio_trigger_validate_own_device,
+	.set_trigger_state = veml6031x00_set_trigger_state,
+	.reenable = veml6031x00_trigger_reenable,
+};
+
 static irqreturn_t veml6031x00_trig_handler(int irq, void *p)
 {
 	struct iio_poll_func *pf = p;
@@ -609,6 +1103,85 @@ static int veml6031x00_validate_part_id(struct veml6031x00_data *data)
 	return 0;
 }
 
+static int veml6031x00_hw_init(struct veml6031x00_data *data)
+{
+	struct regmap *map = data->regmap;
+	struct device *dev = regmap_get_device(map);
+	unsigned int val;
+	__le16 regval;
+	int ret;
+
+	regval = 0;
+	ret = regmap_bulk_write(map, VEML6031X00_REG_WL_L, &regval, sizeof(regval));
+	if (ret)
+		return dev_err_probe(dev, ret, "Failed to set low threshold\n");
+
+	regval = cpu_to_le16(U16_MAX);
+	ret = regmap_bulk_write(map, VEML6031X00_REG_WH_L, &regval, sizeof(regval));
+	if (ret)
+		return dev_err_probe(dev, ret, "Failed to set high threshold\n");
+
+	ret = regmap_field_write(data->rf.int_en, 0);
+	if (ret)
+		return ret;
+
+	ret = regmap_read(map, VEML6031X00_REG_INT, &val);
+	if (ret)
+		return dev_err_probe(dev, ret, "Failed to clear interrupts\n");
+
+	return 0;
+}
+
+static int veml6031x00_setup_irq(struct i2c_client *i2c, struct iio_dev *iio)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+	struct device *dev = regmap_get_device(data->regmap);
+	int ret;
+
+	data->trig = devm_iio_trigger_alloc(dev, "%s-drdy%d",
+					    iio->name, iio_device_id(iio));
+	if (!data->trig)
+		return -ENOMEM;
+
+	data->trig->ops = &veml6031x00_trigger_ops;
+	iio_trigger_set_drvdata(data->trig, iio);
+
+	ret = devm_iio_trigger_register(dev, data->trig);
+	if (ret)
+		return ret;
+
+	return devm_request_threaded_irq(dev, i2c->irq, NULL, veml6031x00_irq,
+					 IRQF_ONESHOT, iio->name, iio);
+}
+
+static int veml6031x00_init_iiodev(struct i2c_client *i2c, struct iio_dev *iio)
+{
+	struct veml6031x00_data *data = iio_priv(iio);
+	struct device *dev = regmap_get_device(data->regmap);
+	int ret;
+
+	iio->name = data->chip->name;
+	iio->modes = INDIO_DIRECT_MODE;
+
+	if (!i2c->irq) {
+		iio->channels = veml6031x00_channels;
+		iio->num_channels = ARRAY_SIZE(veml6031x00_channels);
+		iio->info = &veml6031x00_info_no_irq;
+
+		return 0;
+	}
+
+	iio->channels = veml6031x00_channels_irq;
+	iio->num_channels = ARRAY_SIZE(veml6031x00_channels_irq);
+	iio->info = &veml6031x00_info;
+
+	ret = veml6031x00_setup_irq(i2c, iio);
+	if (ret)
+		return ret;
+
+	return devm_add_action_or_reset(dev, veml6031x00_disable_event_action, data);
+}
+
 static int veml6031x00_probe(struct i2c_client *i2c)
 {
 	struct device *dev = &i2c->dev;
@@ -631,17 +1204,15 @@ static int veml6031x00_probe(struct i2c_client *i2c)
 	if (ret)
 		return ret;
 
+	ret = devm_mutex_init(dev, &data->irq_lock);
+	if (ret)
+		return ret;
+
 	data->regmap = devm_regmap_init_i2c(i2c, &veml6031x00_regmap_config);
 	if (IS_ERR(data->regmap))
 		return dev_err_probe(dev, PTR_ERR(data->regmap),
 				     "Failed to set regmap\n");
 
-	iio->name = data->chip->name;
-	iio->channels = veml6031x00_channels;
-	iio->num_channels = ARRAY_SIZE(veml6031x00_channels);
-	iio->modes = INDIO_DIRECT_MODE;
-	iio->info = &veml6031x00_info;
-
 	ret = veml6031x00_regfield_init(data);
 	if (ret)
 		return dev_err_probe(dev, ret, "Failed to init regfield\n");
@@ -669,6 +1240,10 @@ static int veml6031x00_probe(struct i2c_client *i2c)
 	if (ret)
 		return ret;
 
+	ret = veml6031x00_hw_init(data);
+	if (ret)
+		return ret;
+
 	/* Max resolution = 6.9632 lx/cnt for gain = 0.125 and IT = 3.125ms */
 	ret = devm_iio_init_iio_gts(dev, 6, 963200000,
 				    veml6031x00_gain_sel,
@@ -679,6 +1254,10 @@ static int veml6031x00_probe(struct i2c_client *i2c)
 	if (ret)
 		return dev_err_probe(dev, ret, "Failed to init IIO GTS\n");
 
+	ret = veml6031x00_init_iiodev(i2c, iio);
+	if (ret)
+		return dev_err_probe(dev, ret, "Failed to initialize IIO device\n");
+
 	ret = devm_iio_triggered_buffer_setup(dev, iio,
 					      iio_pollfunc_store_time,
 					      veml6031x00_trig_handler,
Signature · 1 line
2.43.0
#6 lore raw

Re: [PATCH v8 4/4] iio: light: veml6031x00: add support for events and trigger

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure. - [Medium]…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure.
- [Medium] Unintended I2C read of configuration register when pushing timestamp to buffer
- [Medium] The interrupt_users counter can permanently underflow during error recovery, breaking hardware interrupt control. --

commit c87f3d48e1ee614fc184995b816c8f8679a6b774
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for events and trigger

The device provides a shared interrupt line to notify events and data ready. Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index 3d5a27a0baaed..7bd7975eb1a76 100644

[ ... ]

Quoted 2 lines
drivers/iio/light/veml6031x00.c +2 -0
+static irqreturn_t veml6031x00_irq(int irq, void *private)
+{

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_write_raw_get_fmt(struct iio_dev *indio_dev, · line 939

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	if (trigger_poll) {
+		iio->pollfunc->timestamp = timestamp;
+		iio_trigger_poll_nested(data->trig);
+	}
+
+	pm_runtime_put(dev);
+
+	return IRQ_HANDLED;
+}

[Severity: High]
Could this lead to a use-after-free of the pollfunc during device unbind or if probe fails?

Because the IRQ is requested via devres inside veml6031x00_init_iiodev() before the triggered buffer is set up in veml6031x00_probe(), devres will tear down the buffer (and free iio->pollfunc) before freeing the IRQ. If an interrupt fires during this teardown window, the IRQ thread could be preempted and then dereference the freed iio->pollfunc here.

Would it be safer to ensure devm_iio_triggered_buffer_setup() is called before the IRQ is requested?

[ ... ]

Quoted 3 lines
drivers/iio/light/veml6031x00.c +3 -0
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_buffer_postdisable(struct iio_dev *iio) · line 1009

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}

[Severity: Medium]
Can data->interrupt_users permanently underflow here during error recovery?

If an I2C error occurs in __veml6031x00_set_trigger_state() while disabling the trigger, this error recovery path calls veml6031x00_set_interrupt() to revert the counter, but fails to update the software state (data->trig_en).

If a subsequent successful disable happens later, the counter will be decremented again, potentially underflowing to UINT_MAX and silently skipping all future hardware writes.

[ ... ]

Quoted 15 lines
drivers/iio/light/veml6031x00.c +15 -0
+static irqreturn_t veml6031x00_trig_handler(int irq, void *p)
+{
+	struct iio_poll_func *pf = p;
+	struct iio_dev *iio = pf->indio_dev;
+	struct veml6031x00_data *data = iio_priv(iio);
+	struct regmap *map = data->regmap;
+	IIO_DECLARE_BUFFER_WITH_TS(__le16, scan, 2) = { };
+	unsigned int i;
+	int ch, ret;
+
+	if (test_bit(VEML6031X00_SCAN_ALS, iio->active_scan_mask) &&
+	    test_bit(VEML6031X00_SCAN_IR, iio->active_scan_mask)) {
+		ret = regmap_bulk_read(map, VEML6031X00_REG_ALS_L,
+				       scan, 2 * sizeof(*scan));
+		if (ret)

drivers/iio/light/veml6031x00.c

Quoted 10 lines
drivers/iio/light/veml6031x00.c +10 -0
+			goto done;
+	} else {
+		i = 0;
+		iio_for_each_active_channel(iio, ch) {
+			ret = regmap_bulk_read(map, iio->channels[ch].address,
+					       &scan[i++], sizeof(*scan));
+			if (ret)
+				goto done;
+		}
+	}

[Severity: Medium]
Does this loop unintentionally perform an I2C read of the configuration register when pushing the timestamp to the buffer?

The iio_for_each_active_channel() iteration includes the IIO_TIMESTAMP channel. Since its address is 0, this causes an unintended I2C read of the configuration register (0x00) on every trigger event when the IR channel is disabled.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#7 lore raw

Re: [PATCH v8 4/4] iio: light: veml6031x00: add support for events and trigger

Quoted 37 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure.
- [Medium] Unintended I2C read of configuration register when pushing timestamp to buffer
- [Medium] The interrupt_users counter can permanently underflow during error recovery, breaking hardware interrupt control. --

commit c87f3d48e1ee614fc184995b816c8f8679a6b774
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for events and trigger

The device provides a shared interrupt line to notify events and data ready. Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index 3d5a27a0baaed..7bd7975eb1a76 100644

[ ... ]

Quoted 2 lines
drivers/iio/light/veml6031x00.c +2 -0
+static irqreturn_t veml6031x00_irq(int irq, void *private)
+{

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_write_raw_get_fmt(struct iio_dev *indio_dev, · line 939

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	if (trigger_poll) {
+		iio->pollfunc->timestamp = timestamp;
+		iio_trigger_poll_nested(data->trig);
+	}
+
+	pm_runtime_put(dev);
+
+	return IRQ_HANDLED;
+}

[Severity: High]
Could this lead to a use-after-free of the pollfunc during device unbind or if probe fails?

Quoted 9 lines

Because the IRQ is requested via devres inside veml6031x00_init_iiodev() before the triggered buffer is set up in veml6031x00_probe(), devres will tear down the buffer (and free iio->pollfunc) before freeing the IRQ. If an interrupt fires during this teardown window, the IRQ thread could be preempted and then dereference the freed iio->pollfunc here.

Would it be safer to ensure devm_iio_triggered_buffer_setup() is called before the IRQ is requested?

I will register the IRQ right after calling devm_iio_triggered_buffer_setup(), removing it from veml6031x00_init_iiodev(). It was there not to check i2c->irq twice, because that is also necessary to properly initialize the IIO device with the right data, but it is true that the tear down is not clean at the moment.

Quoted 22 lines

[ ... ]

Quoted 3 lines
drivers/iio/light/veml6031x00.c +3 -0
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_buffer_postdisable(struct iio_dev *iio) · line 1009

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}

[Severity: Medium]
Can data->interrupt_users permanently underflow here during error recovery?

If an I2C error occurs in __veml6031x00_set_trigger_state() while disabling the trigger, this error recovery path calls veml6031x00_set_interrupt() to revert the counter, but fails to update the software state (data->trig_en).

Quoted 5 lines

If a subsequent successful disable happens later, the counter will be decremented again, potentially underflowing to UINT_MAX and silently skipping all future hardware writes.

[ ... ]

That is not true because the error path will *increment* the counter to re-enable the IRQ and keept it consistent with data->trig_en. If an I2C operation fails, the trigger will stay enabled in the device registers, and therefore data-trig_en should stay enabled.

I tested it by adding some hacks to force that situation, and what may actually happen is that if *on top* of that failure, the I2C operation in veml6031x00_set_interrupt() also fails, interrupt_users will be decremented (as it should, because the interrupt could not be re-enabled), and *then* a second call to disable the trigger will set interrupt_users to UINT_MAX.

Although this is very unlikely, the fix seems to be trivial:

if (state) {
data->interrupt_users++;
if (data->interrupt_users > 1)
return 0;
} else {
+ if (!data->interrupt_users)
+ return 0;

data->interrupt_users--;
if (data->interrupt_users > 0)
return 0;
}

Note that this fix is not a hack to just get rid of reaching UINT_MAX, it reflects the fact that the previous failed operations lead to a disabled interrupt and an enabled trigger in the hardware, and there is no need to act on the interrupt again when trying to disable the trigger a second time.

I will add it for V9 after testing it with some hacks to force that scenario.

Best regards,
Javier

author maintainer
#8 lore raw

Re: [PATCH v8 4/4] iio: light: veml6031x00: add support for events and trigger

Quoted 75 lines · Javier Carrasco
Quoted 41 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure.
- [Medium] Unintended I2C read of configuration register when pushing timestamp to buffer
- [Medium] The interrupt_users counter can permanently underflow during error recovery, breaking hardware interrupt control. --

commit c87f3d48e1ee614fc184995b816c8f8679a6b774
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for events and trigger

The device provides a shared interrupt line to notify events and data ready. Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index 3d5a27a0baaed..7bd7975eb1a76 100644

[ ... ]

Quoted 3 lines
drivers/iio/light/veml6031x00.c +3 -0
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_buffer_postdisable(struct iio_dev *iio) · line 1009

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}

[Severity: Medium]
Can data->interrupt_users permanently underflow here during error recovery?

If an I2C error occurs in __veml6031x00_set_trigger_state() while disabling the trigger, this error recovery path calls veml6031x00_set_interrupt() to revert the counter, but fails to update the software state (data->trig_en).

Quoted 5 lines

If a subsequent successful disable happens later, the counter will be decremented again, potentially underflowing to UINT_MAX and silently skipping all future hardware writes.

[ ... ]

That is not true because the error path will *increment* the counter to re-enable the IRQ and keept it consistent with data->trig_en. If an I2C operation fails, the trigger will stay enabled in the device registers, and therefore data-trig_en should stay enabled.

I tested it by adding some hacks to force that situation, and what may actually happen is that if *on top* of that failure, the I2C operation in veml6031x00_set_interrupt() also fails, interrupt_users will be decremented (as it should, because the interrupt could not be re-enabled), and *then* a second call to disable the trigger will set interrupt_users to UINT_MAX.

Although this is very unlikely, the fix seems to be trivial:

if (state) {

(quoted diff) +0 -0
 	data->interrupt_users++;
 	if (data->interrupt_users > 1)
 		return 0;
 } else {
 	+	if (!data->interrupt_users)
 	+		return 0;
 
 	data->interrupt_users--;
 	if (data->interrupt_users > 0)
 		return 0;
 }
Quoted 9 lines

Note that this fix is not a hack to just get rid of reaching UINT_MAX, it reflects the fact that the previous failed operations lead to a disabled interrupt and an enabled trigger in the hardware, and there is no need to act on the interrupt again when trying to disable the trigger a second time.

I will add it for V9 after testing it with some hacks to force that scenario.

I am trying to reproduce that scenario with forced errors, and even if those two errors happen during the first attempt to disable the trigger, it's not really possible to reach interrupt_users = UINT_MAX. The 'buffer/enable' attribute is set to 0 by the core even if set_trigger_state() returns an error code, and the next time 'buffer/enable' is set to 0, nothing really happens because set_trigger_state() is not even called.

I could still add the check I suggested in V9 and avoid future issues, but I don't see how to reproduce this in the current state of the core and driver, even forcing those failed I2C operations.

Best regards,
Javier

maintainer
#9 lore raw

Re: [PATCH v8 4/4] iio: light: veml6031x00: add support for events and trigger

Quoted 86 lines · On Wed, 02 Sep 2026 16:58:09 +0200 "Javier Carrasco"…
Quoted 75 lines · Javier Carrasco
Quoted 41 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure.
- [Medium] Unintended I2C read of configuration register when pushing timestamp to buffer
- [Medium] The interrupt_users counter can permanently underflow during error recovery, breaking hardware interrupt control. --

commit c87f3d48e1ee614fc184995b816c8f8679a6b774
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for events and trigger

The device provides a shared interrupt line to notify events and data ready. Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index 3d5a27a0baaed..7bd7975eb1a76 100644

[ ... ]

Quoted 3 lines
drivers/iio/light/veml6031x00.c +3 -0
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{  

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_buffer_postdisable(struct iio_dev *iio) · line 1009

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}  

[Severity: Medium]
Can data->interrupt_users permanently underflow here during error recovery?

If an I2C error occurs in __veml6031x00_set_trigger_state() while disabling the trigger, this error recovery path calls veml6031x00_set_interrupt() to revert the counter, but fails to update the software state (data->trig_en).

Quoted 5 lines

If a subsequent successful disable happens later, the counter will be decremented again, potentially underflowing to UINT_MAX and silently skipping all future hardware writes.

[ ... ]

That is not true because the error path will *increment* the counter to re-enable the IRQ and keept it consistent with data->trig_en. If an I2C operation fails, the trigger will stay enabled in the device registers, and therefore data-trig_en should stay enabled.

I tested it by adding some hacks to force that situation, and what may actually happen is that if *on top* of that failure, the I2C operation in veml6031x00_set_interrupt() also fails, interrupt_users will be decremented (as it should, because the interrupt could not be re-enabled), and *then* a second call to disable the trigger will set interrupt_users to UINT_MAX.

Although this is very unlikely, the fix seems to be trivial:

if (state) {

(quoted diff) +0 -0
 	data->interrupt_users++;
 	if (data->interrupt_users > 1)
 		return 0;
 } else {
 	+	if (!data->interrupt_users)
 	+		return 0;
 
 	data->interrupt_users--;
 	if (data->interrupt_users > 0)
 		return 0;
 }
Quoted 9 lines

Note that this fix is not a hack to just get rid of reaching UINT_MAX, it reflects the fact that the previous failed operations lead to a disabled interrupt and an enabled trigger in the hardware, and there is no need to act on the interrupt again when trying to disable the trigger a second time.

I will add it for V9 after testing it with some hacks to force that scenario.

Quoted 7 lines

I am trying to reproduce that scenario with forced errors, and even if those two errors happen during the first attempt to disable the trigger, it's not really possible to reach interrupt_users = UINT_MAX. The 'buffer/enable' attribute is set to 0 by the core even if set_trigger_state() returns an error code, and the next time 'buffer/enable' is set to 0, nothing really happens because set_trigger_state() is not even called.

I can't remember why we do that. Oh well. Seems it is useful here.

Quoted 4 lines

I could still add the check I suggested in V9 and avoid future issues, but I don't see how to reproduce this in the current state of the core and driver, even forcing those failed I2C operations.

I agree this is worth doing even if we can't trigger it today.

Jonathan

Quoted 3 lines

Best regards,
Javier

author maintainer
#10 lore raw

Re: [PATCH v8 4/4] iio: light: veml6031x00: add support for events and trigger

Quoted 97 lines · Jonathan Cameron
Quoted 86 lines · On Wed, 02 Sep 2026 16:58:09 +0200 "Javier Carrasco"…
Quoted 75 lines · Javier Carrasco
Quoted 41 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure.
- [Medium] Unintended I2C read of configuration register when pushing timestamp to buffer
- [Medium] The interrupt_users counter can permanently underflow during error recovery, breaking hardware interrupt control. --

commit c87f3d48e1ee614fc184995b816c8f8679a6b774
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for events and trigger

The device provides a shared interrupt line to notify events and data ready. Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index 3d5a27a0baaed..7bd7975eb1a76 100644

[ ... ]

Quoted 3 lines
drivers/iio/light/veml6031x00.c +3 -0
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_buffer_postdisable(struct iio_dev *iio) · line 1009

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}

[Severity: Medium]
Can data->interrupt_users permanently underflow here during error recovery?

If an I2C error occurs in __veml6031x00_set_trigger_state() while disabling the trigger, this error recovery path calls veml6031x00_set_interrupt() to revert the counter, but fails to update the software state (data->trig_en).

Quoted 5 lines

If a subsequent successful disable happens later, the counter will be decremented again, potentially underflowing to UINT_MAX and silently skipping all future hardware writes.

[ ... ]

That is not true because the error path will *increment* the counter to re-enable the IRQ and keept it consistent with data->trig_en. If an I2C operation fails, the trigger will stay enabled in the device registers, and therefore data-trig_en should stay enabled.

I tested it by adding some hacks to force that situation, and what may actually happen is that if *on top* of that failure, the I2C operation in veml6031x00_set_interrupt() also fails, interrupt_users will be decremented (as it should, because the interrupt could not be re-enabled), and *then* a second call to disable the trigger will set interrupt_users to UINT_MAX.

Although this is very unlikely, the fix seems to be trivial:

if (state) {

(quoted diff) +0 -0
 	data->interrupt_users++;
 	if (data->interrupt_users > 1)
 		return 0;
 } else {
 	+	if (!data->interrupt_users)
 	+		return 0;
 
 	data->interrupt_users--;
 	if (data->interrupt_users > 0)
 		return 0;
 }
Quoted 9 lines

Note that this fix is not a hack to just get rid of reaching UINT_MAX, it reflects the fact that the previous failed operations lead to a disabled interrupt and an enabled trigger in the hardware, and there is no need to act on the interrupt again when trying to disable the trigger a second time.

I will add it for V9 after testing it with some hacks to force that scenario.

Quoted 7 lines

I am trying to reproduce that scenario with forced errors, and even if those two errors happen during the first attempt to disable the trigger, it's not really possible to reach interrupt_users = UINT_MAX. The 'buffer/enable' attribute is set to 0 by the core even if set_trigger_state() returns an error code, and the next time 'buffer/enable' is set to 0, nothing really happens because set_trigger_state() is not even called.

Quoted 2 lines

I can't remember why we do that. Oh well. Seems it is useful here.

I instrumented some more code, including iio_trigger_attach/detach_poll_func() and current_trigger_store(). When set_trigger_state(false) fails (which I forced), iio_trigger_detach_poll_func() returns without releasing the pollfunc IRQ from the trigger pool, but iio_disable_buffers() continues disabling the buffer.

The next buffer enable adds another consumer to the pool without calling set_trigger_state(true), since the trigger is already in use. The following buffer disable removes that new consumer without calling set_trigger_state(false), since there is still one consumer left in the pool.

So after the first failed disable, subsequent buffer enable/disable cycles do not call set_trigger_state() and the original consumer remains in the pool. That leaves the buffer/enable attribute in a meaningless state: it gets updated from the userspace perspective, but nothing really happens behind the scenes.

Is that intended? Maybe there are historical reasons for it, or maybe there was no cleaner way to operate after an error in set_trigger_state(), or maybe this should not work like that.

This is what it looks like after I instrumented the code:

# All good, the trigger was disabled, and now it gets enabled:
echo 1 > buffer/enable

[   50.590395] IIO trigger veml6031x00-drdy0: attach: before: pool users=0
[   50.596562] IIO trigger veml6031x00-drdy0: attach: pf->irq=188
[   50.602537] IIO trigger veml6031x00-drdy0: attach: after get_irq: pool users=1
[   50.622654] IIO trigger veml6031x00-drdy0: attach: set_trigger_state(1) returned 0

# Forced failure in veml6031x00_set_trigger_state(false):
echo 0 > buffer/enable

[   64.608971] IIO trigger veml6031x00-drdy0: detach: before: pool users=1
[   64.615267] IIO trigger veml6031x00-drdy0: detach: pf->irq=188
[   64.657138] IIO trigger veml6031x00-drdy0: detach: set_trigger_state(0) returned -13
[   64.664968] IIO trigger veml6031x00-drdy0: detach: callback failed: pool users=1

# From now on, set_trigger_state() will not be called:
echo 1 > buffer/enable

[  104.047282] IIO trigger veml6031x00-drdy0: attach: before: pool users=1
[  104.053494] IIO trigger veml6031x00-drdy0: attach: pf->irq=189
[  104.059502] IIO trigger veml6031x00-drdy0: attach: after get_irq: pool users=2
[  104.067023] IIO trigger veml6031x00-drdy0: attach: NOT calling set_trigger_state(1), notinuse=0

echo 0 > buffer/enable

[  117.354867] IIO trigger veml6031x00-drdy0: detach: before: pool users=2
[  117.361070] IIO trigger veml6031x00-drdy0: detach: pf->irq=189
[  117.366975] IIO trigger veml6031x00-drdy0: detach: NOT calling set_trigger_state(0), no_other_users=0
[  117.376297] IIO trigger veml6031x00-drdy0: detach: after put_irq: pool users=1

Best regards,
Javier

maintainer
#11 lore raw

Re: [PATCH v8 4/4] iio: light: veml6031x00: add support for events and trigger

Quoted 107 lines · On Mon, 07 Sep 2026 19:11:34 +0200 "Javier Carrasco"…
Quoted 97 lines · Jonathan Cameron
Quoted 86 lines · On Wed, 02 Sep 2026 16:58:09 +0200 "Javier Carrasco"…
Quoted 75 lines · Javier Carrasco
Quoted 41 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure.
- [Medium] Unintended I2C read of configuration register when pushing timestamp to buffer
- [Medium] The interrupt_users counter can permanently underflow during error recovery, breaking hardware interrupt control. --

commit c87f3d48e1ee614fc184995b816c8f8679a6b774
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for events and trigger

The device provides a shared interrupt line to notify events and data ready. Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index 3d5a27a0baaed..7bd7975eb1a76 100644

[ ... ]

Quoted 3 lines
drivers/iio/light/veml6031x00.c +3 -0
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{  

[ ... ]

drivers/iio/light/veml6031x00.c static int veml6031x00_buffer_postdisable(struct iio_dev *iio) · line 1009

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}  

[Severity: Medium]
Can data->interrupt_users permanently underflow here during error recovery?

If an I2C error occurs in __veml6031x00_set_trigger_state() while disabling the trigger, this error recovery path calls veml6031x00_set_interrupt() to revert the counter, but fails to update the software state (data->trig_en).

Quoted 5 lines

If a subsequent successful disable happens later, the counter will be decremented again, potentially underflowing to UINT_MAX and silently skipping all future hardware writes.

[ ... ]

That is not true because the error path will *increment* the counter to re-enable the IRQ and keept it consistent with data->trig_en. If an I2C operation fails, the trigger will stay enabled in the device registers, and therefore data-trig_en should stay enabled.

I tested it by adding some hacks to force that situation, and what may actually happen is that if *on top* of that failure, the I2C operation in veml6031x00_set_interrupt() also fails, interrupt_users will be decremented (as it should, because the interrupt could not be re-enabled), and *then* a second call to disable the trigger will set interrupt_users to UINT_MAX.

Although this is very unlikely, the fix seems to be trivial:

if (state) {

(quoted diff) +0 -0
 	data->interrupt_users++;
 	if (data->interrupt_users > 1)
 		return 0;
 } else {
 	+	if (!data->interrupt_users)
 	+		return 0;
 
 	data->interrupt_users--;
 	if (data->interrupt_users > 0)
 		return 0;
 }
Quoted 9 lines

Note that this fix is not a hack to just get rid of reaching UINT_MAX, it reflects the fact that the previous failed operations lead to a disabled interrupt and an enabled trigger in the hardware, and there is no need to act on the interrupt again when trying to disable the trigger a second time.

I will add it for V9 after testing it with some hacks to force that scenario.

Quoted 7 lines

I am trying to reproduce that scenario with forced errors, and even if those two errors happen during the first attempt to disable the trigger, it's not really possible to reach interrupt_users = UINT_MAX. The 'buffer/enable' attribute is set to 0 by the core even if set_trigger_state() returns an error code, and the next time 'buffer/enable' is set to 0, nothing really happens because set_trigger_state() is not even called.

Quoted 2 lines

I can't remember why we do that. Oh well. Seems it is useful here.

I instrumented some more code, including iio_trigger_attach/detach_poll_func() and current_trigger_store(). When set_trigger_state(false) fails (which I forced), iio_trigger_detach_poll_func() returns without releasing the pollfunc IRQ from the trigger pool, but iio_disable_buffers() continues disabling the buffer.

Quoted 4 lines

The next buffer enable adds another consumer to the pool without calling set_trigger_state(true), since the trigger is already in use. The following buffer disable removes that new consumer without calling set_trigger_state(false), since there is still one consumer left in the pool.

So do you get two hits on each trigger? Definitely bad as they can be in threads running at the same time and we assume that doesn't happen in most drivers.

Quoted 10 lines

So after the first failed disable, subsequent buffer enable/disable cycles do not call set_trigger_state() and the original consumer remains in the pool. That leaves the buffer/enable attribute in a meaningless state: it gets updated from the userspace perspective, but nothing really happens behind the scenes.

Is that intended? Maybe there are historical reasons for it, or maybe there was no cleaner way to operate after an error in set_trigger_state(), or maybe this should not work like that.

I'd go with "probably not the intended result" as if it were I 'think' I'd have left a comment.

That's not to say I have an immediate answer to how to resolve it. If you still have your test set up, can you try just carrying on and not returning after the set_trigger_state(trig, false) fails - making sure that your injected failure leaves the trigger actually enabled and still firing. That might leave us in a recoverable state as next set_triggers_state(trig, true) should work as normal. In meantime we will have a bunch of irqs firing but resulting in nothing happening.

Not great and may well leave some drivers stuck because they are tightly couple trigger / data readback and need that to happen to not get wedged. Those should have the validate callbacks set but will still be stuck. In theory we could make all triggers that have this property do a clear in the reenable but that is a bit nasty as we would probably want it conditional so each driver would need a 'have I already cleared this' flag set in their buffer read and cleared in the reenable.

Thanks for digging into this btw!

Jonathan

Quoted 32 lines

This is what it looks like after I instrumented the code:

# All good, the trigger was disabled, and now it gets enabled:
echo 1 > buffer/enable

[   50.590395] IIO trigger veml6031x00-drdy0: attach: before: pool users=0
[   50.596562] IIO trigger veml6031x00-drdy0: attach: pf->irq=188
[   50.602537] IIO trigger veml6031x00-drdy0: attach: after get_irq: pool users=1
[   50.622654] IIO trigger veml6031x00-drdy0: attach: set_trigger_state(1) returned 0

# Forced failure in veml6031x00_set_trigger_state(false):
echo 0 > buffer/enable

[   64.608971] IIO trigger veml6031x00-drdy0: detach: before: pool users=1
[   64.615267] IIO trigger veml6031x00-drdy0: detach: pf->irq=188
[   64.657138] IIO trigger veml6031x00-drdy0: detach: set_trigger_state(0) returned -13
[   64.664968] IIO trigger veml6031x00-drdy0: detach: callback failed: pool users=1

# From now on, set_trigger_state() will not be called:
echo 1 > buffer/enable

[  104.047282] IIO trigger veml6031x00-drdy0: attach: before: pool users=1
[  104.053494] IIO trigger veml6031x00-drdy0: attach: pf->irq=189
[  104.059502] IIO trigger veml6031x00-drdy0: attach: after get_irq: pool users=2
[  104.067023] IIO trigger veml6031x00-drdy0: attach: NOT calling set_trigger_state(1), notinuse=0

echo 0 > buffer/enable

[  117.354867] IIO trigger veml6031x00-drdy0: detach: before: pool users=2
[  117.361070] IIO trigger veml6031x00-drdy0: detach: pf->irq=189
[  117.366975] IIO trigger veml6031x00-drdy0: detach: NOT calling set_trigger_state(0), no_other_users=0
[  117.376297] IIO trigger veml6031x00-drdy0: detach: after put_irq: pool users=1

Best regards,
Javier

author maintainer
#12 lore raw

Re: [PATCH v8 4/4] iio: light: veml6031x00: add support for events and trigger

Quoted 149 lines · Jonathan Cameron
Quoted 107 lines · On Mon, 07 Sep 2026 19:11:34 +0200 "Javier Carrasco"…
Quoted 97 lines · Jonathan Cameron
Quoted 86 lines · On Wed, 02 Sep 2026 16:58:09 +0200 "Javier Carrasco"…
Quoted 75 lines · Javier Carrasco
Quoted 41 lines · sashiko-bot

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] Use-After-Free of iio->pollfunc in IRQ handler during device unbind or probe failure.
- [Medium] Unintended I2C read of configuration register when pushing timestamp to buffer
- [Medium] The interrupt_users counter can permanently underflow during error recovery, breaking hardware interrupt control. --

commit c87f3d48e1ee614fc184995b816c8f8679a6b774
Author: Javier Carrasco <[email protected]>

iio: light: veml6031x00: add support for events and trigger

The device provides a shared interrupt line to notify events and data ready. Add support for configurations with and without an interrupt line, providing events and trigger support when an interrupt line is available.

Quoted 4 lines
drivers/iio/light/veml6031x00.c +0 -0
index 3d5a27a0baaed..7bd7975eb1a76 100644

[ ... ]

Quoted 3 lines
drivers/iio/light/veml6031x00.c +3 -0
+static int __veml6031x00_set_trigger_state(struct veml6031x00_data *data, bool state)
+	__must_hold(&data->irq_lock)
+{

[ ... ]

drivers/iio/light/veml6031x00.c

Quoted 9 lines
drivers/iio/light/veml6031x00.c +9 -0
+	data->trig_en = state;
+
+	return 0;
+
+clear_interrupt:
+	veml6031x00_set_interrupt(data, !state);
+
+	return ret;
+}

[Severity: Medium]
Can data->interrupt_users permanently underflow here during error recovery?

If an I2C error occurs in __veml6031x00_set_trigger_state() while disabling the trigger, this error recovery path calls veml6031x00_set_interrupt() to revert the counter, but fails to update the software state (data->trig_en).

Quoted 5 lines

If a subsequent successful disable happens later, the counter will be decremented again, potentially underflowing to UINT_MAX and silently skipping all future hardware writes.

[ ... ]

That is not true because the error path will *increment* the counter to re-enable the IRQ and keept it consistent with data->trig_en. If an I2C operation fails, the trigger will stay enabled in the device registers, and therefore data-trig_en should stay enabled.

I tested it by adding some hacks to force that situation, and what may actually happen is that if *on top* of that failure, the I2C operation in veml6031x00_set_interrupt() also fails, interrupt_users will be decremented (as it should, because the interrupt could not be re-enabled), and *then* a second call to disable the trigger will set interrupt_users to UINT_MAX.

Although this is very unlikely, the fix seems to be trivial:

if (state) {

(quoted diff) +0 -0
 	data->interrupt_users++;
 	if (data->interrupt_users > 1)
 		return 0;
 } else {
 	+	if (!data->interrupt_users)
 	+		return 0;
 
 	data->interrupt_users--;
 	if (data->interrupt_users > 0)
 		return 0;
 }
Quoted 9 lines

Note that this fix is not a hack to just get rid of reaching UINT_MAX, it reflects the fact that the previous failed operations lead to a disabled interrupt and an enabled trigger in the hardware, and there is no need to act on the interrupt again when trying to disable the trigger a second time.

I will add it for V9 after testing it with some hacks to force that scenario.

Quoted 7 lines

I am trying to reproduce that scenario with forced errors, and even if those two errors happen during the first attempt to disable the trigger, it's not really possible to reach interrupt_users = UINT_MAX. The 'buffer/enable' attribute is set to 0 by the core even if set_trigger_state() returns an error code, and the next time 'buffer/enable' is set to 0, nothing really happens because set_trigger_state() is not even called.

Quoted 2 lines

I can't remember why we do that. Oh well. Seems it is useful here.

I instrumented some more code, including iio_trigger_attach/detach_poll_func() and current_trigger_store(). When set_trigger_state(false) fails (which I forced), iio_trigger_detach_poll_func() returns without releasing the pollfunc IRQ from the trigger pool, but iio_disable_buffers() continues disabling the buffer.

Quoted 4 lines

The next buffer enable adds another consumer to the pool without calling set_trigger_state(true), since the trigger is already in use. The following buffer disable removes that new consumer without calling set_trigger_state(false), since there is still one consumer left in the pool.

So do you get two hits on each trigger? Definitely bad as they can be in threads running at the same time and we assume that doesn't happen in most drivers.

Quoted 10 lines

So after the first failed disable, subsequent buffer enable/disable cycles do not call set_trigger_state() and the original consumer remains in the pool. That leaves the buffer/enable attribute in a meaningless state: it gets updated from the userspace perspective, but nothing really happens behind the scenes.

Is that intended? Maybe there are historical reasons for it, or maybe there was no cleaner way to operate after an error in set_trigger_state(), or maybe this should not work like that.

I'd go with "probably not the intended result" as if it were I 'think' I'd have left a comment.

That's not to say I have an immediate answer to how to resolve it. If you still have your test set up, can you try just carrying on and not returning after the set_trigger_state(trig, false) fails - making sure that your injected failure leaves the trigger actually enabled and still firing. That might leave us in a recoverable state as next set_triggers_state(trig, true) should work as normal. In meantime we will have a bunch of irqs firing but resulting in nothing happening.

Not great and may well leave some drivers stuck because they are tightly couple trigger / data readback and need that to happen to not get wedged. Those should have the validate callbacks set but will still be stuck. In theory we could make all triggers that have this property do a clear in the reenable but that is a bit nasty as we would probably want it conditional so each driver would need a 'have I already cleared this' flag set in their buffer read and cleared in the reenable.

Quoted 4 lines

Thanks for digging into this btw!

Jonathan

I still have my test set up, and I will get back to this once I am done with the driver that triggered the issue. It looks like some action should be taken if set_trigger_state() fails, but I need to invest more time on this.

Best regards,
Javier

maintainer
#13 lore raw
In reply to Javier Carrasco
Quoted 3 lines · On Tue, 01 Sep 2026 15:05:45 +0200 Javier Carrasco…

These ambient light sensors with I2C interface provide two light channels (ALS and IR), high/low threshold alarms with configurable persistence, and a data ready signal.

Hi Javier,

I took a quick look through and don't have anything to add. Hopefully that code reordering you are doing is simple and v9 will the one to go in!

Thanks for persisting!

Jonathan