xref: /openbmc/linux/drivers/iio/light/rohm-bu27008.c (revision 1b36955c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * BU27008 ROHM Colour Sensor
4  *
5  * Copyright (c) 2023, ROHM Semiconductor.
6  */
7 
8 #include <linux/bitfield.h>
9 #include <linux/bitops.h>
10 #include <linux/device.h>
11 #include <linux/i2c.h>
12 #include <linux/interrupt.h>
13 #include <linux/module.h>
14 #include <linux/property.h>
15 #include <linux/regmap.h>
16 #include <linux/regulator/consumer.h>
17 #include <linux/units.h>
18 
19 #include <linux/iio/iio.h>
20 #include <linux/iio/iio-gts-helper.h>
21 #include <linux/iio/trigger.h>
22 #include <linux/iio/trigger_consumer.h>
23 #include <linux/iio/triggered_buffer.h>
24 
25 #define BU27008_REG_SYSTEM_CONTROL	0x40
26 #define BU27008_MASK_SW_RESET		BIT(7)
27 #define BU27008_MASK_PART_ID		GENMASK(5, 0)
28 #define BU27008_ID			0x1a
29 #define BU27008_REG_MODE_CONTROL1	0x41
30 #define BU27008_MASK_MEAS_MODE		GENMASK(2, 0)
31 #define BU27008_MASK_CHAN_SEL		GENMASK(3, 2)
32 
33 #define BU27008_REG_MODE_CONTROL2	0x42
34 #define BU27008_MASK_RGBC_GAIN		GENMASK(7, 3)
35 #define BU27008_MASK_IR_GAIN_LO		GENMASK(2, 0)
36 #define BU27008_SHIFT_IR_GAIN		3
37 
38 #define BU27008_REG_MODE_CONTROL3	0x43
39 #define BU27008_MASK_VALID		BIT(7)
40 #define BU27008_MASK_INT_EN		BIT(1)
41 #define BU27008_INT_EN			BU27008_MASK_INT_EN
42 #define BU27008_INT_DIS			0
43 #define BU27008_MASK_MEAS_EN		BIT(0)
44 #define BU27008_MEAS_EN			BIT(0)
45 #define BU27008_MEAS_DIS		0
46 
47 #define BU27008_REG_DATA0_LO		0x50
48 #define BU27008_REG_DATA1_LO		0x52
49 #define BU27008_REG_DATA2_LO		0x54
50 #define BU27008_REG_DATA3_LO		0x56
51 #define BU27008_REG_DATA3_HI		0x57
52 #define BU27008_REG_MANUFACTURER_ID	0x92
53 #define BU27008_REG_MAX BU27008_REG_MANUFACTURER_ID
54 
55 /**
56  * enum bu27008_chan_type - BU27008 channel types
57  * @BU27008_RED:	Red channel. Always via data0.
58  * @BU27008_GREEN:	Green channel. Always via data1.
59  * @BU27008_BLUE:	Blue channel. Via data2 (when used).
60  * @BU27008_CLEAR:	Clear channel. Via data2 or data3 (when used).
61  * @BU27008_IR:		IR channel. Via data3 (when used).
62  * @BU27008_NUM_CHANS:	Number of channel types.
63  */
64 enum bu27008_chan_type {
65 	BU27008_RED,
66 	BU27008_GREEN,
67 	BU27008_BLUE,
68 	BU27008_CLEAR,
69 	BU27008_IR,
70 	BU27008_NUM_CHANS
71 };
72 
73 /**
74  * enum bu27008_chan - BU27008 physical data channel
75  * @BU27008_DATA0:		Always red.
76  * @BU27008_DATA1:		Always green.
77  * @BU27008_DATA2:		Blue or clear.
78  * @BU27008_DATA3:		IR or clear.
79  * @BU27008_NUM_HW_CHANS:	Number of physical channels
80  */
81 enum bu27008_chan {
82 	BU27008_DATA0,
83 	BU27008_DATA1,
84 	BU27008_DATA2,
85 	BU27008_DATA3,
86 	BU27008_NUM_HW_CHANS
87 };
88 
89 /* We can always measure red and green at same time */
90 #define ALWAYS_SCANNABLE (BIT(BU27008_RED) | BIT(BU27008_GREEN))
91 
92 /* We use these data channel configs. Ensure scan_masks below follow them too */
93 #define BU27008_BLUE2_CLEAR3		0x0 /* buffer is R, G, B, C */
94 #define BU27008_CLEAR2_IR3		0x1 /* buffer is R, G, C, IR */
95 #define BU27008_BLUE2_IR3		0x2 /* buffer is R, G, B, IR */
96 
97 static const unsigned long bu27008_scan_masks[] = {
98 	/* buffer is R, G, B, C */
99 	ALWAYS_SCANNABLE | BIT(BU27008_BLUE) | BIT(BU27008_CLEAR),
100 	/* buffer is R, G, C, IR */
101 	ALWAYS_SCANNABLE | BIT(BU27008_CLEAR) | BIT(BU27008_IR),
102 	/* buffer is R, G, B, IR */
103 	ALWAYS_SCANNABLE | BIT(BU27008_BLUE) | BIT(BU27008_IR),
104 	0
105 };
106 
107 /*
108  * Available scales with gain 1x - 1024x, timings 55, 100, 200, 400 mS
109  * Time impacts to gain: 1x, 2x, 4x, 8x.
110  *
111  * => Max total gain is HWGAIN * gain by integration time (8 * 1024) = 8192
112  *
113  * Max amplification is (HWGAIN * MAX integration-time multiplier) 1024 * 8
114  * = 8192. With NANO scale we get rid of accuracy loss when we start with the
115  * scale 16.0 for HWGAIN1, INT-TIME 55 mS. This way the nano scale for MAX
116  * total gain 8192 will be 1953125
117  */
118 #define BU27008_SCALE_1X 16
119 
120 /* See the data sheet for the "Gain Setting" table */
121 #define BU27008_GSEL_1X		0x00
122 #define BU27008_GSEL_4X		0x08
123 #define BU27008_GSEL_8X		0x09
124 #define BU27008_GSEL_16X	0x0a
125 #define BU27008_GSEL_32X	0x0b
126 #define BU27008_GSEL_64X	0x0c
127 #define BU27008_GSEL_256X	0x18
128 #define BU27008_GSEL_512X	0x19
129 #define BU27008_GSEL_1024X	0x1a
130 
131 static const struct iio_gain_sel_pair bu27008_gains[] = {
132 	GAIN_SCALE_GAIN(1, BU27008_GSEL_1X),
133 	GAIN_SCALE_GAIN(4, BU27008_GSEL_4X),
134 	GAIN_SCALE_GAIN(8, BU27008_GSEL_8X),
135 	GAIN_SCALE_GAIN(16, BU27008_GSEL_16X),
136 	GAIN_SCALE_GAIN(32, BU27008_GSEL_32X),
137 	GAIN_SCALE_GAIN(64, BU27008_GSEL_64X),
138 	GAIN_SCALE_GAIN(256, BU27008_GSEL_256X),
139 	GAIN_SCALE_GAIN(512, BU27008_GSEL_512X),
140 	GAIN_SCALE_GAIN(1024, BU27008_GSEL_1024X),
141 };
142 
143 static const struct iio_gain_sel_pair bu27008_gains_ir[] = {
144 	GAIN_SCALE_GAIN(2, BU27008_GSEL_1X),
145 	GAIN_SCALE_GAIN(4, BU27008_GSEL_4X),
146 	GAIN_SCALE_GAIN(8, BU27008_GSEL_8X),
147 	GAIN_SCALE_GAIN(16, BU27008_GSEL_16X),
148 	GAIN_SCALE_GAIN(32, BU27008_GSEL_32X),
149 	GAIN_SCALE_GAIN(64, BU27008_GSEL_64X),
150 	GAIN_SCALE_GAIN(256, BU27008_GSEL_256X),
151 	GAIN_SCALE_GAIN(512, BU27008_GSEL_512X),
152 	GAIN_SCALE_GAIN(1024, BU27008_GSEL_1024X),
153 };
154 
155 #define BU27008_MEAS_MODE_100MS		0x00
156 #define BU27008_MEAS_MODE_55MS		0x01
157 #define BU27008_MEAS_MODE_200MS		0x02
158 #define BU27008_MEAS_MODE_400MS		0x04
159 #define BU27008_MEAS_TIME_MAX_MS	400
160 
161 static const struct iio_itime_sel_mul bu27008_itimes[] = {
162 	GAIN_SCALE_ITIME_US(400000, BU27008_MEAS_MODE_400MS, 8),
163 	GAIN_SCALE_ITIME_US(200000, BU27008_MEAS_MODE_200MS, 4),
164 	GAIN_SCALE_ITIME_US(100000, BU27008_MEAS_MODE_100MS, 2),
165 	GAIN_SCALE_ITIME_US(55000, BU27008_MEAS_MODE_55MS, 1),
166 };
167 
168 /*
169  * All the RGBC channels share the same gain.
170  * IR gain can be fine-tuned from the gain set for the RGBC by 2 bit, but this
171  * would yield quite complex gain setting. Especially since not all bit
172  * compinations are supported. And in any case setting GAIN for RGBC will
173  * always also change the IR-gain.
174  *
175  * On top of this, the selector '0' which corresponds to hw-gain 1X on RGBC,
176  * corresponds to gain 2X on IR. Rest of the selctors correspond to same gains
177  * though. This, however, makes it not possible to use shared gain for all
178  * RGBC and IR settings even though they are all changed at the one go.
179  */
180 #define BU27008_CHAN(color, data, separate_avail)				\
181 {										\
182 	.type = IIO_INTENSITY,							\
183 	.modified = 1,								\
184 	.channel2 = IIO_MOD_LIGHT_##color,					\
185 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |				\
186 			      BIT(IIO_CHAN_INFO_SCALE),				\
187 	.info_mask_separate_available = (separate_avail),			\
188 	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_INT_TIME),			\
189 	.info_mask_shared_by_all_available = BIT(IIO_CHAN_INFO_INT_TIME),	\
190 	.address = BU27008_REG_##data##_LO,					\
191 	.scan_index = BU27008_##color,						\
192 	.scan_type = {								\
193 		.sign = 'u',							\
194 		.realbits = 16,							\
195 		.storagebits = 16,						\
196 		.endianness = IIO_LE,						\
197 	},									\
198 }
199 
200 /* For raw reads we always configure DATA3 for CLEAR */
201 static const struct iio_chan_spec bu27008_channels[] = {
202 	BU27008_CHAN(RED, DATA0, BIT(IIO_CHAN_INFO_SCALE)),
203 	BU27008_CHAN(GREEN, DATA1, BIT(IIO_CHAN_INFO_SCALE)),
204 	BU27008_CHAN(BLUE, DATA2, BIT(IIO_CHAN_INFO_SCALE)),
205 	BU27008_CHAN(CLEAR, DATA2, BIT(IIO_CHAN_INFO_SCALE)),
206 	/*
207 	 * We don't allow setting scale for IR (because of shared gain bits).
208 	 * Hence we don't advertise available ones either.
209 	 */
210 	BU27008_CHAN(IR, DATA3, 0),
211 	IIO_CHAN_SOFT_TIMESTAMP(BU27008_NUM_CHANS),
212 };
213 
214 struct bu27008_data {
215 	struct regmap *regmap;
216 	struct iio_trigger *trig;
217 	struct device *dev;
218 	struct iio_gts gts;
219 	struct iio_gts gts_ir;
220 	int irq;
221 
222 	/*
223 	 * Prevent changing gain/time config when scale is read/written.
224 	 * Similarly, protect the integration_time read/change sequence.
225 	 * Prevent changing gain/time when data is read.
226 	 */
227 	struct mutex mutex;
228 };
229 
230 static const struct regmap_range bu27008_volatile_ranges[] = {
231 	{
232 		.range_min = BU27008_REG_SYSTEM_CONTROL,	/* SWRESET */
233 		.range_max = BU27008_REG_SYSTEM_CONTROL,
234 	}, {
235 		.range_min = BU27008_REG_MODE_CONTROL3,		/* VALID */
236 		.range_max = BU27008_REG_MODE_CONTROL3,
237 	}, {
238 		.range_min = BU27008_REG_DATA0_LO,		/* DATA */
239 		.range_max = BU27008_REG_DATA3_HI,
240 	},
241 };
242 
243 static const struct regmap_access_table bu27008_volatile_regs = {
244 	.yes_ranges = &bu27008_volatile_ranges[0],
245 	.n_yes_ranges = ARRAY_SIZE(bu27008_volatile_ranges),
246 };
247 
248 static const struct regmap_range bu27008_read_only_ranges[] = {
249 	{
250 		.range_min = BU27008_REG_DATA0_LO,
251 		.range_max = BU27008_REG_DATA3_HI,
252 	}, {
253 		.range_min = BU27008_REG_MANUFACTURER_ID,
254 		.range_max = BU27008_REG_MANUFACTURER_ID,
255 	},
256 };
257 
258 static const struct regmap_access_table bu27008_ro_regs = {
259 	.no_ranges = &bu27008_read_only_ranges[0],
260 	.n_no_ranges = ARRAY_SIZE(bu27008_read_only_ranges),
261 };
262 
263 static const struct regmap_config bu27008_regmap = {
264 	.reg_bits = 8,
265 	.val_bits = 8,
266 	.max_register = BU27008_REG_MAX,
267 	.cache_type = REGCACHE_RBTREE,
268 	.volatile_table = &bu27008_volatile_regs,
269 	.wr_table = &bu27008_ro_regs,
270 	/*
271 	 * All register writes are serialized by the mutex which protects the
272 	 * scale setting/getting. This is needed because scale is combined by
273 	 * gain and integration time settings and we need to ensure those are
274 	 * not read / written when scale is being computed.
275 	 *
276 	 * As a result of this serializing, we don't need regmap locking. Note,
277 	 * this is not true if we add any configurations which are not
278 	 * serialized by the mutex and which may need for example a protected
279 	 * read-modify-write cycle (eg. regmap_update_bits()). Please, revise
280 	 * this when adding features to the driver.
281 	 */
282 	.disable_locking = true,
283 };
284 
285 #define BU27008_MAX_VALID_RESULT_WAIT_US	50000
286 #define BU27008_VALID_RESULT_WAIT_QUANTA_US	1000
287 
288 static int bu27008_chan_read_data(struct bu27008_data *data, int reg, int *val)
289 {
290 	int ret, valid;
291 	__le16 tmp;
292 
293 	ret = regmap_read_poll_timeout(data->regmap, BU27008_REG_MODE_CONTROL3,
294 				       valid, (valid & BU27008_MASK_VALID),
295 				       BU27008_VALID_RESULT_WAIT_QUANTA_US,
296 				       BU27008_MAX_VALID_RESULT_WAIT_US);
297 	if (ret)
298 		return ret;
299 
300 	ret = regmap_bulk_read(data->regmap, reg, &tmp, sizeof(tmp));
301 	if (ret)
302 		dev_err(data->dev, "Reading channel data failed\n");
303 
304 	*val = le16_to_cpu(tmp);
305 
306 	return ret;
307 }
308 
309 static int bu27008_get_gain(struct bu27008_data *data, struct iio_gts *gts, int *gain)
310 {
311 	int ret, sel;
312 
313 	ret = regmap_read(data->regmap, BU27008_REG_MODE_CONTROL2, &sel);
314 	if (ret)
315 		return ret;
316 
317 	sel = FIELD_GET(BU27008_MASK_RGBC_GAIN, sel);
318 
319 	ret = iio_gts_find_gain_by_sel(gts, sel);
320 	if (ret < 0) {
321 		dev_err(data->dev, "unknown gain value 0x%x\n", sel);
322 		return ret;
323 	}
324 
325 	*gain = ret;
326 
327 	return 0;
328 }
329 
330 static int bu27008_write_gain_sel(struct bu27008_data *data, int sel)
331 {
332 	int regval;
333 
334 	regval = FIELD_PREP(BU27008_MASK_RGBC_GAIN, sel);
335 
336 	/*
337 	 * We do always set also the LOW bits of IR-gain because othervice we
338 	 * would risk resulting an invalid GAIN register value.
339 	 *
340 	 * We could allow setting separate gains for RGBC and IR when the
341 	 * values were such that HW could support both gain settings.
342 	 * Eg, when the shared bits were same for both gain values.
343 	 *
344 	 * This, however, has a negligible benefit compared to the increased
345 	 * software complexity when we would need to go through the gains
346 	 * for both channels separately when the integration time changes.
347 	 * This would end up with nasty logic for computing gain values for
348 	 * both channels - and rejecting them if shared bits changed.
349 	 *
350 	 * We should then build the logic by guessing what a user prefers.
351 	 * RGBC or IR gains correctly set while other jumps to odd value?
352 	 * Maybe look-up a value where both gains are somehow optimized
353 	 * <what this somehow is, is ATM unknown to us>. Or maybe user would
354 	 * expect us to reject changes when optimal gains can't be set to both
355 	 * channels w/given integration time. At best that would result
356 	 * solution that works well for a very specific subset of
357 	 * configurations but causes unexpected corner-cases.
358 	 *
359 	 * So, we keep it simple. Always set same selector to IR and RGBC.
360 	 * We disallow setting IR (as I expect that most of the users are
361 	 * interested in RGBC). This way we can show the user that the scales
362 	 * for RGBC and IR channels are different (1X Vs 2X with sel 0) while
363 	 * still keeping the operation deterministic.
364 	 */
365 	regval |= FIELD_PREP(BU27008_MASK_IR_GAIN_LO, sel);
366 
367 	return regmap_update_bits(data->regmap, BU27008_REG_MODE_CONTROL2,
368 				  BU27008_MASK_RGBC_GAIN, regval);
369 }
370 
371 static int bu27008_set_gain(struct bu27008_data *data, int gain)
372 {
373 	int ret;
374 
375 	ret = iio_gts_find_sel_by_gain(&data->gts, gain);
376 	if (ret < 0)
377 		return ret;
378 
379 	return bu27008_write_gain_sel(data, ret);
380 }
381 
382 static int bu27008_get_int_time_sel(struct bu27008_data *data, int *sel)
383 {
384 	int ret, val;
385 
386 	ret = regmap_read(data->regmap, BU27008_REG_MODE_CONTROL1, &val);
387 	*sel = FIELD_GET(BU27008_MASK_MEAS_MODE, val);
388 
389 	return ret;
390 }
391 
392 static int bu27008_set_int_time_sel(struct bu27008_data *data, int sel)
393 {
394 	return regmap_update_bits(data->regmap, BU27008_REG_MODE_CONTROL1,
395 				  BU27008_MASK_MEAS_MODE, sel);
396 }
397 
398 static int bu27008_get_int_time_us(struct bu27008_data *data)
399 {
400 	int ret, sel;
401 
402 	ret = bu27008_get_int_time_sel(data, &sel);
403 	if (ret)
404 		return ret;
405 
406 	return iio_gts_find_int_time_by_sel(&data->gts, sel);
407 }
408 
409 static int _bu27008_get_scale(struct bu27008_data *data, bool ir, int *val,
410 			      int *val2)
411 {
412 	struct iio_gts *gts;
413 	int gain, ret;
414 
415 	if (ir)
416 		gts = &data->gts_ir;
417 	else
418 		gts = &data->gts;
419 
420 	ret = bu27008_get_gain(data, gts, &gain);
421 	if (ret)
422 		return ret;
423 
424 	ret = bu27008_get_int_time_us(data);
425 	if (ret < 0)
426 		return ret;
427 
428 	return iio_gts_get_scale(gts, gain, ret, val, val2);
429 }
430 
431 static int bu27008_get_scale(struct bu27008_data *data, bool ir, int *val,
432 			     int *val2)
433 {
434 	int ret;
435 
436 	mutex_lock(&data->mutex);
437 	ret = _bu27008_get_scale(data, ir, val, val2);
438 	mutex_unlock(&data->mutex);
439 
440 	return ret;
441 }
442 
443 static int bu27008_set_int_time(struct bu27008_data *data, int time)
444 {
445 	int ret;
446 
447 	ret = iio_gts_find_sel_by_int_time(&data->gts, time);
448 	if (ret < 0)
449 		return ret;
450 
451 	return regmap_update_bits(data->regmap, BU27008_REG_MODE_CONTROL1,
452 				  BU27008_MASK_MEAS_MODE, ret);
453 }
454 
455 /* Try to change the time so that the scale is maintained */
456 static int bu27008_try_set_int_time(struct bu27008_data *data, int int_time_new)
457 {
458 	int ret, old_time_sel, new_time_sel,  old_gain, new_gain;
459 
460 	mutex_lock(&data->mutex);
461 
462 	ret = bu27008_get_int_time_sel(data, &old_time_sel);
463 	if (ret < 0)
464 		goto unlock_out;
465 
466 	if (!iio_gts_valid_time(&data->gts, int_time_new)) {
467 		dev_dbg(data->dev, "Unsupported integration time %u\n",
468 			int_time_new);
469 
470 		ret = -EINVAL;
471 		goto unlock_out;
472 	}
473 
474 	/* If we already use requested time, then we're done */
475 	new_time_sel = iio_gts_find_sel_by_int_time(&data->gts, int_time_new);
476 	if (new_time_sel == old_time_sel)
477 		goto unlock_out;
478 
479 	ret = bu27008_get_gain(data, &data->gts, &old_gain);
480 	if (ret)
481 		goto unlock_out;
482 
483 	ret = iio_gts_find_new_gain_sel_by_old_gain_time(&data->gts, old_gain,
484 				old_time_sel, new_time_sel, &new_gain);
485 	if (ret) {
486 		int scale1, scale2;
487 		bool ok;
488 
489 		_bu27008_get_scale(data, false, &scale1, &scale2);
490 		dev_dbg(data->dev,
491 			"Can't support time %u with current scale %u %u\n",
492 			int_time_new, scale1, scale2);
493 
494 		if (new_gain < 0)
495 			goto unlock_out;
496 
497 		/*
498 		 * If caller requests for integration time change and we
499 		 * can't support the scale - then the caller should be
500 		 * prepared to 'pick up the pieces and deal with the
501 		 * fact that the scale changed'.
502 		 */
503 		ret = iio_find_closest_gain_low(&data->gts, new_gain, &ok);
504 		if (!ok)
505 			dev_dbg(data->dev, "optimal gain out of range\n");
506 
507 		if (ret < 0) {
508 			dev_dbg(data->dev,
509 				 "Total gain increase. Risk of saturation");
510 			ret = iio_gts_get_min_gain(&data->gts);
511 			if (ret < 0)
512 				goto unlock_out;
513 		}
514 		new_gain = ret;
515 		dev_dbg(data->dev, "scale changed, new gain %u\n", new_gain);
516 	}
517 
518 	ret = bu27008_set_gain(data, new_gain);
519 	if (ret)
520 		goto unlock_out;
521 
522 	ret = bu27008_set_int_time(data, int_time_new);
523 
524 unlock_out:
525 	mutex_unlock(&data->mutex);
526 
527 	return ret;
528 }
529 
530 static int bu27008_meas_set(struct bu27008_data *data, int state)
531 {
532 	return regmap_update_bits(data->regmap, BU27008_REG_MODE_CONTROL3,
533 				  BU27008_MASK_MEAS_EN, state);
534 }
535 
536 static int bu27008_chan_cfg(struct bu27008_data *data,
537 			    struct iio_chan_spec const *chan)
538 {
539 	int chan_sel;
540 
541 	if (chan->scan_index == BU27008_BLUE)
542 		chan_sel = BU27008_BLUE2_CLEAR3;
543 	else
544 		chan_sel = BU27008_CLEAR2_IR3;
545 
546 	chan_sel = FIELD_PREP(BU27008_MASK_CHAN_SEL, chan_sel);
547 
548 	return regmap_update_bits(data->regmap, BU27008_REG_MODE_CONTROL3,
549 				  BU27008_MASK_CHAN_SEL, chan_sel);
550 }
551 
552 static int bu27008_read_one(struct bu27008_data *data, struct iio_dev *idev,
553 			    struct iio_chan_spec const *chan, int *val, int *val2)
554 {
555 	int ret, int_time;
556 
557 	ret = bu27008_chan_cfg(data, chan);
558 	if (ret)
559 		return ret;
560 
561 	ret = bu27008_meas_set(data, BU27008_MEAS_EN);
562 	if (ret)
563 		return ret;
564 
565 	ret = bu27008_get_int_time_us(data);
566 	if (ret < 0)
567 		int_time = BU27008_MEAS_TIME_MAX_MS;
568 	else
569 		int_time = ret / USEC_PER_MSEC;
570 
571 	msleep(int_time);
572 
573 	ret = bu27008_chan_read_data(data, chan->address, val);
574 	if (!ret)
575 		ret = IIO_VAL_INT;
576 
577 	if (bu27008_meas_set(data, BU27008_MEAS_DIS))
578 		dev_warn(data->dev, "measurement disabling failed\n");
579 
580 	return ret;
581 }
582 
583 static int bu27008_read_raw(struct iio_dev *idev,
584 			   struct iio_chan_spec const *chan,
585 			   int *val, int *val2, long mask)
586 {
587 	struct bu27008_data *data = iio_priv(idev);
588 	int busy, ret;
589 
590 	switch (mask) {
591 	case IIO_CHAN_INFO_RAW:
592 		busy = iio_device_claim_direct_mode(idev);
593 		if (busy)
594 			return -EBUSY;
595 
596 		mutex_lock(&data->mutex);
597 		ret = bu27008_read_one(data, idev, chan, val, val2);
598 		mutex_unlock(&data->mutex);
599 
600 		iio_device_release_direct_mode(idev);
601 
602 		return ret;
603 
604 	case IIO_CHAN_INFO_SCALE:
605 		ret = bu27008_get_scale(data, chan->scan_index == BU27008_IR,
606 					val, val2);
607 		if (ret)
608 			return ret;
609 
610 		return IIO_VAL_INT_PLUS_NANO;
611 
612 	case IIO_CHAN_INFO_INT_TIME:
613 		ret = bu27008_get_int_time_us(data);
614 		if (ret < 0)
615 			return ret;
616 
617 		*val = 0;
618 		*val2 = ret;
619 
620 		return IIO_VAL_INT_PLUS_MICRO;
621 
622 	default:
623 		return -EINVAL;
624 	}
625 }
626 
627 /* Called if the new scale could not be supported with existing int-time */
628 static int bu27008_try_find_new_time_gain(struct bu27008_data *data, int val,
629 					  int val2, int *gain_sel)
630 {
631 	int i, ret, new_time_sel;
632 
633 	for (i = 0; i < data->gts.num_itime; i++) {
634 		new_time_sel = data->gts.itime_table[i].sel;
635 		ret = iio_gts_find_gain_sel_for_scale_using_time(&data->gts,
636 					new_time_sel, val, val2, gain_sel);
637 		if (!ret)
638 			break;
639 	}
640 	if (i == data->gts.num_itime) {
641 		dev_err(data->dev, "Can't support scale %u %u\n", val, val2);
642 
643 		return -EINVAL;
644 	}
645 
646 	return bu27008_set_int_time_sel(data, new_time_sel);
647 }
648 
649 static int bu27008_set_scale(struct bu27008_data *data,
650 			     struct iio_chan_spec const *chan,
651 			     int val, int val2)
652 {
653 	int ret, gain_sel, time_sel;
654 
655 	if (chan->scan_index == BU27008_IR)
656 		return -EINVAL;
657 
658 	mutex_lock(&data->mutex);
659 
660 	ret = bu27008_get_int_time_sel(data, &time_sel);
661 	if (ret < 0)
662 		goto unlock_out;
663 
664 	ret = iio_gts_find_gain_sel_for_scale_using_time(&data->gts, time_sel,
665 						val, val2, &gain_sel);
666 	if (ret) {
667 		ret = bu27008_try_find_new_time_gain(data, val, val2, &gain_sel);
668 		if (ret)
669 			goto unlock_out;
670 
671 	}
672 	ret = bu27008_write_gain_sel(data, gain_sel);
673 
674 unlock_out:
675 	mutex_unlock(&data->mutex);
676 
677 	return ret;
678 }
679 
680 static int bu27008_write_raw_get_fmt(struct iio_dev *indio_dev,
681 				     struct iio_chan_spec const *chan,
682 				     long mask)
683 {
684 
685 	switch (mask) {
686 	case IIO_CHAN_INFO_SCALE:
687 		return IIO_VAL_INT_PLUS_NANO;
688 	case IIO_CHAN_INFO_INT_TIME:
689 		return IIO_VAL_INT_PLUS_MICRO;
690 	default:
691 		return -EINVAL;
692 	}
693 }
694 
695 static int bu27008_write_raw(struct iio_dev *idev,
696 			     struct iio_chan_spec const *chan,
697 			     int val, int val2, long mask)
698 {
699 	struct bu27008_data *data = iio_priv(idev);
700 	int ret;
701 
702 	/*
703 	 * Do not allow changing scale when measurement is ongoing as doing so
704 	 * could make values in the buffer inconsistent.
705 	 */
706 	ret = iio_device_claim_direct_mode(idev);
707 	if (ret)
708 		return ret;
709 
710 	switch (mask) {
711 	case IIO_CHAN_INFO_SCALE:
712 		ret = bu27008_set_scale(data, chan, val, val2);
713 		break;
714 	case IIO_CHAN_INFO_INT_TIME:
715 		if (val) {
716 			ret = -EINVAL;
717 			break;
718 		}
719 		ret = bu27008_try_set_int_time(data, val2);
720 		break;
721 	default:
722 		ret = -EINVAL;
723 		break;
724 	}
725 	iio_device_release_direct_mode(idev);
726 
727 	return ret;
728 }
729 
730 static int bu27008_read_avail(struct iio_dev *idev,
731 			      struct iio_chan_spec const *chan, const int **vals,
732 			      int *type, int *length, long mask)
733 {
734 	struct bu27008_data *data = iio_priv(idev);
735 
736 	switch (mask) {
737 	case IIO_CHAN_INFO_INT_TIME:
738 		return iio_gts_avail_times(&data->gts, vals, type, length);
739 	case IIO_CHAN_INFO_SCALE:
740 		if (chan->channel2 == IIO_MOD_LIGHT_IR)
741 			return iio_gts_all_avail_scales(&data->gts_ir, vals,
742 							type, length);
743 		return iio_gts_all_avail_scales(&data->gts, vals, type, length);
744 	default:
745 		return -EINVAL;
746 	}
747 }
748 
749 static int bu27008_update_scan_mode(struct iio_dev *idev,
750 				    const unsigned long *scan_mask)
751 {
752 	struct bu27008_data *data = iio_priv(idev);
753 	int chan_sel;
754 
755 	/* Configure channel selection */
756 	if (test_bit(BU27008_BLUE, idev->active_scan_mask)) {
757 		if (test_bit(BU27008_CLEAR, idev->active_scan_mask))
758 			chan_sel = BU27008_BLUE2_CLEAR3;
759 		else
760 			chan_sel = BU27008_BLUE2_IR3;
761 	} else {
762 		chan_sel = BU27008_CLEAR2_IR3;
763 	}
764 
765 	chan_sel = FIELD_PREP(BU27008_MASK_CHAN_SEL, chan_sel);
766 
767 	return regmap_update_bits(data->regmap, BU27008_REG_MODE_CONTROL3,
768 				 BU27008_MASK_CHAN_SEL, chan_sel);
769 }
770 
771 static const struct iio_info bu27008_info = {
772 	.read_raw = &bu27008_read_raw,
773 	.write_raw = &bu27008_write_raw,
774 	.write_raw_get_fmt = &bu27008_write_raw_get_fmt,
775 	.read_avail = &bu27008_read_avail,
776 	.update_scan_mode = bu27008_update_scan_mode,
777 	.validate_trigger = iio_validate_own_trigger,
778 };
779 
780 static int bu27008_chip_init(struct bu27008_data *data)
781 {
782 	int ret;
783 
784 	ret = regmap_write_bits(data->regmap, BU27008_REG_SYSTEM_CONTROL,
785 				BU27008_MASK_SW_RESET, BU27008_MASK_SW_RESET);
786 	if (ret)
787 		return dev_err_probe(data->dev, ret, "Sensor reset failed\n");
788 
789 	/*
790 	 * The data-sheet does not tell how long performing the IC reset takes.
791 	 * However, the data-sheet says the minimum time it takes the IC to be
792 	 * able to take inputs after power is applied, is 100 uS. I'd assume
793 	 * > 1 mS is enough.
794 	 */
795 	msleep(1);
796 
797 	ret = regmap_reinit_cache(data->regmap, &bu27008_regmap);
798 	if (ret)
799 		dev_err(data->dev, "Failed to reinit reg cache\n");
800 
801 	return ret;
802 }
803 
804 static int bu27008_set_drdy_irq(struct bu27008_data *data, int state)
805 {
806 	return regmap_update_bits(data->regmap, BU27008_REG_MODE_CONTROL3,
807 				 BU27008_MASK_INT_EN, state);
808 }
809 
810 static int bu27008_trigger_set_state(struct iio_trigger *trig,
811 				     bool state)
812 {
813 	struct bu27008_data *data = iio_trigger_get_drvdata(trig);
814 	int ret;
815 
816 	if (state)
817 		ret = bu27008_set_drdy_irq(data, BU27008_INT_EN);
818 	else
819 		ret = bu27008_set_drdy_irq(data, BU27008_INT_DIS);
820 	if (ret)
821 		dev_err(data->dev, "Failed to set trigger state\n");
822 
823 	return ret;
824 }
825 
826 static void bu27008_trigger_reenable(struct iio_trigger *trig)
827 {
828 	struct bu27008_data *data = iio_trigger_get_drvdata(trig);
829 
830 	enable_irq(data->irq);
831 }
832 
833 static const struct iio_trigger_ops bu27008_trigger_ops = {
834 	.set_trigger_state = bu27008_trigger_set_state,
835 	.reenable = bu27008_trigger_reenable,
836 };
837 
838 static irqreturn_t bu27008_trigger_handler(int irq, void *p)
839 {
840 	struct iio_poll_func *pf = p;
841 	struct iio_dev *idev = pf->indio_dev;
842 	struct bu27008_data *data = iio_priv(idev);
843 	struct {
844 		__le16 chan[BU27008_NUM_HW_CHANS];
845 		s64 ts __aligned(8);
846 	} raw;
847 	int ret, dummy;
848 
849 	memset(&raw, 0, sizeof(raw));
850 
851 	/*
852 	 * After some measurements, it seems reading the
853 	 * BU27008_REG_MODE_CONTROL3 debounces the IRQ line
854 	 */
855 	ret = regmap_read(data->regmap, BU27008_REG_MODE_CONTROL3, &dummy);
856 	if (ret < 0)
857 		goto err_read;
858 
859 	ret = regmap_bulk_read(data->regmap, BU27008_REG_DATA0_LO, &raw.chan,
860 			       sizeof(raw.chan));
861 	if (ret < 0)
862 		goto err_read;
863 
864 	iio_push_to_buffers_with_timestamp(idev, &raw, pf->timestamp);
865 err_read:
866 	iio_trigger_notify_done(idev->trig);
867 
868 	return IRQ_HANDLED;
869 }
870 
871 static int bu27008_buffer_preenable(struct iio_dev *idev)
872 {
873 	struct bu27008_data *data = iio_priv(idev);
874 
875 	return bu27008_meas_set(data, BU27008_MEAS_EN);
876 }
877 
878 static int bu27008_buffer_postdisable(struct iio_dev *idev)
879 {
880 	struct bu27008_data *data = iio_priv(idev);
881 
882 	return bu27008_meas_set(data, BU27008_MEAS_DIS);
883 }
884 
885 static const struct iio_buffer_setup_ops bu27008_buffer_ops = {
886 	.preenable = bu27008_buffer_preenable,
887 	.postdisable = bu27008_buffer_postdisable,
888 };
889 
890 static irqreturn_t bu27008_data_rdy_poll(int irq, void *private)
891 {
892 	/*
893 	 * The BU27008 keeps IRQ asserted until we read the VALID bit from
894 	 * a register. We need to keep the IRQ disabled until then.
895 	 */
896 	disable_irq_nosync(irq);
897 	iio_trigger_poll(private);
898 
899 	return IRQ_HANDLED;
900 }
901 
902 static int bu27008_setup_trigger(struct bu27008_data *data, struct iio_dev *idev)
903 {
904 	struct iio_trigger *itrig;
905 	char *name;
906 	int ret;
907 
908 	ret = devm_iio_triggered_buffer_setup(data->dev, idev,
909 					      &iio_pollfunc_store_time,
910 					      bu27008_trigger_handler,
911 					      &bu27008_buffer_ops);
912 	if (ret)
913 		return dev_err_probe(data->dev, ret,
914 			     "iio_triggered_buffer_setup_ext FAIL\n");
915 
916 	itrig = devm_iio_trigger_alloc(data->dev, "%sdata-rdy-dev%d",
917 				       idev->name, iio_device_id(idev));
918 	if (!itrig)
919 		return -ENOMEM;
920 
921 	data->trig = itrig;
922 
923 	itrig->ops = &bu27008_trigger_ops;
924 	iio_trigger_set_drvdata(itrig, data);
925 
926 	name = devm_kasprintf(data->dev, GFP_KERNEL, "%s-bu27008",
927 			      dev_name(data->dev));
928 
929 	ret = devm_request_irq(data->dev, data->irq,
930 			       &bu27008_data_rdy_poll,
931 			       0, name, itrig);
932 	if (ret)
933 		return dev_err_probe(data->dev, ret, "Could not request IRQ\n");
934 
935 	ret = devm_iio_trigger_register(data->dev, itrig);
936 	if (ret)
937 		return dev_err_probe(data->dev, ret,
938 				     "Trigger registration failed\n");
939 
940 	/* set default trigger */
941 	idev->trig = iio_trigger_get(itrig);
942 
943 	return 0;
944 }
945 
946 static int bu27008_probe(struct i2c_client *i2c)
947 {
948 	struct device *dev = &i2c->dev;
949 	struct bu27008_data *data;
950 	struct regmap *regmap;
951 	unsigned int part_id, reg;
952 	struct iio_dev *idev;
953 	int ret;
954 
955 	regmap = devm_regmap_init_i2c(i2c, &bu27008_regmap);
956 	if (IS_ERR(regmap))
957 		return dev_err_probe(dev, PTR_ERR(regmap),
958 				     "Failed to initialize Regmap\n");
959 
960 	idev = devm_iio_device_alloc(dev, sizeof(*data));
961 	if (!idev)
962 		return -ENOMEM;
963 
964 	ret = devm_regulator_get_enable(dev, "vdd");
965 	if (ret)
966 		return dev_err_probe(dev, ret, "Failed to get regulator\n");
967 
968 	data = iio_priv(idev);
969 
970 	ret = regmap_read(regmap, BU27008_REG_SYSTEM_CONTROL, &reg);
971 	if (ret)
972 		return dev_err_probe(dev, ret, "Failed to access sensor\n");
973 
974 	part_id = FIELD_GET(BU27008_MASK_PART_ID, reg);
975 
976 	if (part_id != BU27008_ID)
977 		dev_warn(dev, "unknown device 0x%x\n", part_id);
978 
979 	ret = devm_iio_init_iio_gts(dev, BU27008_SCALE_1X, 0, bu27008_gains,
980 				    ARRAY_SIZE(bu27008_gains), bu27008_itimes,
981 				    ARRAY_SIZE(bu27008_itimes), &data->gts);
982 	if (ret)
983 		return ret;
984 
985 	ret = devm_iio_init_iio_gts(dev, BU27008_SCALE_1X, 0, bu27008_gains_ir,
986 				    ARRAY_SIZE(bu27008_gains_ir), bu27008_itimes,
987 				    ARRAY_SIZE(bu27008_itimes), &data->gts_ir);
988 	if (ret)
989 		return ret;
990 
991 	mutex_init(&data->mutex);
992 	data->regmap = regmap;
993 	data->dev = dev;
994 	data->irq = i2c->irq;
995 
996 	idev->channels = bu27008_channels;
997 	idev->num_channels = ARRAY_SIZE(bu27008_channels);
998 	idev->name = "bu27008";
999 	idev->info = &bu27008_info;
1000 	idev->modes = INDIO_DIRECT_MODE;
1001 	idev->available_scan_masks = bu27008_scan_masks;
1002 
1003 	ret = bu27008_chip_init(data);
1004 	if (ret)
1005 		return ret;
1006 
1007 	if (i2c->irq) {
1008 		ret = bu27008_setup_trigger(data, idev);
1009 		if (ret)
1010 			return ret;
1011 	} else {
1012 		dev_info(dev, "No IRQ, buffered mode disabled\n");
1013 	}
1014 
1015 	ret = devm_iio_device_register(dev, idev);
1016 	if (ret)
1017 		return dev_err_probe(dev, ret,
1018 				     "Unable to register iio device\n");
1019 
1020 	return 0;
1021 }
1022 
1023 static const struct of_device_id bu27008_of_match[] = {
1024 	{ .compatible = "rohm,bu27008" },
1025 	{ }
1026 };
1027 MODULE_DEVICE_TABLE(of, bu27008_of_match);
1028 
1029 static struct i2c_driver bu27008_i2c_driver = {
1030 	.driver = {
1031 		.name = "bu27008",
1032 		.of_match_table = bu27008_of_match,
1033 		.probe_type = PROBE_PREFER_ASYNCHRONOUS,
1034 	},
1035 	.probe = bu27008_probe,
1036 };
1037 module_i2c_driver(bu27008_i2c_driver);
1038 
1039 MODULE_DESCRIPTION("ROHM BU27008 colour sensor driver");
1040 MODULE_AUTHOR("Matti Vaittinen <matti.vaittinen@fi.rohmeurope.com>");
1041 MODULE_LICENSE("GPL");
1042 MODULE_IMPORT_NS(IIO_GTS_HELPER);
1043