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 
opt4060_als_time_to_index(const u32 als_integration_time)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 
opt4060_calculate_crc(u8 exp,u32 mantissa,u8 count)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 
opt4060_set_int_state(struct opt4060_chip * chip,u32 state)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 
opt4060_set_sampling_mode(struct opt4060_chip * chip,bool continuous)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 
opt4060_event_active(struct opt4060_chip * chip)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 
opt4060_set_state_common(struct opt4060_chip * chip,bool continuous_sampling,bool continuous_irq)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  */
opt4060_set_driver_state(struct iio_dev * indio_dev,bool continuous_sampling,bool continuous_irq)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 	int ret = 0;
306 any_mode_retry:
307 	if (iio_device_claim_buffer_mode(indio_dev)) {
308 		/*
309 		 * This one is a *bit* hacky. If we cannot claim buffer mode,
310 		 * then try direct mode so that we make sure things cannot
311 		 * concurrently change. And we just keep trying until we get one
312 		 * of the modes...
313 		 */
314 		if (iio_device_claim_direct_mode(indio_dev))
315 			goto any_mode_retry;
316 		/*
317 		 * This path means that we managed to claim direct mode. In
318 		 * this case the buffer isn't enabled and it's okay to leave
319 		 * continuous mode for sampling and/or irq.
320 		 */
321 		ret = opt4060_set_state_common(chip, continuous_sampling,
322 					       continuous_irq);
323 		iio_device_release_direct_mode(indio_dev);
324 	} else {
325 		/*
326 		 * This path means that we managed to claim buffer mode. In
327 		 * this case the buffer is enabled and irq and sampling must go
328 		 * to or remain continuous, but only if the trigger is from this
329 		 * device.
330 		 */
331 		if (!iio_trigger_validate_own_device(indio_dev->trig, indio_dev))
332 			ret = opt4060_set_state_common(chip, true, true);
333 		else
334 			ret = opt4060_set_state_common(chip, continuous_sampling,
335 						       continuous_irq);
336 		iio_device_release_buffer_mode(indio_dev);
337 	}
338 	return ret;
339 }
340 
341 /*
342  * This function is called with framework mutex locked.
343  */
opt4060_trigger_set_state(struct iio_trigger * trig,bool state)344 static int opt4060_trigger_set_state(struct iio_trigger *trig, bool state)
345 {
346 	struct iio_dev *indio_dev = iio_trigger_get_drvdata(trig);
347 	struct opt4060_chip *chip = iio_priv(indio_dev);
348 
349 	return opt4060_set_state_common(chip, state, state);
350 }
351 
opt4060_read_raw_value(struct opt4060_chip * chip,unsigned long address,u32 * raw)352 static int opt4060_read_raw_value(struct opt4060_chip *chip,
353 				  unsigned long address, u32 *raw)
354 {
355 	int ret;
356 	u16 result[2];
357 	u32 mantissa_raw;
358 	u16 msb, lsb;
359 	u8 exp, count, crc, calc_crc;
360 
361 	ret = regmap_bulk_read(chip->regmap, address, result, 2);
362 	if (ret) {
363 		dev_err(chip->dev, "Reading channel data failed\n");
364 		return ret;
365 	}
366 	exp = FIELD_GET(OPT4060_EXPONENT_MASK, result[0]);
367 	msb = FIELD_GET(OPT4060_MSB_MASK, result[0]);
368 	count = FIELD_GET(OPT4060_COUNTER_MASK, result[1]);
369 	crc = FIELD_GET(OPT4060_CRC_MASK, result[1]);
370 	lsb = FIELD_GET(OPT4060_LSB_MASK, result[1]);
371 	mantissa_raw = (msb << 8) + lsb;
372 	calc_crc = opt4060_calculate_crc(exp, mantissa_raw, count);
373 	if (calc_crc != crc)
374 		return -EIO;
375 	*raw = mantissa_raw << exp;
376 	return 0;
377 }
378 
opt4060_trigger_new_samples(struct iio_dev * indio_dev)379 static int opt4060_trigger_new_samples(struct iio_dev *indio_dev)
380 {
381 	struct opt4060_chip *chip = iio_priv(indio_dev);
382 	int ret;
383 
384 	/*
385 	 * The conversion time should be 500us startup time plus the integration time
386 	 * times the number of channels. An exact timeout isn't critical, it's better
387 	 * not to get incorrect errors in the log. Setting the timeout to double the
388 	 * theoretical time plus and extra 100ms margin.
389 	 */
390 	unsigned int timeout_us = (500 + OPT4060_NUM_CHANS *
391 				  opt4060_int_time_reg[chip->int_time][0]) * 2 + 100000;
392 
393 	/* Setting the state in one shot mode with irq on each sample. */
394 	ret = opt4060_set_driver_state(indio_dev, false, true);
395 	if (ret)
396 		return ret;
397 
398 	if (chip->irq) {
399 		guard(mutex)(&chip->irq_setting_lock);
400 		reinit_completion(&chip->completion);
401 		if (wait_for_completion_timeout(&chip->completion,
402 						usecs_to_jiffies(timeout_us)) == 0) {
403 			dev_err(chip->dev, "Completion timed out.\n");
404 			return -ETIME;
405 		}
406 	} else {
407 		unsigned int ready;
408 
409 		ret = regmap_read_poll_timeout(chip->regmap, OPT4060_RES_CTRL,
410 					       ready, (ready & OPT4060_RES_CTRL_CONV_READY),
411 					       1000, timeout_us);
412 		if (ret)
413 			dev_err(chip->dev, "Conversion ready did not finish within timeout.\n");
414 	}
415 	/* Setting the state in one shot mode with irq on thresholds. */
416 	return opt4060_set_driver_state(indio_dev, false, false);
417 }
418 
opt4060_read_chan_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val)419 static int opt4060_read_chan_raw(struct iio_dev *indio_dev,
420 				 struct iio_chan_spec const *chan, int *val)
421 {
422 	struct opt4060_chip *chip = iio_priv(indio_dev);
423 	u32 adc_raw;
424 	int ret;
425 
426 	ret = opt4060_trigger_new_samples(indio_dev);
427 	if (ret) {
428 		dev_err(chip->dev, "Failed to trigger new samples.\n");
429 		return ret;
430 	}
431 
432 	ret = opt4060_read_raw_value(chip, chan->address, &adc_raw);
433 	if (ret) {
434 		dev_err(chip->dev, "Reading raw channel data failed.\n");
435 		return ret;
436 	}
437 	*val = adc_raw;
438 	return IIO_VAL_INT;
439 }
440 
441 /*
442  * Returns the scale values used for red, green and blue. Scales the raw value
443  * so that for a particular test light source, typically white, the measurement
444  * intensity is the same across different color channels.
445  */
opt4060_get_chan_scale(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2)446 static int opt4060_get_chan_scale(struct iio_dev *indio_dev,
447 				  struct iio_chan_spec const *chan,
448 				  int *val, int *val2)
449 {
450 	struct opt4060_chip *chip = iio_priv(indio_dev);
451 
452 	switch (chan->scan_index) {
453 	case OPT4060_RED:
454 		/* 2.4 */
455 		*val = 2;
456 		*val2 = 400000;
457 		break;
458 	case OPT4060_GREEN:
459 		/* 1.0 */
460 		*val = 1;
461 		*val2 = 0;
462 		break;
463 	case OPT4060_BLUE:
464 		/* 1.3 */
465 		*val = 1;
466 		*val2 = 300000;
467 		break;
468 	default:
469 		dev_err(chip->dev, "Unexpected channel index.\n");
470 		return -EINVAL;
471 	}
472 	return IIO_VAL_INT_PLUS_MICRO;
473 }
474 
opt4060_calc_illuminance(struct opt4060_chip * chip,int * val)475 static int opt4060_calc_illuminance(struct opt4060_chip *chip, int *val)
476 {
477 	u32 lux_raw;
478 	int ret;
479 
480 	/* The green wide spectral channel is used for illuminance. */
481 	ret = opt4060_read_raw_value(chip, OPT4060_GREEN_MSB, &lux_raw);
482 	if (ret) {
483 		dev_err(chip->dev, "Reading raw channel data failed\n");
484 		return ret;
485 	}
486 
487 	/* Illuminance is calculated by ADC_RAW * 2.15e-3. */
488 	*val = DIV_U64_ROUND_CLOSEST((u64)(lux_raw * 215), 1000);
489 	return ret;
490 }
491 
opt4060_read_illuminance(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val)492 static int opt4060_read_illuminance(struct iio_dev *indio_dev,
493 				    struct iio_chan_spec const *chan,
494 				    int *val)
495 {
496 	struct opt4060_chip *chip = iio_priv(indio_dev);
497 	int ret;
498 
499 	ret = opt4060_trigger_new_samples(indio_dev);
500 	if (ret) {
501 		dev_err(chip->dev, "Failed to trigger new samples.\n");
502 		return ret;
503 	}
504 	ret = opt4060_calc_illuminance(chip, val);
505 	if (ret) {
506 		dev_err(chip->dev, "Failed to calculate illuminance.\n");
507 		return ret;
508 	}
509 
510 	return IIO_VAL_INT;
511 }
512 
opt4060_set_int_time(struct opt4060_chip * chip)513 static int opt4060_set_int_time(struct opt4060_chip *chip)
514 {
515 	unsigned int regval;
516 	int ret;
517 
518 	regval = FIELD_PREP(OPT4060_CTRL_CONV_TIME_MASK, chip->int_time);
519 	ret = regmap_update_bits(chip->regmap, OPT4060_CTRL,
520 				 OPT4060_CTRL_CONV_TIME_MASK, regval);
521 	if (ret)
522 		dev_err(chip->dev, "Failed to set integration time.\n");
523 
524 	return ret;
525 }
526 
opt4060_power_down(struct opt4060_chip * chip)527 static int opt4060_power_down(struct opt4060_chip *chip)
528 {
529 	int ret;
530 
531 	ret = regmap_clear_bits(chip->regmap, OPT4060_CTRL, OPT4060_CTRL_OPER_MODE_MASK);
532 	if (ret)
533 		dev_err(chip->dev, "Failed to power down\n");
534 
535 	return ret;
536 }
537 
opt4060_chip_off_action(void * chip)538 static void opt4060_chip_off_action(void *chip)
539 {
540 	opt4060_power_down(chip);
541 }
542 
543 #define _OPT4060_COLOR_CHANNEL(_color, _mask, _ev_spec, _num_ev_spec)		\
544 {										\
545 	.type = IIO_INTENSITY,							\
546 	.modified = 1,								\
547 	.channel2 = IIO_MOD_LIGHT_##_color,					\
548 	.info_mask_separate = _mask,						\
549 	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_INT_TIME),			\
550 	.info_mask_shared_by_all_available = BIT(IIO_CHAN_INFO_INT_TIME),	\
551 	.address = OPT4060_##_color##_MSB,					\
552 	.scan_index = OPT4060_##_color,						\
553 	.scan_type = {								\
554 		.sign = 'u',							\
555 		.realbits = 32,							\
556 		.storagebits = 32,						\
557 		.endianness = IIO_CPU,						\
558 	},									\
559 	.event_spec = _ev_spec,							\
560 	.num_event_specs = _num_ev_spec,					\
561 }
562 
563 #define OPT4060_COLOR_CHANNEL(_color, _mask)					\
564 	_OPT4060_COLOR_CHANNEL(_color, _mask, opt4060_event_spec,		\
565 			       ARRAY_SIZE(opt4060_event_spec))			\
566 
567 #define OPT4060_COLOR_CHANNEL_NO_EVENTS(_color, _mask)				\
568 	_OPT4060_COLOR_CHANNEL(_color, _mask, NULL, 0)				\
569 
570 #define OPT4060_LIGHT_CHANNEL(_channel)						\
571 {										\
572 	.type = IIO_LIGHT,							\
573 	.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),			\
574 	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_INT_TIME),			\
575 	.info_mask_shared_by_all_available = BIT(IIO_CHAN_INFO_INT_TIME),	\
576 	.scan_index = OPT4060_##_channel,					\
577 	.scan_type = {								\
578 		.sign = 'u',							\
579 		.realbits = 32,							\
580 		.storagebits = 32,						\
581 		.endianness = IIO_CPU,						\
582 	},									\
583 }
584 
585 static const struct iio_event_spec opt4060_event_spec[] = {
586 	{
587 		.type = IIO_EV_TYPE_THRESH,
588 		.dir = IIO_EV_DIR_RISING,
589 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
590 				 BIT(IIO_EV_INFO_ENABLE),
591 	}, {
592 		.type = IIO_EV_TYPE_THRESH,
593 		.dir = IIO_EV_DIR_FALLING,
594 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
595 				 BIT(IIO_EV_INFO_ENABLE),
596 	}, {
597 		.type = IIO_EV_TYPE_THRESH,
598 		.dir = IIO_EV_DIR_EITHER,
599 		.mask_separate = BIT(IIO_EV_INFO_PERIOD),
600 	},
601 };
602 
603 static const struct iio_chan_spec opt4060_channels[] = {
604 	OPT4060_COLOR_CHANNEL(RED, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
605 	OPT4060_COLOR_CHANNEL(GREEN, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
606 	OPT4060_COLOR_CHANNEL(BLUE, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
607 	OPT4060_COLOR_CHANNEL(CLEAR, BIT(IIO_CHAN_INFO_RAW)),
608 	OPT4060_LIGHT_CHANNEL(ILLUM),
609 	IIO_CHAN_SOFT_TIMESTAMP(OPT4060_NUM_CHANS),
610 };
611 
612 static const struct iio_chan_spec opt4060_channels_no_events[] = {
613 	OPT4060_COLOR_CHANNEL_NO_EVENTS(RED, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
614 	OPT4060_COLOR_CHANNEL_NO_EVENTS(GREEN, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
615 	OPT4060_COLOR_CHANNEL_NO_EVENTS(BLUE, BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE)),
616 	OPT4060_COLOR_CHANNEL_NO_EVENTS(CLEAR, BIT(IIO_CHAN_INFO_RAW)),
617 	OPT4060_LIGHT_CHANNEL(ILLUM),
618 	IIO_CHAN_SOFT_TIMESTAMP(OPT4060_NUM_CHANS),
619 };
620 
opt4060_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)621 static int opt4060_read_raw(struct iio_dev *indio_dev,
622 			    struct iio_chan_spec const *chan,
623 			    int *val, int *val2, long mask)
624 {
625 	struct opt4060_chip *chip = iio_priv(indio_dev);
626 
627 	switch (mask) {
628 	case IIO_CHAN_INFO_RAW:
629 		return opt4060_read_chan_raw(indio_dev, chan, val);
630 	case IIO_CHAN_INFO_SCALE:
631 		return opt4060_get_chan_scale(indio_dev, chan, val, val2);
632 	case IIO_CHAN_INFO_PROCESSED:
633 		return opt4060_read_illuminance(indio_dev, chan, val);
634 	case IIO_CHAN_INFO_INT_TIME:
635 		*val = 0;
636 		*val2 = opt4060_int_time_reg[chip->int_time][0];
637 		return IIO_VAL_INT_PLUS_MICRO;
638 	default:
639 		return -EINVAL;
640 	}
641 }
642 
opt4060_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)643 static int opt4060_write_raw(struct iio_dev *indio_dev,
644 			     struct iio_chan_spec const *chan,
645 			     int val, int val2, long mask)
646 {
647 	struct opt4060_chip *chip = iio_priv(indio_dev);
648 	int int_time;
649 
650 	switch (mask) {
651 	case IIO_CHAN_INFO_INT_TIME:
652 		int_time = opt4060_als_time_to_index(val2);
653 		if (int_time < 0)
654 			return int_time;
655 		chip->int_time = int_time;
656 		return opt4060_set_int_time(chip);
657 	default:
658 		return -EINVAL;
659 	}
660 }
661 
opt4060_write_raw_get_fmt(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,long mask)662 static int opt4060_write_raw_get_fmt(struct iio_dev *indio_dev,
663 				     struct iio_chan_spec const *chan,
664 				     long mask)
665 {
666 	switch (mask) {
667 	case IIO_CHAN_INFO_INT_TIME:
668 		return IIO_VAL_INT_PLUS_MICRO;
669 	default:
670 		return -EINVAL;
671 	}
672 }
673 
opt4060_calc_th_reg(u32 adc_val)674 static u32 opt4060_calc_th_reg(u32 adc_val)
675 {
676 	u32 th_val, th_exp, bits;
677 	/*
678 	 * The threshold registers take 4 bits of exponent and 12 bits of data
679 	 * ADC = TH_VAL << (8 + TH_EXP)
680 	 */
681 	bits = fls(adc_val);
682 
683 	if (bits > 31)
684 		th_exp = 11; /* Maximum exponent */
685 	else if (bits > 20)
686 		th_exp = bits - 20;
687 	else
688 		th_exp = 0;
689 	th_val = (adc_val >> (8 + th_exp)) & 0xfff;
690 
691 	return (th_exp << 12) + th_val;
692 }
693 
opt4060_calc_val_from_th_reg(u32 th_reg)694 static u32 opt4060_calc_val_from_th_reg(u32 th_reg)
695 {
696 	/*
697 	 * The threshold registers take 4 bits of exponent and 12 bits of data
698 	 * ADC = TH_VAL << (8 + TH_EXP)
699 	 */
700 	u32 th_val, th_exp;
701 
702 	th_exp = (th_reg >> 12) & 0xf;
703 	th_val = th_reg & 0xfff;
704 
705 	return th_val << (8 + th_exp);
706 }
707 
opt4060_read_available(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long mask)708 static int opt4060_read_available(struct iio_dev *indio_dev,
709 				  struct iio_chan_spec const *chan,
710 				  const int **vals, int *type, int *length,
711 				  long mask)
712 {
713 	switch (mask) {
714 	case IIO_CHAN_INFO_INT_TIME:
715 		*length = ARRAY_SIZE(opt4060_int_time_available) * 2;
716 		*vals = (const int *)opt4060_int_time_available;
717 		*type = IIO_VAL_INT_PLUS_MICRO;
718 		return IIO_AVAIL_LIST;
719 
720 	default:
721 		return -EINVAL;
722 	}
723 }
724 
opt4060_read_ev_period(struct opt4060_chip * chip,int * val,int * val2)725 static ssize_t opt4060_read_ev_period(struct opt4060_chip *chip, int *val,
726 				      int *val2)
727 {
728 	int ret, pers, fault_count, int_time;
729 	u64 uval;
730 
731 	int_time = opt4060_int_time_reg[chip->int_time][0];
732 
733 	ret = regmap_read(chip->regmap, OPT4060_CTRL, &fault_count);
734 	if (ret < 0)
735 		return ret;
736 
737 	fault_count = fault_count & OPT4060_CTRL_FAULT_COUNT_MASK;
738 	switch (fault_count) {
739 	case OPT4060_CTRL_FAULT_COUNT_2:
740 		pers = 2;
741 		break;
742 	case OPT4060_CTRL_FAULT_COUNT_4:
743 		pers = 4;
744 		break;
745 	case OPT4060_CTRL_FAULT_COUNT_8:
746 		pers = 8;
747 		break;
748 
749 	default:
750 		pers = 1;
751 		break;
752 	}
753 
754 	uval = mul_u32_u32(int_time, pers);
755 	*val = div_u64_rem(uval, MICRO, val2);
756 
757 	return IIO_VAL_INT_PLUS_MICRO;
758 }
759 
opt4060_write_ev_period(struct opt4060_chip * chip,int val,int val2)760 static ssize_t opt4060_write_ev_period(struct opt4060_chip *chip, int val,
761 				       int val2)
762 {
763 	u64 uval, int_time;
764 	unsigned int regval, fault_count_val;
765 
766 	uval = mul_u32_u32(val, MICRO) + val2;
767 	int_time = opt4060_int_time_reg[chip->int_time][0];
768 
769 	/* Check if the period is closest to 1, 2, 4 or 8 times integration time.*/
770 	if (uval <= int_time)
771 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_1;
772 	else if (uval <= int_time * 2)
773 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_2;
774 	else if (uval <= int_time * 4)
775 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_4;
776 	else
777 		fault_count_val = OPT4060_CTRL_FAULT_COUNT_8;
778 
779 	regval = FIELD_PREP(OPT4060_CTRL_FAULT_COUNT_MASK, fault_count_val);
780 	return regmap_update_bits(chip->regmap, OPT4060_CTRL,
781 				 OPT4060_CTRL_FAULT_COUNT_MASK, regval);
782 }
783 
opt4060_get_channel_sel(struct opt4060_chip * chip,int * ch_sel)784 static int opt4060_get_channel_sel(struct opt4060_chip *chip, int *ch_sel)
785 {
786 	int ret;
787 	u32 regval;
788 
789 	ret = regmap_read(chip->regmap, OPT4060_INT_CTRL, &regval);
790 	if (ret) {
791 		dev_err(chip->dev, "Failed to get channel selection.\n");
792 		return ret;
793 	}
794 	*ch_sel = FIELD_GET(OPT4060_INT_CTRL_THRESH_SEL, regval);
795 	return ret;
796 }
797 
opt4060_set_channel_sel(struct opt4060_chip * chip,int ch_sel)798 static int opt4060_set_channel_sel(struct opt4060_chip *chip, int ch_sel)
799 {
800 	int ret;
801 	u32 regval;
802 
803 	regval = FIELD_PREP(OPT4060_INT_CTRL_THRESH_SEL, ch_sel);
804 	ret = regmap_update_bits(chip->regmap, OPT4060_INT_CTRL,
805 				 OPT4060_INT_CTRL_THRESH_SEL, regval);
806 	if (ret)
807 		dev_err(chip->dev, "Failed to set channel selection.\n");
808 	return ret;
809 }
810 
opt4060_get_thresholds(struct opt4060_chip * chip,u32 * th_lo,u32 * th_hi)811 static int opt4060_get_thresholds(struct opt4060_chip *chip, u32 *th_lo, u32 *th_hi)
812 {
813 	int ret;
814 	u32 regval;
815 
816 	ret = regmap_read(chip->regmap, OPT4060_THRESHOLD_LOW, &regval);
817 	if (ret) {
818 		dev_err(chip->dev, "Failed to read THRESHOLD_LOW.\n");
819 		return ret;
820 	}
821 	*th_lo = opt4060_calc_val_from_th_reg(regval);
822 
823 	ret = regmap_read(chip->regmap, OPT4060_THRESHOLD_HIGH, &regval);
824 	if (ret) {
825 		dev_err(chip->dev, "Failed to read THRESHOLD_LOW.\n");
826 		return ret;
827 	}
828 	*th_hi = opt4060_calc_val_from_th_reg(regval);
829 
830 	return ret;
831 }
832 
opt4060_set_thresholds(struct opt4060_chip * chip,u32 th_lo,u32 th_hi)833 static int opt4060_set_thresholds(struct opt4060_chip *chip, u32 th_lo, u32 th_hi)
834 {
835 	int ret;
836 
837 	ret = regmap_write(chip->regmap, OPT4060_THRESHOLD_LOW, opt4060_calc_th_reg(th_lo));
838 	if (ret) {
839 		dev_err(chip->dev, "Failed to write THRESHOLD_LOW.\n");
840 		return ret;
841 	}
842 
843 	ret = regmap_write(chip->regmap, OPT4060_THRESHOLD_HIGH, opt4060_calc_th_reg(th_hi));
844 	if (ret)
845 		dev_err(chip->dev, "Failed to write THRESHOLD_HIGH.\n");
846 
847 	return ret;
848 }
849 
opt4060_read_event(struct iio_dev * indio_dev,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)850 static int opt4060_read_event(struct iio_dev *indio_dev,
851 			      const struct iio_chan_spec *chan,
852 			      enum iio_event_type type,
853 			      enum iio_event_direction dir,
854 			      enum iio_event_info info,
855 			      int *val, int *val2)
856 {
857 	struct opt4060_chip *chip = iio_priv(indio_dev);
858 	u32 th_lo, th_hi;
859 	int ret;
860 
861 	if (chan->type != IIO_INTENSITY)
862 		return -EINVAL;
863 	if (type != IIO_EV_TYPE_THRESH)
864 		return -EINVAL;
865 
866 	switch (info) {
867 	case IIO_EV_INFO_VALUE:
868 		ret = opt4060_get_thresholds(chip, &th_lo, &th_hi);
869 		if (ret)
870 			return ret;
871 		if (dir == IIO_EV_DIR_FALLING) {
872 			*val = th_lo;
873 			ret = IIO_VAL_INT;
874 		} else if (dir == IIO_EV_DIR_RISING) {
875 			*val = th_hi;
876 			ret = IIO_VAL_INT;
877 		}
878 		return ret;
879 	case IIO_EV_INFO_PERIOD:
880 		return opt4060_read_ev_period(chip, val, val2);
881 	default:
882 		return -EINVAL;
883 	}
884 }
885 
opt4060_write_event(struct iio_dev * indio_dev,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)886 static int opt4060_write_event(struct iio_dev *indio_dev,
887 			       const struct iio_chan_spec *chan,
888 			       enum iio_event_type type,
889 			       enum iio_event_direction dir,
890 			       enum iio_event_info info,
891 			       int val, int val2)
892 {
893 	struct opt4060_chip *chip = iio_priv(indio_dev);
894 	u32 th_lo, th_hi;
895 	int ret;
896 
897 	if (chan->type != IIO_INTENSITY)
898 		return -EINVAL;
899 	if (type != IIO_EV_TYPE_THRESH)
900 		return -EINVAL;
901 
902 	switch (info) {
903 	case IIO_EV_INFO_VALUE:
904 		ret = opt4060_get_thresholds(chip, &th_lo, &th_hi);
905 		if (ret)
906 			return ret;
907 		if (dir == IIO_EV_DIR_FALLING)
908 			th_lo = val;
909 		else if (dir == IIO_EV_DIR_RISING)
910 			th_hi = val;
911 		return opt4060_set_thresholds(chip, th_lo, th_hi);
912 	case IIO_EV_INFO_PERIOD:
913 		return opt4060_write_ev_period(chip, val, val2);
914 	default:
915 		return -EINVAL;
916 	}
917 }
918 
opt4060_read_event_config(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir)919 static int opt4060_read_event_config(struct iio_dev *indio_dev,
920 				     const struct iio_chan_spec *chan,
921 				     enum iio_event_type type,
922 				     enum iio_event_direction dir)
923 {
924 	int ch_sel, ch_idx = chan->scan_index;
925 	struct opt4060_chip *chip = iio_priv(indio_dev);
926 	int ret;
927 
928 	if (chan->type != IIO_INTENSITY)
929 		return -EINVAL;
930 	if (type != IIO_EV_TYPE_THRESH)
931 		return -EINVAL;
932 
933 	ret = opt4060_get_channel_sel(chip, &ch_sel);
934 	if (ret)
935 		return ret;
936 
937 	if (((dir == IIO_EV_DIR_FALLING) && chip->thresh_event_lo_active) ||
938 	    ((dir == IIO_EV_DIR_RISING) && chip->thresh_event_hi_active))
939 		return ch_sel == ch_idx;
940 
941 	return ret;
942 }
943 
opt4060_write_event_config(struct iio_dev * indio_dev,const struct iio_chan_spec * chan,enum iio_event_type type,enum iio_event_direction dir,bool state)944 static int opt4060_write_event_config(struct iio_dev *indio_dev,
945 				      const struct iio_chan_spec *chan,
946 				      enum iio_event_type type,
947 				      enum iio_event_direction dir, bool state)
948 {
949 	int ch_sel, ch_idx = chan->scan_index;
950 	struct opt4060_chip *chip = iio_priv(indio_dev);
951 	int ret;
952 
953 	guard(mutex)(&chip->event_enabling_lock);
954 
955 	if (chan->type != IIO_INTENSITY)
956 		return -EINVAL;
957 	if (type != IIO_EV_TYPE_THRESH)
958 		return -EINVAL;
959 
960 	ret = opt4060_get_channel_sel(chip, &ch_sel);
961 	if (ret)
962 		return ret;
963 
964 	if (state) {
965 		/* Only one channel can be active at the same time */
966 		if ((chip->thresh_event_lo_active || chip->thresh_event_hi_active) &&
967 		    (ch_idx != ch_sel))
968 			return -EBUSY;
969 		if (dir == IIO_EV_DIR_FALLING)
970 			chip->thresh_event_lo_active = true;
971 		else if (dir == IIO_EV_DIR_RISING)
972 			chip->thresh_event_hi_active = true;
973 		ret = opt4060_set_channel_sel(chip, ch_idx);
974 		if (ret)
975 			return ret;
976 	} else {
977 		if (ch_idx == ch_sel) {
978 			if (dir == IIO_EV_DIR_FALLING)
979 				chip->thresh_event_lo_active = false;
980 			else if (dir == IIO_EV_DIR_RISING)
981 				chip->thresh_event_hi_active = false;
982 		}
983 	}
984 
985 	return opt4060_set_driver_state(indio_dev,
986 					chip->thresh_event_hi_active |
987 					chip->thresh_event_lo_active,
988 					false);
989 }
990 
991 static const struct iio_info opt4060_info = {
992 	.read_raw = opt4060_read_raw,
993 	.write_raw = opt4060_write_raw,
994 	.write_raw_get_fmt = opt4060_write_raw_get_fmt,
995 	.read_avail = opt4060_read_available,
996 	.read_event_value = opt4060_read_event,
997 	.write_event_value = opt4060_write_event,
998 	.read_event_config = opt4060_read_event_config,
999 	.write_event_config = opt4060_write_event_config,
1000 };
1001 
1002 static const struct iio_info opt4060_info_no_irq = {
1003 	.read_raw = opt4060_read_raw,
1004 	.write_raw = opt4060_write_raw,
1005 	.write_raw_get_fmt = opt4060_write_raw_get_fmt,
1006 	.read_avail = opt4060_read_available,
1007 };
1008 
opt4060_load_defaults(struct opt4060_chip * chip)1009 static int opt4060_load_defaults(struct opt4060_chip *chip)
1010 {
1011 	u16 reg;
1012 	int ret;
1013 
1014 	chip->int_time = OPT4060_DEFAULT_CONVERSION_TIME;
1015 
1016 	/* Set initial MIN/MAX thresholds */
1017 	ret = opt4060_set_thresholds(chip, 0, UINT_MAX);
1018 	if (ret)
1019 		return ret;
1020 
1021 	/*
1022 	 * Setting auto-range, latched window for thresholds, one-shot conversion
1023 	 * and quick wake-up mode as default.
1024 	 */
1025 	reg = FIELD_PREP(OPT4060_CTRL_RANGE_MASK,
1026 			 OPT4060_CTRL_LIGHT_SCALE_AUTO);
1027 	reg |= FIELD_PREP(OPT4060_CTRL_CONV_TIME_MASK, chip->int_time);
1028 	reg |= FIELD_PREP(OPT4060_CTRL_OPER_MODE_MASK,
1029 				OPT4060_CTRL_OPER_MODE_ONE_SHOT);
1030 	reg |= OPT4060_CTRL_QWAKE_MASK | OPT4060_CTRL_LATCH_MASK;
1031 
1032 	ret = regmap_write(chip->regmap, OPT4060_CTRL, reg);
1033 	if (ret)
1034 		dev_err(chip->dev, "Failed to set configuration\n");
1035 
1036 	return ret;
1037 }
1038 
opt4060_volatile_reg(struct device * dev,unsigned int reg)1039 static bool opt4060_volatile_reg(struct device *dev, unsigned int reg)
1040 {
1041 	return reg <= OPT4060_CLEAR_LSB || reg == OPT4060_RES_CTRL;
1042 }
1043 
opt4060_writable_reg(struct device * dev,unsigned int reg)1044 static bool opt4060_writable_reg(struct device *dev, unsigned int reg)
1045 {
1046 	return reg >= OPT4060_THRESHOLD_LOW || reg >= OPT4060_INT_CTRL;
1047 }
1048 
opt4060_readonly_reg(struct device * dev,unsigned int reg)1049 static bool opt4060_readonly_reg(struct device *dev, unsigned int reg)
1050 {
1051 	return reg == OPT4060_DEVICE_ID;
1052 }
1053 
opt4060_readable_reg(struct device * dev,unsigned int reg)1054 static bool opt4060_readable_reg(struct device *dev, unsigned int reg)
1055 {
1056 	/* Volatile, writable and read-only registers are readable. */
1057 	return opt4060_volatile_reg(dev, reg) || opt4060_writable_reg(dev, reg) ||
1058 	       opt4060_readonly_reg(dev, reg);
1059 }
1060 
1061 static const struct regmap_config opt4060_regmap_config = {
1062 	.name = "opt4060",
1063 	.reg_bits = 8,
1064 	.val_bits = 16,
1065 	.cache_type = REGCACHE_RBTREE,
1066 	.max_register = OPT4060_DEVICE_ID,
1067 	.readable_reg = opt4060_readable_reg,
1068 	.writeable_reg = opt4060_writable_reg,
1069 	.volatile_reg = opt4060_volatile_reg,
1070 	.val_format_endian = REGMAP_ENDIAN_BIG,
1071 };
1072 
1073 static const struct iio_trigger_ops opt4060_trigger_ops = {
1074 	.set_trigger_state = opt4060_trigger_set_state,
1075 };
1076 
opt4060_trigger_handler(int irq,void * p)1077 static irqreturn_t opt4060_trigger_handler(int irq, void *p)
1078 {
1079 	struct iio_poll_func *pf = p;
1080 	struct iio_dev *idev = pf->indio_dev;
1081 	struct opt4060_chip *chip = iio_priv(idev);
1082 	struct  {
1083 		u32 chan[OPT4060_NUM_CHANS];
1084 		aligned_s64 ts;
1085 	} raw;
1086 	int i = 0;
1087 	int chan, ret;
1088 
1089 	/* If the trigger is not from this driver, a new sample is needed.*/
1090 	if (iio_trigger_validate_own_device(idev->trig, idev))
1091 		opt4060_trigger_new_samples(idev);
1092 
1093 	memset(&raw, 0, sizeof(raw));
1094 
1095 	iio_for_each_active_channel(idev, chan) {
1096 		if (chan == OPT4060_ILLUM)
1097 			ret = opt4060_calc_illuminance(chip, &raw.chan[i++]);
1098 		else
1099 			ret = opt4060_read_raw_value(chip,
1100 						     idev->channels[chan].address,
1101 						     &raw.chan[i++]);
1102 		if (ret) {
1103 			dev_err(chip->dev, "Reading channel data failed\n");
1104 			goto err_read;
1105 		}
1106 	}
1107 
1108 	iio_push_to_buffers_with_timestamp(idev, &raw, pf->timestamp);
1109 err_read:
1110 	iio_trigger_notify_done(idev->trig);
1111 	return IRQ_HANDLED;
1112 }
1113 
opt4060_irq_thread(int irq,void * private)1114 static irqreturn_t opt4060_irq_thread(int irq, void *private)
1115 {
1116 	struct iio_dev *idev = private;
1117 	struct opt4060_chip *chip = iio_priv(idev);
1118 	int ret, dummy;
1119 	unsigned int int_res;
1120 
1121 	ret = regmap_read(chip->regmap, OPT4060_RES_CTRL, &int_res);
1122 	if (ret < 0) {
1123 		dev_err(chip->dev, "Failed to read interrupt reasons.\n");
1124 		return IRQ_NONE;
1125 	}
1126 
1127 	/* Read OPT4060_CTRL to clear interrupt */
1128 	ret = regmap_read(chip->regmap, OPT4060_CTRL, &dummy);
1129 	if (ret < 0) {
1130 		dev_err(chip->dev, "Failed to clear interrupt\n");
1131 		return IRQ_NONE;
1132 	}
1133 
1134 	/* Handle events */
1135 	if (int_res & (OPT4060_RES_CTRL_FLAG_H | OPT4060_RES_CTRL_FLAG_L)) {
1136 		u64 code;
1137 		int chan = 0;
1138 
1139 		ret = opt4060_get_channel_sel(chip, &chan);
1140 		if (ret) {
1141 			dev_err(chip->dev, "Failed to read threshold channel.\n");
1142 			return IRQ_NONE;
1143 		}
1144 
1145 		/* Check if the interrupt is from the lower threshold */
1146 		if (int_res & OPT4060_RES_CTRL_FLAG_L) {
1147 			code = IIO_MOD_EVENT_CODE(IIO_INTENSITY,
1148 						  chan,
1149 						  idev->channels[chan].channel2,
1150 						  IIO_EV_TYPE_THRESH,
1151 						  IIO_EV_DIR_FALLING);
1152 			iio_push_event(idev, code, iio_get_time_ns(idev));
1153 		}
1154 		/* Check if the interrupt is from the upper threshold */
1155 		if (int_res & OPT4060_RES_CTRL_FLAG_H) {
1156 			code = IIO_MOD_EVENT_CODE(IIO_INTENSITY,
1157 						  chan,
1158 						  idev->channels[chan].channel2,
1159 						  IIO_EV_TYPE_THRESH,
1160 						  IIO_EV_DIR_RISING);
1161 			iio_push_event(idev, code, iio_get_time_ns(idev));
1162 		}
1163 	}
1164 
1165 	/* Handle conversion ready */
1166 	if (int_res & OPT4060_RES_CTRL_CONV_READY) {
1167 		/* Signal completion for potentially waiting reads */
1168 		complete(&chip->completion);
1169 
1170 		/* Handle data ready triggers */
1171 		if (iio_buffer_enabled(idev))
1172 			iio_trigger_poll_nested(chip->trig);
1173 	}
1174 	return IRQ_HANDLED;
1175 }
1176 
opt4060_setup_buffer(struct opt4060_chip * chip,struct iio_dev * idev)1177 static int opt4060_setup_buffer(struct opt4060_chip *chip, struct iio_dev *idev)
1178 {
1179 	int ret;
1180 
1181 	ret = devm_iio_triggered_buffer_setup(chip->dev, idev,
1182 					      &iio_pollfunc_store_time,
1183 					      opt4060_trigger_handler, NULL);
1184 	if (ret)
1185 		return dev_err_probe(chip->dev, ret,
1186 				     "Buffer setup failed.\n");
1187 	return ret;
1188 }
1189 
opt4060_setup_trigger(struct opt4060_chip * chip,struct iio_dev * idev)1190 static int opt4060_setup_trigger(struct opt4060_chip *chip, struct iio_dev *idev)
1191 {
1192 	struct iio_trigger *data_trigger;
1193 	char *name;
1194 	int ret;
1195 
1196 	data_trigger = devm_iio_trigger_alloc(chip->dev, "%s-data-ready-dev%d",
1197 					      idev->name, iio_device_id(idev));
1198 	if (!data_trigger)
1199 		return -ENOMEM;
1200 
1201 	/*
1202 	 * The data trigger allows for sample capture on each new conversion
1203 	 * ready interrupt.
1204 	 */
1205 	chip->trig = data_trigger;
1206 	data_trigger->ops = &opt4060_trigger_ops;
1207 	iio_trigger_set_drvdata(data_trigger, idev);
1208 	ret = devm_iio_trigger_register(chip->dev, data_trigger);
1209 	if (ret)
1210 		return dev_err_probe(chip->dev, ret,
1211 				     "Data ready trigger registration failed\n");
1212 
1213 	name = devm_kasprintf(chip->dev, GFP_KERNEL, "%s-opt4060",
1214 			      dev_name(chip->dev));
1215 	if (!name)
1216 		return dev_err_probe(chip->dev, -ENOMEM, "Failed to alloc chip name\n");
1217 
1218 	ret = devm_request_threaded_irq(chip->dev, chip->irq, NULL, opt4060_irq_thread,
1219 					IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
1220 					name, idev);
1221 	if (ret)
1222 		return dev_err_probe(chip->dev, ret, "Could not request IRQ\n");
1223 
1224 	init_completion(&chip->completion);
1225 
1226 	ret = devm_mutex_init(chip->dev, &chip->irq_setting_lock);
1227 	if (ret)
1228 		return ret;
1229 
1230 	ret = devm_mutex_init(chip->dev, &chip->event_enabling_lock);
1231 	if (ret)
1232 		return ret;
1233 
1234 	ret = regmap_write_bits(chip->regmap, OPT4060_INT_CTRL,
1235 				OPT4060_INT_CTRL_OUTPUT,
1236 				OPT4060_INT_CTRL_OUTPUT);
1237 	if (ret)
1238 		return dev_err_probe(chip->dev, ret,
1239 				     "Failed to set interrupt as output\n");
1240 
1241 	return 0;
1242 }
1243 
opt4060_probe(struct i2c_client * client)1244 static int opt4060_probe(struct i2c_client *client)
1245 {
1246 	struct device *dev = &client->dev;
1247 	struct opt4060_chip *chip;
1248 	struct iio_dev *indio_dev;
1249 	int ret;
1250 	unsigned int regval, dev_id;
1251 
1252 	indio_dev = devm_iio_device_alloc(dev, sizeof(*chip));
1253 	if (!indio_dev)
1254 		return -ENOMEM;
1255 
1256 	chip = iio_priv(indio_dev);
1257 
1258 	ret = devm_regulator_get_enable(dev, "vdd");
1259 	if (ret)
1260 		return dev_err_probe(dev, ret, "Failed to enable vdd supply\n");
1261 
1262 	chip->regmap = devm_regmap_init_i2c(client, &opt4060_regmap_config);
1263 	if (IS_ERR(chip->regmap))
1264 		return dev_err_probe(dev, PTR_ERR(chip->regmap),
1265 				     "regmap initialization failed\n");
1266 
1267 	chip->dev = dev;
1268 	chip->irq = client->irq;
1269 
1270 	ret = regmap_reinit_cache(chip->regmap, &opt4060_regmap_config);
1271 	if (ret)
1272 		return dev_err_probe(dev, ret,
1273 				     "failed to reinit regmap cache\n");
1274 
1275 	ret = regmap_read(chip->regmap, OPT4060_DEVICE_ID, &regval);
1276 	if (ret < 0)
1277 		return dev_err_probe(dev, ret,
1278 			"Failed to read the device ID register\n");
1279 
1280 	dev_id = FIELD_GET(OPT4060_DEVICE_ID_MASK, regval);
1281 	if (dev_id != OPT4060_DEVICE_ID_VAL)
1282 		dev_info(dev, "Device ID: %#04x unknown\n", dev_id);
1283 
1284 	if (chip->irq) {
1285 		indio_dev->info = &opt4060_info;
1286 		indio_dev->channels = opt4060_channels;
1287 		indio_dev->num_channels = ARRAY_SIZE(opt4060_channels);
1288 	} else {
1289 		indio_dev->info = &opt4060_info_no_irq;
1290 		indio_dev->channels = opt4060_channels_no_events;
1291 		indio_dev->num_channels = ARRAY_SIZE(opt4060_channels_no_events);
1292 	}
1293 	indio_dev->modes = INDIO_DIRECT_MODE;
1294 	indio_dev->name = "opt4060";
1295 
1296 	ret = opt4060_load_defaults(chip);
1297 	if (ret < 0)
1298 		return dev_err_probe(dev, ret,
1299 				     "Failed to set sensor defaults\n");
1300 
1301 	ret = devm_add_action_or_reset(dev, opt4060_chip_off_action, chip);
1302 	if (ret < 0)
1303 		return dev_err_probe(dev, ret,
1304 				     "Failed to setup power off action\n");
1305 
1306 	ret = opt4060_setup_buffer(chip, indio_dev);
1307 	if (ret)
1308 		return ret;
1309 
1310 	if (chip->irq) {
1311 		ret = opt4060_setup_trigger(chip, indio_dev);
1312 		if (ret)
1313 			return ret;
1314 	}
1315 
1316 	return devm_iio_device_register(dev, indio_dev);
1317 }
1318 
1319 static const struct i2c_device_id opt4060_id[] = {
1320 	{ "opt4060", },
1321 	{ }
1322 };
1323 MODULE_DEVICE_TABLE(i2c, opt4060_id);
1324 
1325 static const struct of_device_id opt4060_of_match[] = {
1326 	{ .compatible = "ti,opt4060" },
1327 	{ }
1328 };
1329 MODULE_DEVICE_TABLE(of, opt4060_of_match);
1330 
1331 static struct i2c_driver opt4060_driver = {
1332 	.driver = {
1333 		.name = "opt4060",
1334 		.of_match_table = opt4060_of_match,
1335 	},
1336 	.probe = opt4060_probe,
1337 	.id_table = opt4060_id,
1338 };
1339 module_i2c_driver(opt4060_driver);
1340 
1341 MODULE_AUTHOR("Per-Daniel Olsson <[email protected]>");
1342 MODULE_DESCRIPTION("Texas Instruments OPT4060 RGBW color sensor driver");
1343 MODULE_LICENSE("GPL");
1344