xref: /linux/drivers/iio/light/opt4060.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2024 Axis Communications AB
4  *
5  * Datasheet: https://www.ti.com/lit/gpn/opt4060
6  *
7  * Device driver for the Texas Instruments OPT4060 RGBW Color Sensor.
8  */
9 
10 #include <linux/bitfield.h>
11 #include <linux/i2c.h>
12 #include <linux/iio/iio.h>
13 #include <linux/math64.h>
14 #include <linux/units.h>
15 #include <linux/limits.h>
16 #include <linux/module.h>
17 #include <linux/property.h>
18 #include <linux/regmap.h>
19 #include <linux/mutex.h>
20 #include <linux/regulator/consumer.h>
21 #include <linux/iio/events.h>
22 #include <linux/iio/trigger.h>
23 #include <linux/iio/trigger_consumer.h>
24 #include <linux/iio/triggered_buffer.h>
25 
26 /* OPT4060 register set */
27 #define OPT4060_RED_MSB				0x00
28 #define OPT4060_RED_LSB				0x01
29 #define OPT4060_GREEN_MSB			0x02
30 #define OPT4060_GREEN_LSB			0x03
31 #define OPT4060_BLUE_MSB			0x04
32 #define OPT4060_BLUE_LSB			0x05
33 #define OPT4060_CLEAR_MSB			0x06
34 #define OPT4060_CLEAR_LSB			0x07
35 #define OPT4060_THRESHOLD_LOW			0x08
36 #define OPT4060_THRESHOLD_HIGH			0x09
37 #define OPT4060_CTRL				0x0a
38 #define OPT4060_INT_CTRL			0x0b
39 #define OPT4060_RES_CTRL			0x0c
40 #define OPT4060_DEVICE_ID			0x11
41 
42 /* OPT4060 register mask */
43 #define OPT4060_EXPONENT_MASK			GENMASK(15, 12)
44 #define OPT4060_MSB_MASK			GENMASK(11, 0)
45 #define OPT4060_LSB_MASK			GENMASK(15, 8)
46 #define OPT4060_COUNTER_MASK			GENMASK(7, 4)
47 #define OPT4060_CRC_MASK			GENMASK(3, 0)
48 
49 /* OPT4060 device id mask */
50 #define OPT4060_DEVICE_ID_MASK			GENMASK(11, 0)
51 
52 /* OPT4060 control register masks */
53 #define OPT4060_CTRL_QWAKE_MASK			BIT(15)
54 #define OPT4060_CTRL_RANGE_MASK			GENMASK(13, 10)
55 #define OPT4060_CTRL_CONV_TIME_MASK		GENMASK(9, 6)
56 #define OPT4060_CTRL_OPER_MODE_MASK		GENMASK(5, 4)
57 #define OPT4060_CTRL_LATCH_MASK			BIT(3)
58 #define OPT4060_CTRL_INT_POL_MASK		BIT(2)
59 #define OPT4060_CTRL_FAULT_COUNT_MASK		GENMASK(1, 0)
60 
61 /* OPT4060 interrupt control register masks */
62 #define OPT4060_INT_CTRL_THRESH_SEL		GENMASK(6, 5)
63 #define OPT4060_INT_CTRL_OUTPUT			BIT(4)
64 #define OPT4060_INT_CTRL_INT_CFG		GENMASK(3, 2)
65 #define OPT4060_INT_CTRL_THRESHOLD		0x0
66 #define OPT4060_INT_CTRL_NEXT_CH		0x1
67 #define OPT4060_INT_CTRL_ALL_CH			0x3
68 
69 /* OPT4060 result control register masks */
70 #define OPT4060_RES_CTRL_OVERLOAD		BIT(3)
71 #define OPT4060_RES_CTRL_CONV_READY		BIT(2)
72 #define OPT4060_RES_CTRL_FLAG_H			BIT(1)
73 #define OPT4060_RES_CTRL_FLAG_L			BIT(0)
74 
75 /* OPT4060 constants */
76 #define OPT4060_DEVICE_ID_VAL			0x821
77 
78 /* OPT4060 operating modes */
79 #define OPT4060_CTRL_OPER_MODE_OFF		0x0
80 #define OPT4060_CTRL_OPER_MODE_FORCED		0x1
81 #define OPT4060_CTRL_OPER_MODE_ONE_SHOT		0x2
82 #define OPT4060_CTRL_OPER_MODE_CONTINUOUS	0x3
83 
84 /* OPT4060 conversion control register definitions */
85 #define OPT4060_CTRL_CONVERSION_0_6MS		0x0
86 #define OPT4060_CTRL_CONVERSION_1MS		0x1
87 #define OPT4060_CTRL_CONVERSION_1_8MS		0x2
88 #define OPT4060_CTRL_CONVERSION_3_4MS		0x3
89 #define OPT4060_CTRL_CONVERSION_6_5MS		0x4
90 #define OPT4060_CTRL_CONVERSION_12_7MS		0x5
91 #define OPT4060_CTRL_CONVERSION_25MS		0x6
92 #define OPT4060_CTRL_CONVERSION_50MS		0x7
93 #define OPT4060_CTRL_CONVERSION_100MS		0x8
94 #define OPT4060_CTRL_CONVERSION_200MS		0x9
95 #define OPT4060_CTRL_CONVERSION_400MS		0xa
96 #define OPT4060_CTRL_CONVERSION_800MS		0xb
97 
98 /* OPT4060 fault count control register definitions */
99 #define OPT4060_CTRL_FAULT_COUNT_1		0x0
100 #define OPT4060_CTRL_FAULT_COUNT_2		0x1
101 #define OPT4060_CTRL_FAULT_COUNT_4		0x2
102 #define OPT4060_CTRL_FAULT_COUNT_8		0x3
103 
104 /* OPT4060 scale light level range definitions */
105 #define OPT4060_CTRL_LIGHT_SCALE_AUTO		12
106 
107 /* OPT4060 default values */
108 #define OPT4060_DEFAULT_CONVERSION_TIME OPT4060_CTRL_CONVERSION_50MS
109 
110 /*
111  * enum opt4060_chan_type - OPT4060 channel types
112  * @OPT4060_RED:	Red channel.
113  * @OPT4060_GREEN:	Green channel.
114  * @OPT4060_BLUE:	Blue channel.
115  * @OPT4060_CLEAR:	Clear (white) channel.
116  * @OPT4060_ILLUM:	Calculated illuminance channel.
117  * @OPT4060_NUM_CHANS:	Number of channel types.
118  */
119 enum opt4060_chan_type {
120 	OPT4060_RED,
121 	OPT4060_GREEN,
122 	OPT4060_BLUE,
123 	OPT4060_CLEAR,
124 	OPT4060_ILLUM,
125 	OPT4060_NUM_CHANS
126 };
127 
128 struct opt4060_chip {
129 	struct regmap *regmap;
130 	struct device *dev;
131 	struct iio_trigger *trig;
132 	u8 int_time;
133 	int irq;
134 	/*
135 	 * Mutex for protecting sensor irq settings. Switching between interrupt
136 	 * on each sample and on thresholds needs to be synchronized.
137 	 */
138 	struct mutex irq_setting_lock;
139 	/*
140 	 * Mutex for protecting event enabling.
141 	 */
142 	struct mutex event_enabling_lock;
143 	struct completion completion;
144 	bool thresh_event_lo_active;
145 	bool thresh_event_hi_active;
146 };
147 
148 struct opt4060_channel_factor {
149 	u32 mul;
150 	u32 div;
151 };
152 
153 static const int opt4060_int_time_available[][2] = {
154 	{ 0,    600 },
155 	{ 0,   1000 },
156 	{ 0,   1800 },
157 	{ 0,   3400 },
158 	{ 0,   6500 },
159 	{ 0,  12700 },
160 	{ 0,  25000 },
161 	{ 0,  50000 },
162 	{ 0, 100000 },
163 	{ 0, 200000 },
164 	{ 0, 400000 },
165 	{ 0, 800000 },
166 };
167 
168 /*
169  * Conversion time is integration time + time to set register
170  * this is used as integration time.
171  */
172 static const int opt4060_int_time_reg[][2] = {
173 	{    600,  OPT4060_CTRL_CONVERSION_0_6MS  },
174 	{   1000,  OPT4060_CTRL_CONVERSION_1MS    },
175 	{   1800,  OPT4060_CTRL_CONVERSION_1_8MS  },
176 	{   3400,  OPT4060_CTRL_CONVERSION_3_4MS  },
177 	{   6500,  OPT4060_CTRL_CONVERSION_6_5MS  },
178 	{  12700,  OPT4060_CTRL_CONVERSION_12_7MS },
179 	{  25000,  OPT4060_CTRL_CONVERSION_25MS   },
180 	{  50000,  OPT4060_CTRL_CONVERSION_50MS   },
181 	{ 100000,  OPT4060_CTRL_CONVERSION_100MS  },
182 	{ 200000,  OPT4060_CTRL_CONVERSION_200MS  },
183 	{ 400000,  OPT4060_CTRL_CONVERSION_400MS  },
184 	{ 800000,  OPT4060_CTRL_CONVERSION_800MS  },
185 };
186 
187 static int opt4060_als_time_to_index(const u32 als_integration_time)
188 {
189 	int i;
190 
191 	for (i = 0; i < ARRAY_SIZE(opt4060_int_time_available); i++) {
192 		if (als_integration_time == opt4060_int_time_available[i][1])
193 			return i;
194 	}
195 
196 	return -EINVAL;
197 }
198 
199 static u8 opt4060_calculate_crc(u8 exp, u32 mantissa, u8 count)
200 {
201 	u8 crc;
202 
203 	/*
204 	 * Calculates a 4-bit CRC from a 20-bit mantissa, 4-bit exponent and a 4-bit counter.
205 	 * crc[0] = XOR(mantissa[19:0], exp[3:0], count[3:0])
206 	 * crc[1] = XOR(mantissa[1,3,5,7,9,11,13,15,17,19], exp[1,3], count[1,3])
207 	 * crc[2] = XOR(mantissa[3,7,11,15,19], exp[3], count[3])
208 	 * crc[3] = XOR(mantissa[3,11,19])
209 	 */
210 	crc = (hweight32(mantissa) + hweight32(exp) + hweight32(count)) % 2;
211 	crc |= ((hweight32(mantissa & 0xAAAAA) + hweight32(exp & 0xA)
212 		 + hweight32(count & 0xA)) % 2) << 1;
213 	crc |= ((hweight32(mantissa & 0x88888) + hweight32(exp & 0x8)
214 		 + hweight32(count & 0x8)) % 2) << 2;
215 	crc |= (hweight32(mantissa & 0x80808) % 2) << 3;
216 
217 	return crc;
218 }
219 
220 static int opt4060_set_int_state(struct opt4060_chip *chip, u32 state)
221 {
222 	int ret;
223 	unsigned int regval;
224 
225 	guard(mutex)(&chip->irq_setting_lock);
226 
227 	regval = FIELD_PREP(OPT4060_INT_CTRL_INT_CFG, state);
228 	ret = regmap_update_bits(chip->regmap, OPT4060_INT_CTRL,
229 				 OPT4060_INT_CTRL_INT_CFG, regval);
230 	if (ret)
231 		dev_err(chip->dev, "Failed to set interrupt config\n");
232 	return ret;
233 }
234 
235 static int opt4060_set_sampling_mode(struct opt4060_chip *chip,
236 				     bool continuous)
237 {
238 	unsigned int reg;
239 	int ret;
240 
241 	ret = regmap_read(chip->regmap, OPT4060_CTRL, &reg);
242 	if (ret < 0) {
243 		dev_err(chip->dev, "Failed to read ctrl register\n");
244 		return ret;
245 	}
246 	reg &= ~OPT4060_CTRL_OPER_MODE_MASK;
247 	if (continuous)
248 		reg |= FIELD_PREP(OPT4060_CTRL_OPER_MODE_MASK,
249 				  OPT4060_CTRL_OPER_MODE_CONTINUOUS);
250 	else
251 		reg |= FIELD_PREP(OPT4060_CTRL_OPER_MODE_MASK,
252 				  OPT4060_CTRL_OPER_MODE_ONE_SHOT);
253 
254 	/*
255 	 * Trigger a new conversions by writing to CRTL register. It is not
256 	 * possible to use regmap_update_bits() since that will only write when
257 	 * data is modified.
258 	 */
259 	ret = regmap_write(chip->regmap, OPT4060_CTRL, reg);
260 	if (ret)
261 		dev_err(chip->dev, "Failed to set ctrl register\n");
262 	return ret;
263 }
264 
265 static bool opt4060_event_active(struct opt4060_chip *chip)
266 {
267 	return chip->thresh_event_lo_active || chip->thresh_event_hi_active;
268 }
269 
270 static int opt4060_set_state_common(struct opt4060_chip *chip,
271 				    bool continuous_sampling,
272 				    bool continuous_irq)
273 {
274 	int ret = 0;
275 
276 	/* It is important to setup irq before sampling to avoid missing samples. */
277 	if (continuous_irq)
278 		ret = opt4060_set_int_state(chip, OPT4060_INT_CTRL_ALL_CH);
279 	else
280 		ret = opt4060_set_int_state(chip, OPT4060_INT_CTRL_THRESHOLD);
281 	if (ret) {
282 		dev_err(chip->dev, "Failed to set irq state.\n");
283 		return ret;
284 	}
285 
286 	if (continuous_sampling || opt4060_event_active(chip))
287 		ret = opt4060_set_sampling_mode(chip, true);
288 	else
289 		ret = opt4060_set_sampling_mode(chip, false);
290 	if (ret)
291 		dev_err(chip->dev, "Failed to set sampling state.\n");
292 	return ret;
293 }
294 
295 /*
296  * Function for setting the driver state for sampling and irq. Either direct
297  * mode of buffer mode will be claimed during the transition to prevent races
298  * between sysfs read, buffer or events.
299  */
300 static int opt4060_set_driver_state(struct iio_dev *indio_dev,
301 				    bool continuous_sampling,
302 				    bool continuous_irq)
303 {
304 	struct opt4060_chip *chip = iio_priv(indio_dev);
305 
306 	IIO_DEV_GUARD_CURRENT_MODE(indio_dev);
307 
308 	/*
309 	 * If we manage to claim buffer mode and we are using our own trigger,
310 	 * IRQ and sampling must go to or remain continuous.
311 	 */
312 	if (iio_buffer_enabled(indio_dev) &&
313 	    iio_trigger_validate_own_device(indio_dev->trig, indio_dev))
314 		return opt4060_set_state_common(chip, true, true);
315 
316 	/*
317 	 * This path means that we managed to claim direct mode. In this case
318 	 * the buffer isn't enabled and it's okay to leave continuous mode for
319 	 * sampling and/or irq.
320 	 */
321 	return opt4060_set_state_common(chip, continuous_sampling, continuous_irq);
322 }
323 
324 /*
325  * This function is called with framework mutex locked.
326  */
327 static int opt4060_trigger_set_state(struct iio_trigger *trig, bool state)
328 {
329 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
330 	struct opt4060_chip *chip = iio_priv(indio_dev);
331 
332 	return opt4060_set_state_common(chip, state, state);
333 }
334 
335 static int opt4060_read_raw_value(struct opt4060_chip *chip,
336 				  unsigned long address, u32 *raw)
337 {
338 	int ret;
339 	u16 result[2];
340 	u32 mantissa_raw;
341 	u16 msb, lsb;
342 	u8 exp, count, crc, calc_crc;
343 
344 	ret = regmap_bulk_read(chip->regmap, address, result, 2);
345 	if (ret) {
346 		dev_err(chip->dev, "Reading channel data failed\n");
347 		return ret;
348 	}
349 	exp = FIELD_GET(OPT4060_EXPONENT_MASK, result[0]);
350 	msb = FIELD_GET(OPT4060_MSB_MASK, result[0]);
351 	count = FIELD_GET(OPT4060_COUNTER_MASK, result[1]);
352 	crc = FIELD_GET(OPT4060_CRC_MASK, result[1]);
353 	lsb = FIELD_GET(OPT4060_LSB_MASK, result[1]);
354 	mantissa_raw = (msb << 8) + lsb;
355 	calc_crc = opt4060_calculate_crc(exp, mantissa_raw, count);
356 	if (calc_crc != crc)
357 		return -EIO;
358 	*raw = mantissa_raw << exp;
359 	return 0;
360 }
361 
362 static int opt4060_trigger_new_samples(struct iio_dev *indio_dev)
363 {
364 	struct opt4060_chip *chip = iio_priv(indio_dev);
365 	int ret;
366 
367 	/*
368 	 * The conversion time should be 500us startup time plus the integration time
369 	 * times the number of channels. An exact timeout isn't critical, it's better
370 	 * not to get incorrect errors in the log. Setting the timeout to double the
371 	 * theoretical time plus and extra 100ms margin.
372 	 */
373 	unsigned int timeout_us = (500 + OPT4060_NUM_CHANS *
374 				  opt4060_int_time_reg[chip->int_time][0]) * 2 + 100000;
375 
376 	/* Setting the state in one shot mode with irq on each sample. */
377 	ret = opt4060_set_driver_state(indio_dev, false, true);
378 	if (ret)
379 		return ret;
380 
381 	if (chip->irq) {
382 		guard(mutex)(&chip->irq_setting_lock);
383 		reinit_completion(&chip->completion);
384 		if (wait_for_completion_timeout(&chip->completion,
385 						usecs_to_jiffies(timeout_us)) == 0) {
386 			dev_err(chip->dev, "Completion timed out.\n");
387 			return -ETIME;
388 		}
389 	} else {
390 		unsigned int ready;
391 
392 		ret = regmap_read_poll_timeout(chip->regmap, OPT4060_RES_CTRL,
393 					       ready, (ready & OPT4060_RES_CTRL_CONV_READY),
394 					       1000, timeout_us);
395 		if (ret)
396 			dev_err(chip->dev, "Conversion ready did not finish within timeout.\n");
397 	}
398 	/* Setting the state in one shot mode with irq on thresholds. */
399 	return opt4060_set_driver_state(indio_dev, false, false);
400 }
401 
402 static int opt4060_read_chan_raw(struct iio_dev *indio_dev,
403 				 struct iio_chan_spec const *chan, int *val)
404 {
405 	struct opt4060_chip *chip = iio_priv(indio_dev);
406 	u32 adc_raw;
407 	int ret;
408 
409 	ret = opt4060_trigger_new_samples(indio_dev);
410 	if (ret) {
411 		dev_err(chip->dev, "Failed to trigger new samples.\n");
412 		return ret;
413 	}
414 
415 	ret = opt4060_read_raw_value(chip, chan->address, &adc_raw);
416 	if (ret) {
417 		dev_err(chip->dev, "Reading raw channel data failed.\n");
418 		return ret;
419 	}
420 	*val = adc_raw;
421 	return IIO_VAL_INT;
422 }
423 
424 /*
425  * Returns the scale values used for red, green and blue. Scales the raw value
426  * so that for a particular test light source, typically white, the measurement
427  * intensity is the same across different color channels.
428  */
429 static int opt4060_get_chan_scale(struct iio_dev *indio_dev,
430 				  struct iio_chan_spec const *chan,
431 				  int *val, int *val2)
432 {
433 	struct opt4060_chip *chip = iio_priv(indio_dev);
434 
435 	switch (chan->scan_index) {
436 	case OPT4060_RED:
437 		/* 2.4 */
438 		*val = 2;
439 		*val2 = 400000;
440 		break;
441 	case OPT4060_GREEN:
442 		/* 1.0 */
443 		*val = 1;
444 		*val2 = 0;
445 		break;
446 	case OPT4060_BLUE:
447 		/* 1.3 */
448 		*val = 1;
449 		*val2 = 300000;
450 		break;
451 	default:
452 		dev_err(chip->dev, "Unexpected channel index.\n");
453 		return -EINVAL;
454 	}
455 	return IIO_VAL_INT_PLUS_MICRO;
456 }
457 
458 static int opt4060_calc_illuminance(struct opt4060_chip *chip, int *val)
459 {
460 	u32 lux_raw;
461 	int ret;
462 
463 	/* The green wide spectral channel is used for illuminance. */
464 	ret = opt4060_read_raw_value(chip, OPT4060_GREEN_MSB, &lux_raw);
465 	if (ret) {
466 		dev_err(chip->dev, "Reading raw channel data failed\n");
467 		return ret;
468 	}
469 
470 	/* Illuminance is calculated by ADC_RAW * 2.15e-3. */
471 	*val = DIV_U64_ROUND_CLOSEST((u64)(lux_raw * 215), 1000);
472 	return ret;
473 }
474 
475 static int opt4060_read_illuminance(struct iio_dev *indio_dev,
476 				    struct iio_chan_spec const *chan,
477 				    int *val)
478 {
479 	struct opt4060_chip *chip = iio_priv(indio_dev);
480 	int ret;
481 
482 	ret = opt4060_trigger_new_samples(indio_dev);
483 	if (ret) {
484 		dev_err(chip->dev, "Failed to trigger new samples.\n");
485 		return ret;
486 	}
487 	ret = opt4060_calc_illuminance(chip, val);
488 	if (ret) {
489 		dev_err(chip->dev, "Failed to calculate illuminance.\n");
490 		return ret;
491 	}
492 
493 	return IIO_VAL_INT;
494 }
495 
496 static int opt4060_set_int_time(struct opt4060_chip *chip)
497 {
498 	unsigned int regval;
499 	int ret;
500 
501 	regval = FIELD_PREP(OPT4060_CTRL_CONV_TIME_MASK, chip->int_time);
502 	ret = regmap_update_bits(chip->regmap, OPT4060_CTRL,
503 				 OPT4060_CTRL_CONV_TIME_MASK, regval);
504 	if (ret)
505 		dev_err(chip->dev, "Failed to set integration time.\n");
506 
507 	return ret;
508 }
509 
510 static int opt4060_power_down(struct opt4060_chip *chip)
511 {
512 	int ret;
513 
514 	ret = regmap_clear_bits(chip->regmap, OPT4060_CTRL, OPT4060_CTRL_OPER_MODE_MASK);
515 	if (ret)
516 		dev_err(chip->dev, "Failed to power down\n");
517 
518 	return ret;
519 }
520 
521 static void opt4060_chip_off_action(void *chip)
522 {
523 	opt4060_power_down(chip);
524 }
525 
526 #define _OPT4060_COLOR_CHANNEL(_color, _mask, _ev_spec, _num_ev_spec)		\
527 {										\
528 	.type = IIO_INTENSITY,							\
529 	.modified = 1,								\
530 	.channel2 = IIO_MOD_LIGHT_##_color,					\
531 	.info_mask_separate = _mask,						\
532 	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_INT_TIME),			\
533 	.info_mask_shared_by_all_available = BIT(IIO_CHAN_INFO_INT_TIME),	\
534 	.address = OPT4060_##_color##_MSB,					\
535 	.scan_index = OPT4060_##_color,						\
536 	.scan_type = {								\
537 		.sign = 'u',							\
538 		.realbits = 32,							\
539 		.storagebits = 32,						\
540 		.endianness = IIO_CPU,						\
541 	},									\
542 	.event_spec = _ev_spec,							\
543 	.num_event_specs = _num_ev_spec,					\
544 }
545 
546 #define OPT4060_COLOR_CHANNEL(_color, _mask)					\
547 	_OPT4060_COLOR_CHANNEL(_color, _mask, opt4060_event_spec,		\
548 			       ARRAY_SIZE(opt4060_event_spec))			\
549 
550 #define OPT4060_COLOR_CHANNEL_NO_EVENTS(_color, _mask)				\
551 	_OPT4060_COLOR_CHANNEL(_color, _mask, NULL, 0)				\
552 
553 #define OPT4060_LIGHT_CHANNEL(_channel)						\
554 {										\
555 	.type = IIO_LIGHT,							\
556 	.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),			\
557 	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_INT_TIME),			\
558 	.info_mask_shared_by_all_available = BIT(IIO_CHAN_INFO_INT_TIME),	\
559 	.scan_index = OPT4060_##_channel,					\
560 	.scan_type = {								\
561 		.sign = 'u',							\
562 		.realbits = 32,							\
563 		.storagebits = 32,						\
564 		.endianness = IIO_CPU,						\
565 	},									\
566 }
567 
568 static const struct iio_event_spec opt4060_event_spec[] = {
569 	{
570 		.type = IIO_EV_TYPE_THRESH,
571 		.dir = IIO_EV_DIR_RISING,
572 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
573 				 BIT(IIO_EV_INFO_ENABLE),
574 	}, {
575 		.type = IIO_EV_TYPE_THRESH,
576 		.dir = IIO_EV_DIR_FALLING,
577 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
578 				 BIT(IIO_EV_INFO_ENABLE),
579 	}, {
580 		.type = IIO_EV_TYPE_THRESH,
581 		.dir = IIO_EV_DIR_EITHER,
582 		.mask_separate = BIT(IIO_EV_INFO_PERIOD),
583 	},
584 };
585 
586 static const struct iio_chan_spec opt4060_channels[] = {
587 	OPT4060_COLOR_CHANNEL(RED, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
588 	OPT4060_COLOR_CHANNEL(GREEN, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
589 	OPT4060_COLOR_CHANNEL(BLUE, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
590 	OPT4060_COLOR_CHANNEL(CLEAR, BIT(IIO_CHAN_INFO_RAW)),
591 	OPT4060_LIGHT_CHANNEL(ILLUM),
592 	IIO_CHAN_SOFT_TIMESTAMP(OPT4060_NUM_CHANS),
593 };
594 
595 static const struct iio_chan_spec opt4060_channels_no_events[] = {
596 	OPT4060_COLOR_CHANNEL_NO_EVENTS(RED, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
597 	OPT4060_COLOR_CHANNEL_NO_EVENTS(GREEN, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
598 	OPT4060_COLOR_CHANNEL_NO_EVENTS(BLUE, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
599 	OPT4060_COLOR_CHANNEL_NO_EVENTS(CLEAR, BIT(IIO_CHAN_INFO_RAW)),
600 	OPT4060_LIGHT_CHANNEL(ILLUM),
601 	IIO_CHAN_SOFT_TIMESTAMP(OPT4060_NUM_CHANS),
602 };
603 
604 static int opt4060_read_raw(struct iio_dev *indio_dev,
605 			    struct iio_chan_spec const *chan,
606 			    int *val, int *val2, long mask)
607 {
608 	struct opt4060_chip *chip = iio_priv(indio_dev);
609 
610 	switch (mask) {
611 	case IIO_CHAN_INFO_RAW:
612 		return opt4060_read_chan_raw(indio_dev, chan, val);
613 	case IIO_CHAN_INFO_SCALE:
614 		return opt4060_get_chan_scale(indio_dev, chan, val, val2);
615 	case IIO_CHAN_INFO_PROCESSED:
616 		return opt4060_read_illuminance(indio_dev, chan, val);
617 	case IIO_CHAN_INFO_INT_TIME:
618 		*val = 0;
619 		*val2 = opt4060_int_time_reg[chip->int_time][0];
620 		return IIO_VAL_INT_PLUS_MICRO;
621 	default:
622 		return -EINVAL;
623 	}
624 }
625 
626 static int opt4060_write_raw(struct iio_dev *indio_dev,
627 			     struct iio_chan_spec const *chan,
628 			     int val, int val2, long mask)
629 {
630 	struct opt4060_chip *chip = iio_priv(indio_dev);
631 	int int_time;
632 
633 	switch (mask) {
634 	case IIO_CHAN_INFO_INT_TIME:
635 		if (val)
636 			return -EINVAL;
637 
638 		int_time = opt4060_als_time_to_index(val2);
639 		if (int_time < 0)
640 			return int_time;
641 		chip->int_time = int_time;
642 		return opt4060_set_int_time(chip);
643 	default:
644 		return -EINVAL;
645 	}
646 }
647 
648 static int opt4060_write_raw_get_fmt(struct iio_dev *indio_dev,
649 				     struct iio_chan_spec const *chan,
650 				     long mask)
651 {
652 	switch (mask) {
653 	case IIO_CHAN_INFO_INT_TIME:
654 		return IIO_VAL_INT_PLUS_MICRO;
655 	default:
656 		return -EINVAL;
657 	}
658 }
659 
660 static u32 opt4060_calc_th_reg(u32 adc_val)
661 {
662 	u32 th_val, th_exp, bits;
663 	/*
664 	 * The threshold registers take 4 bits of exponent and 12 bits of data
665 	 * ADC = TH_VAL << (8 + TH_EXP)
666 	 */
667 	bits = fls(adc_val);
668 
669 	if (bits > 31)
670 		th_exp = 11; /* Maximum exponent */
671 	else if (bits > 20)
672 		th_exp = bits - 20;
673 	else
674 		th_exp = 0;
675 	th_val = (adc_val >> (8 + th_exp)) & 0xfff;
676 
677 	return (th_exp << 12) + th_val;
678 }
679 
680 static u32 opt4060_calc_val_from_th_reg(u32 th_reg)
681 {
682 	/*
683 	 * The threshold registers take 4 bits of exponent and 12 bits of data
684 	 * ADC = TH_VAL << (8 + TH_EXP)
685 	 */
686 	u32 th_val, th_exp;
687 
688 	th_exp = (th_reg >> 12) & 0xf;
689 	th_val = th_reg & 0xfff;
690 
691 	return th_val << (8 + th_exp);
692 }
693 
694 static int opt4060_read_available(struct iio_dev *indio_dev,
695 				  struct iio_chan_spec const *chan,
696 				  const int **vals, int *type, int *length,
697 				  long mask)
698 {
699 	switch (mask) {
700 	case IIO_CHAN_INFO_INT_TIME:
701 		*length = ARRAY_SIZE(opt4060_int_time_available) * 2;
702 		*vals = (const int *)opt4060_int_time_available;
703 		*type = IIO_VAL_INT_PLUS_MICRO;
704 		return IIO_AVAIL_LIST;
705 
706 	default:
707 		return -EINVAL;
708 	}
709 }
710 
711 static ssize_t opt4060_read_ev_period(struct opt4060_chip *chip, int *val,
712 				      int *val2)
713 {
714 	int ret, pers, fault_count, int_time;
715 	u64 uval;
716 	u32 rem;
717 
718 	int_time = opt4060_int_time_reg[chip->int_time][0];
719 
720 	ret = regmap_read(chip->regmap, OPT4060_CTRL, &fault_count);
721 	if (ret < 0)
722 		return ret;
723 
724 	fault_count = fault_count & OPT4060_CTRL_FAULT_COUNT_MASK;
725 	switch (fault_count) {
726 	case OPT4060_CTRL_FAULT_COUNT_2:
727 		pers = 2;
728 		break;
729 	case OPT4060_CTRL_FAULT_COUNT_4:
730 		pers = 4;
731 		break;
732 	case OPT4060_CTRL_FAULT_COUNT_8:
733 		pers = 8;
734 		break;
735 
736 	default:
737 		pers = 1;
738 		break;
739 	}
740 
741 	uval = mul_u32_u32(int_time, pers);
742 	*val = div_u64_rem(uval, MICRO, &rem);
743 	*val2 = rem;
744 
745 	return IIO_VAL_INT_PLUS_MICRO;
746 }
747 
748 static ssize_t opt4060_write_ev_period(struct opt4060_chip *chip, int val,
749 				       int val2)
750 {
751 	u64 uval, int_time;
752 	unsigned int regval, fault_count_val;
753 
754 	uval = mul_u32_u32(val, MICRO) + val2;
755 	int_time = opt4060_int_time_reg[chip->int_time][0];
756 
757 	/* Check if the period is closest to 1, 2, 4 or 8 times integration time.*/
758 	if (uval <= int_time)
759 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_1;
760 	else if (uval <= int_time * 2)
761 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_2;
762 	else if (uval <= int_time * 4)
763 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_4;
764 	else
765 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_8;
766 
767 	regval = FIELD_PREP(OPT4060_CTRL_FAULT_COUNT_MASK, fault_count_val);
768 	return regmap_update_bits(chip->regmap, OPT4060_CTRL,
769 				 OPT4060_CTRL_FAULT_COUNT_MASK, regval);
770 }
771 
772 static int opt4060_get_channel_sel(struct opt4060_chip *chip, int *ch_sel)
773 {
774 	int ret;
775 	u32 regval;
776 
777 	ret = regmap_read(chip->regmap, OPT4060_INT_CTRL, &regval);
778 	if (ret) {
779 		dev_err(chip->dev, "Failed to get channel selection.\n");
780 		return ret;
781 	}
782 	*ch_sel = FIELD_GET(OPT4060_INT_CTRL_THRESH_SEL, regval);
783 	return ret;
784 }
785 
786 static int opt4060_set_channel_sel(struct opt4060_chip *chip, int ch_sel)
787 {
788 	int ret;
789 	u32 regval;
790 
791 	regval = FIELD_PREP(OPT4060_INT_CTRL_THRESH_SEL, ch_sel);
792 	ret = regmap_update_bits(chip->regmap, OPT4060_INT_CTRL,
793 				 OPT4060_INT_CTRL_THRESH_SEL, regval);
794 	if (ret)
795 		dev_err(chip->dev, "Failed to set channel selection.\n");
796 	return ret;
797 }
798 
799 static int opt4060_get_thresholds(struct opt4060_chip *chip, u32 *th_lo, u32 *th_hi)
800 {
801 	int ret;
802 	u32 regval;
803 
804 	ret = regmap_read(chip->regmap, OPT4060_THRESHOLD_LOW, &regval);
805 	if (ret) {
806 		dev_err(chip->dev, "Failed to read THRESHOLD_LOW.\n");
807 		return ret;
808 	}
809 	*th_lo = opt4060_calc_val_from_th_reg(regval);
810 
811 	ret = regmap_read(chip->regmap, OPT4060_THRESHOLD_HIGH, &regval);
812 	if (ret) {
813 		dev_err(chip->dev, "Failed to read THRESHOLD_HIGH.\n");
814 		return ret;
815 	}
816 	*th_hi = opt4060_calc_val_from_th_reg(regval);
817 
818 	return ret;
819 }
820 
821 static int opt4060_set_thresholds(struct opt4060_chip *chip, u32 th_lo, u32 th_hi)
822 {
823 	int ret;
824 
825 	ret = regmap_write(chip->regmap, OPT4060_THRESHOLD_LOW, opt4060_calc_th_reg(th_lo));
826 	if (ret) {
827 		dev_err(chip->dev, "Failed to write THRESHOLD_LOW.\n");
828 		return ret;
829 	}
830 
831 	ret = regmap_write(chip->regmap, OPT4060_THRESHOLD_HIGH, opt4060_calc_th_reg(th_hi));
832 	if (ret)
833 		dev_err(chip->dev, "Failed to write THRESHOLD_HIGH.\n");
834 
835 	return ret;
836 }
837 
838 static int opt4060_read_event(struct iio_dev *indio_dev,
839 			      const struct iio_chan_spec *chan,
840 			      enum iio_event_type type,
841 			      enum iio_event_direction dir,
842 			      enum iio_event_info info,
843 			      int *val, int *val2)
844 {
845 	struct opt4060_chip *chip = iio_priv(indio_dev);
846 	u32 th_lo, th_hi;
847 	int ret;
848 
849 	if (chan->type != IIO_INTENSITY)
850 		return -EINVAL;
851 	if (type != IIO_EV_TYPE_THRESH)
852 		return -EINVAL;
853 
854 	switch (info) {
855 	case IIO_EV_INFO_VALUE:
856 		ret = opt4060_get_thresholds(chip, &th_lo, &th_hi);
857 		if (ret)
858 			return ret;
859 		if (dir == IIO_EV_DIR_FALLING) {
860 			*val = th_lo;
861 			ret = IIO_VAL_INT;
862 		} else if (dir == IIO_EV_DIR_RISING) {
863 			*val = th_hi;
864 			ret = IIO_VAL_INT;
865 		}
866 		return ret;
867 	case IIO_EV_INFO_PERIOD:
868 		return opt4060_read_ev_period(chip, val, val2);
869 	default:
870 		return -EINVAL;
871 	}
872 }
873 
874 static int opt4060_write_event(struct iio_dev *indio_dev,
875 			       const struct iio_chan_spec *chan,
876 			       enum iio_event_type type,
877 			       enum iio_event_direction dir,
878 			       enum iio_event_info info,
879 			       int val, int val2)
880 {
881 	struct opt4060_chip *chip = iio_priv(indio_dev);
882 	u32 th_lo, th_hi;
883 	int ret;
884 
885 	if (chan->type != IIO_INTENSITY)
886 		return -EINVAL;
887 	if (type != IIO_EV_TYPE_THRESH)
888 		return -EINVAL;
889 
890 	switch (info) {
891 	case IIO_EV_INFO_VALUE:
892 		ret = opt4060_get_thresholds(chip, &th_lo, &th_hi);
893 		if (ret)
894 			return ret;
895 		if (dir == IIO_EV_DIR_FALLING)
896 			th_lo = val;
897 		else if (dir == IIO_EV_DIR_RISING)
898 			th_hi = val;
899 		return opt4060_set_thresholds(chip, th_lo, th_hi);
900 	case IIO_EV_INFO_PERIOD:
901 		return opt4060_write_ev_period(chip, val, val2);
902 	default:
903 		return -EINVAL;
904 	}
905 }
906 
907 static int opt4060_read_event_config(struct iio_dev *indio_dev,
908 				     const struct iio_chan_spec *chan,
909 				     enum iio_event_type type,
910 				     enum iio_event_direction dir)
911 {
912 	int ch_sel, ch_idx = chan->scan_index;
913 	struct opt4060_chip *chip = iio_priv(indio_dev);
914 	int ret;
915 
916 	if (chan->type != IIO_INTENSITY)
917 		return -EINVAL;
918 	if (type != IIO_EV_TYPE_THRESH)
919 		return -EINVAL;
920 
921 	ret = opt4060_get_channel_sel(chip, &ch_sel);
922 	if (ret)
923 		return ret;
924 
925 	if (((dir == IIO_EV_DIR_FALLING) && chip->thresh_event_lo_active) ||
926 	    ((dir == IIO_EV_DIR_RISING) && chip->thresh_event_hi_active))
927 		return ch_sel == ch_idx;
928 
929 	return ret;
930 }
931 
932 static int opt4060_write_event_config(struct iio_dev *indio_dev,
933 				      const struct iio_chan_spec *chan,
934 				      enum iio_event_type type,
935 				      enum iio_event_direction dir, bool state)
936 {
937 	int ch_sel, ch_idx = chan->scan_index;
938 	struct opt4060_chip *chip = iio_priv(indio_dev);
939 	int ret;
940 
941 	guard(mutex)(&chip->event_enabling_lock);
942 
943 	if (chan->type != IIO_INTENSITY)
944 		return -EINVAL;
945 	if (type != IIO_EV_TYPE_THRESH)
946 		return -EINVAL;
947 
948 	ret = opt4060_get_channel_sel(chip, &ch_sel);
949 	if (ret)
950 		return ret;
951 
952 	if (state) {
953 		/* Only one channel can be active at the same time */
954 		if ((chip->thresh_event_lo_active || chip->thresh_event_hi_active) &&
955 		    (ch_idx != ch_sel))
956 			return -EBUSY;
957 		if (dir == IIO_EV_DIR_FALLING)
958 			chip->thresh_event_lo_active = true;
959 		else if (dir == IIO_EV_DIR_RISING)
960 			chip->thresh_event_hi_active = true;
961 		ret = opt4060_set_channel_sel(chip, ch_idx);
962 		if (ret)
963 			return ret;
964 	} else {
965 		if (ch_idx == ch_sel) {
966 			if (dir == IIO_EV_DIR_FALLING)
967 				chip->thresh_event_lo_active = false;
968 			else if (dir == IIO_EV_DIR_RISING)
969 				chip->thresh_event_hi_active = false;
970 		}
971 	}
972 
973 	return opt4060_set_driver_state(indio_dev,
974 					chip->thresh_event_hi_active |
975 					chip->thresh_event_lo_active,
976 					false);
977 }
978 
979 static const struct iio_info opt4060_info = {
980 	.read_raw = opt4060_read_raw,
981 	.write_raw = opt4060_write_raw,
982 	.write_raw_get_fmt = opt4060_write_raw_get_fmt,
983 	.read_avail = opt4060_read_available,
984 	.read_event_value = opt4060_read_event,
985 	.write_event_value = opt4060_write_event,
986 	.read_event_config = opt4060_read_event_config,
987 	.write_event_config = opt4060_write_event_config,
988 };
989 
990 static const struct iio_info opt4060_info_no_irq = {
991 	.read_raw = opt4060_read_raw,
992 	.write_raw = opt4060_write_raw,
993 	.write_raw_get_fmt = opt4060_write_raw_get_fmt,
994 	.read_avail = opt4060_read_available,
995 };
996 
997 static int opt4060_load_defaults(struct opt4060_chip *chip)
998 {
999 	u16 reg;
1000 	int ret;
1001 
1002 	chip->int_time = OPT4060_DEFAULT_CONVERSION_TIME;
1003 
1004 	/* Set initial MIN/MAX thresholds */
1005 	ret = opt4060_set_thresholds(chip, 0, UINT_MAX);
1006 	if (ret)
1007 		return ret;
1008 
1009 	/*
1010 	 * Setting auto-range, latched window for thresholds, one-shot conversion
1011 	 * and quick wake-up mode as default.
1012 	 */
1013 	reg = FIELD_PREP(OPT4060_CTRL_RANGE_MASK,
1014 			 OPT4060_CTRL_LIGHT_SCALE_AUTO);
1015 	reg |= FIELD_PREP(OPT4060_CTRL_CONV_TIME_MASK, chip->int_time);
1016 	reg |= FIELD_PREP(OPT4060_CTRL_OPER_MODE_MASK,
1017 				OPT4060_CTRL_OPER_MODE_ONE_SHOT);
1018 	reg |= OPT4060_CTRL_QWAKE_MASK | OPT4060_CTRL_LATCH_MASK;
1019 
1020 	ret = regmap_write(chip->regmap, OPT4060_CTRL, reg);
1021 	if (ret)
1022 		dev_err(chip->dev, "Failed to set configuration\n");
1023 
1024 	return ret;
1025 }
1026 
1027 static bool opt4060_volatile_reg(struct device *dev, unsigned int reg)
1028 {
1029 	return reg <= OPT4060_CLEAR_LSB || reg == OPT4060_RES_CTRL;
1030 }
1031 
1032 static bool opt4060_writable_reg(struct device *dev, unsigned int reg)
1033 {
1034 	return reg >= OPT4060_THRESHOLD_LOW || reg >= OPT4060_INT_CTRL;
1035 }
1036 
1037 static bool opt4060_readonly_reg(struct device *dev, unsigned int reg)
1038 {
1039 	return reg == OPT4060_DEVICE_ID;
1040 }
1041 
1042 static bool opt4060_readable_reg(struct device *dev, unsigned int reg)
1043 {
1044 	/* Volatile, writable and read-only registers are readable. */
1045 	return opt4060_volatile_reg(dev, reg) || opt4060_writable_reg(dev, reg) ||
1046 	       opt4060_readonly_reg(dev, reg);
1047 }
1048 
1049 static const struct regmap_config opt4060_regmap_config = {
1050 	.name = "opt4060",
1051 	.reg_bits = 8,
1052 	.val_bits = 16,
1053 	.cache_type = REGCACHE_MAPLE,
1054 	.max_register = OPT4060_DEVICE_ID,
1055 	.readable_reg = opt4060_readable_reg,
1056 	.writeable_reg = opt4060_writable_reg,
1057 	.volatile_reg = opt4060_volatile_reg,
1058 	.val_format_endian = REGMAP_ENDIAN_BIG,
1059 };
1060 
1061 static const struct iio_trigger_ops opt4060_trigger_ops = {
1062 	.set_trigger_state = opt4060_trigger_set_state,
1063 };
1064 
1065 static irqreturn_t opt4060_trigger_handler(int irq, void *p)
1066 {
1067 	struct iio_poll_func *pf = p;
1068 	struct iio_dev *idev = pf->indio_dev;
1069 	struct opt4060_chip *chip = iio_priv(idev);
1070 	struct  {
1071 		u32 chan[OPT4060_NUM_CHANS];
1072 		aligned_s64 ts;
1073 	} raw = { };
1074 	int i = 0;
1075 	int chan, ret;
1076 
1077 	/* If the trigger is not from this driver, a new sample is needed.*/
1078 	if (iio_trigger_validate_own_device(idev->trig, idev))
1079 		opt4060_trigger_new_samples(idev);
1080 
1081 	iio_for_each_active_channel(idev, chan) {
1082 		if (chan == OPT4060_ILLUM)
1083 			ret = opt4060_calc_illuminance(chip, &raw.chan[i++]);
1084 		else
1085 			ret = opt4060_read_raw_value(chip,
1086 						     idev->channels[chan].address,
1087 						     &raw.chan[i++]);
1088 		if (ret) {
1089 			dev_err(chip->dev, "Reading channel data failed\n");
1090 			goto err_read;
1091 		}
1092 	}
1093 
1094 	iio_push_to_buffers_with_ts(idev, &raw, sizeof(raw), pf->timestamp);
1095 err_read:
1096 	iio_trigger_notify_done(idev->trig);
1097 	return IRQ_HANDLED;
1098 }
1099 
1100 static irqreturn_t opt4060_irq_thread(int irq, void *private)
1101 {
1102 	struct iio_dev *idev = private;
1103 	struct opt4060_chip *chip = iio_priv(idev);
1104 	int ret, dummy;
1105 	unsigned int int_res;
1106 
1107 	ret = regmap_read(chip->regmap, OPT4060_RES_CTRL, &int_res);
1108 	if (ret < 0) {
1109 		dev_err(chip->dev, "Failed to read interrupt reasons.\n");
1110 		return IRQ_NONE;
1111 	}
1112 
1113 	/* Read OPT4060_CTRL to clear interrupt */
1114 	ret = regmap_read(chip->regmap, OPT4060_CTRL, &dummy);
1115 	if (ret < 0) {
1116 		dev_err(chip->dev, "Failed to clear interrupt\n");
1117 		return IRQ_NONE;
1118 	}
1119 
1120 	/* Handle events */
1121 	if (int_res & (OPT4060_RES_CTRL_FLAG_H | OPT4060_RES_CTRL_FLAG_L)) {
1122 		u64 code;
1123 		int chan = 0;
1124 
1125 		ret = opt4060_get_channel_sel(chip, &chan);
1126 		if (ret) {
1127 			dev_err(chip->dev, "Failed to read threshold channel.\n");
1128 			return IRQ_NONE;
1129 		}
1130 
1131 		/* Check if the interrupt is from the lower threshold */
1132 		if (int_res & OPT4060_RES_CTRL_FLAG_L) {
1133 			code = IIO_MOD_EVENT_CODE(IIO_INTENSITY,
1134 						  chan,
1135 						  idev->channels[chan].channel2,
1136 						  IIO_EV_TYPE_THRESH,
1137 						  IIO_EV_DIR_FALLING);
1138 			iio_push_event(idev, code, iio_get_time_ns(idev));
1139 		}
1140 		/* Check if the interrupt is from the upper threshold */
1141 		if (int_res & OPT4060_RES_CTRL_FLAG_H) {
1142 			code = IIO_MOD_EVENT_CODE(IIO_INTENSITY,
1143 						  chan,
1144 						  idev->channels[chan].channel2,
1145 						  IIO_EV_TYPE_THRESH,
1146 						  IIO_EV_DIR_RISING);
1147 			iio_push_event(idev, code, iio_get_time_ns(idev));
1148 		}
1149 	}
1150 
1151 	/* Handle conversion ready */
1152 	if (int_res & OPT4060_RES_CTRL_CONV_READY) {
1153 		/* Signal completion for potentially waiting reads */
1154 		complete(&chip->completion);
1155 
1156 		/* Handle data ready triggers */
1157 		if (iio_buffer_enabled(idev))
1158 			iio_trigger_poll_nested(chip->trig);
1159 	}
1160 	return IRQ_HANDLED;
1161 }
1162 
1163 static int opt4060_setup_buffer(struct opt4060_chip *chip, struct iio_dev *idev)
1164 {
1165 	int ret;
1166 
1167 	ret = devm_iio_triggered_buffer_setup(chip->dev, idev,
1168 					      &iio_pollfunc_store_time,
1169 					      opt4060_trigger_handler, NULL);
1170 	if (ret)
1171 		return dev_err_probe(chip->dev, ret,
1172 				     "Buffer setup failed.\n");
1173 	return ret;
1174 }
1175 
1176 static int opt4060_setup_trigger(struct opt4060_chip *chip, struct iio_dev *idev)
1177 {
1178 	struct iio_trigger *data_trigger;
1179 	char *name;
1180 	int ret;
1181 
1182 	data_trigger = devm_iio_trigger_alloc(chip->dev, "%s-data-ready-dev%d",
1183 					      idev->name, iio_device_id(idev));
1184 	if (!data_trigger)
1185 		return -ENOMEM;
1186 
1187 	/*
1188 	 * The data trigger allows for sample capture on each new conversion
1189 	 * ready interrupt.
1190 	 */
1191 	chip->trig = data_trigger;
1192 	data_trigger->ops = &opt4060_trigger_ops;
1193 	iio_trigger_set_drvdata(data_trigger, idev);
1194 	ret = devm_iio_trigger_register(chip->dev, data_trigger);
1195 	if (ret)
1196 		return dev_err_probe(chip->dev, ret,
1197 				     "Data ready trigger registration failed\n");
1198 
1199 	name = devm_kasprintf(chip->dev, GFP_KERNEL, "%s-opt4060",
1200 			      dev_name(chip->dev));
1201 	if (!name)
1202 		return -ENOMEM;
1203 
1204 	ret = devm_request_threaded_irq(chip->dev, chip->irq, NULL, opt4060_irq_thread,
1205 					IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
1206 					name, idev);
1207 	if (ret)
1208 		return ret;
1209 
1210 	init_completion(&chip->completion);
1211 
1212 	ret = devm_mutex_init(chip->dev, &chip->irq_setting_lock);
1213 	if (ret)
1214 		return ret;
1215 
1216 	ret = devm_mutex_init(chip->dev, &chip->event_enabling_lock);
1217 	if (ret)
1218 		return ret;
1219 
1220 	ret = regmap_write_bits(chip->regmap, OPT4060_INT_CTRL,
1221 				OPT4060_INT_CTRL_OUTPUT,
1222 				OPT4060_INT_CTRL_OUTPUT);
1223 	if (ret)
1224 		return dev_err_probe(chip->dev, ret,
1225 				     "Failed to set interrupt as output\n");
1226 
1227 	return 0;
1228 }
1229 
1230 static int opt4060_probe(struct i2c_client *client)
1231 {
1232 	struct device *dev = &client->dev;
1233 	struct opt4060_chip *chip;
1234 	struct iio_dev *indio_dev;
1235 	int ret;
1236 	unsigned int regval, dev_id;
1237 
1238 	indio_dev = devm_iio_device_alloc(dev, sizeof(*chip));
1239 	if (!indio_dev)
1240 		return -ENOMEM;
1241 
1242 	chip = iio_priv(indio_dev);
1243 
1244 	ret = devm_regulator_get_enable(dev, "vdd");
1245 	if (ret)
1246 		return dev_err_probe(dev, ret, "Failed to enable vdd supply\n");
1247 
1248 	chip->regmap = devm_regmap_init_i2c(client, &opt4060_regmap_config);
1249 	if (IS_ERR(chip->regmap))
1250 		return dev_err_probe(dev, PTR_ERR(chip->regmap),
1251 				     "regmap initialization failed\n");
1252 
1253 	chip->dev = dev;
1254 	chip->irq = client->irq;
1255 
1256 	ret = regmap_reinit_cache(chip->regmap, &opt4060_regmap_config);
1257 	if (ret)
1258 		return dev_err_probe(dev, ret,
1259 				     "failed to reinit regmap cache\n");
1260 
1261 	ret = regmap_read(chip->regmap, OPT4060_DEVICE_ID, &regval);
1262 	if (ret < 0)
1263 		return dev_err_probe(dev, ret,
1264 			"Failed to read the device ID register\n");
1265 
1266 	dev_id = FIELD_GET(OPT4060_DEVICE_ID_MASK, regval);
1267 	if (dev_id != OPT4060_DEVICE_ID_VAL)
1268 		dev_info(dev, "Device ID: %#04x unknown\n", dev_id);
1269 
1270 	if (chip->irq) {
1271 		indio_dev->info = &opt4060_info;
1272 		indio_dev->channels = opt4060_channels;
1273 		indio_dev->num_channels = ARRAY_SIZE(opt4060_channels);
1274 	} else {
1275 		indio_dev->info = &opt4060_info_no_irq;
1276 		indio_dev->channels = opt4060_channels_no_events;
1277 		indio_dev->num_channels = ARRAY_SIZE(opt4060_channels_no_events);
1278 	}
1279 	indio_dev->modes = INDIO_DIRECT_MODE;
1280 	indio_dev->name = "opt4060";
1281 
1282 	ret = opt4060_load_defaults(chip);
1283 	if (ret < 0)
1284 		return dev_err_probe(dev, ret,
1285 				     "Failed to set sensor defaults\n");
1286 
1287 	ret = devm_add_action_or_reset(dev, opt4060_chip_off_action, chip);
1288 	if (ret < 0)
1289 		return ret;
1290 
1291 	ret = opt4060_setup_buffer(chip, indio_dev);
1292 	if (ret)
1293 		return ret;
1294 
1295 	if (chip->irq) {
1296 		ret = opt4060_setup_trigger(chip, indio_dev);
1297 		if (ret)
1298 			return ret;
1299 	}
1300 
1301 	return devm_iio_device_register(dev, indio_dev);
1302 }
1303 
1304 static const struct i2c_device_id opt4060_id[] = {
1305 	{ .name = "opt4060" },
1306 	{ }
1307 };
1308 MODULE_DEVICE_TABLE(i2c, opt4060_id);
1309 
1310 static const struct of_device_id opt4060_of_match[] = {
1311 	{ .compatible = "ti,opt4060" },
1312 	{ }
1313 };
1314 MODULE_DEVICE_TABLE(of, opt4060_of_match);
1315 
1316 static struct i2c_driver opt4060_driver = {
1317 	.driver = {
1318 		.name = "opt4060",
1319 		.of_match_table = opt4060_of_match,
1320 	},
1321 	.probe = opt4060_probe,
1322 	.id_table = opt4060_id,
1323 };
1324 module_i2c_driver(opt4060_driver);
1325 
1326 MODULE_AUTHOR("Per-Daniel Olsson <perdaniel.olsson@axis.com>");
1327 MODULE_DESCRIPTION("Texas Instruments OPT4060 RGBW color sensor driver");
1328 MODULE_LICENSE("GPL");
1329