xref: /linux/drivers/iio/light/rohm-bu27034.c (revision 42d37fc0c819b81f6f6afd108b55d04ba9d32d0f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * BU27034 ROHM Ambient Light Sensor
4  *
5  * Copyright (c) 2023, ROHM Semiconductor.
6  * https://fscdn.rohm.com/en/products/databook/datasheet/ic/sensor/light/bu27034nuc-e.pdf
7  */
8 
9 #include <linux/bitfield.h>
10 #include <linux/bits.h>
11 #include <linux/device.h>
12 #include <linux/i2c.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/buffer.h>
20 #include <linux/iio/iio.h>
21 #include <linux/iio/iio-gts-helper.h>
22 #include <linux/iio/kfifo_buf.h>
23 
24 #define BU27034_REG_SYSTEM_CONTROL	0x40
25 #define BU27034_MASK_SW_RESET		BIT(7)
26 #define BU27034_MASK_PART_ID		GENMASK(5, 0)
27 #define BU27034_ID			0x19
28 #define BU27034_REG_MODE_CONTROL1	0x41
29 #define BU27034_MASK_MEAS_MODE		GENMASK(2, 0)
30 
31 #define BU27034_REG_MODE_CONTROL2	0x42
32 #define BU27034_MASK_D01_GAIN		GENMASK(7, 3)
33 #define BU27034_MASK_D2_GAIN_HI		GENMASK(7, 6)
34 #define BU27034_MASK_D2_GAIN_LO		GENMASK(2, 0)
35 
36 #define BU27034_REG_MODE_CONTROL3	0x43
37 #define BU27034_REG_MODE_CONTROL4	0x44
38 #define BU27034_MASK_MEAS_EN		BIT(0)
39 #define BU27034_MASK_VALID		BIT(7)
40 #define BU27034_REG_DATA0_LO		0x50
41 #define BU27034_REG_DATA1_LO		0x52
42 #define BU27034_REG_DATA2_LO		0x54
43 #define BU27034_REG_DATA2_HI		0x55
44 #define BU27034_REG_MANUFACTURER_ID	0x92
45 #define BU27034_REG_MAX BU27034_REG_MANUFACTURER_ID
46 
47 /*
48  * The BU27034 does not have interrupt to trigger the data read when a
49  * measurement has finished. Hence we poll the VALID bit in a thread. We will
50  * try to wake the thread BU27034_MEAS_WAIT_PREMATURE_MS milliseconds before
51  * the expected sampling time to prevent the drifting.
52  *
53  * If we constantly wake up a bit too late we would eventually skip a sample.
54  * And because the sleep can't wake up _exactly_ at given time this would be
55  * inevitable even if the sensor clock would be perfectly phase-locked to CPU
56  * clock - which we can't say is the case.
57  *
58  * This is still fragile. No matter how big advance do we have, we will still
59  * risk of losing a sample because things can in a rainy-day scenario be
60  * delayed a lot. Yet, more we reserve the time for polling, more we also lose
61  * the performance by spending cycles polling the register. So, selecting this
62  * value is a balancing dance between severity of wasting CPU time and severity
63  * of losing samples.
64  *
65  * In most cases losing the samples is not _that_ crucial because light levels
66  * tend to change slowly.
67  *
68  * Other option that was pointed to me would be always sleeping 1/2 of the
69  * measurement time, checking the VALID bit and just sleeping again if the bit
70  * was not set. That should be pretty tolerant against missing samples due to
71  * the scheduling delays while also not wasting much of cycles for polling.
72  * Downside is that the time-stamps would be very inaccurate as the wake-up
73  * would not really be tied to the sensor toggling the valid bit. This would also
74  * result 'jumps' in the time-stamps when the delay drifted so that wake-up was
75  * performed during the consecutive wake-ups (Or, when sensor and CPU clocks
76  * were very different and scheduling the wake-ups was very close to given
77  * timeout - and when the time-outs were very close to the actual sensor
78  * sampling, Eg. once in a blue moon, two consecutive time-outs would occur
79  * without having a sample ready).
80  */
81 #define BU27034_MEAS_WAIT_PREMATURE_MS	5
82 #define BU27034_DATA_WAIT_TIME_US	1000
83 #define BU27034_TOTAL_DATA_WAIT_TIME_US (BU27034_MEAS_WAIT_PREMATURE_MS * 1000)
84 
85 #define BU27034_RETRY_LIMIT 18
86 
87 enum {
88 	BU27034_CHAN_ALS,
89 	BU27034_CHAN_DATA0,
90 	BU27034_CHAN_DATA1,
91 	BU27034_CHAN_DATA2,
92 	BU27034_NUM_CHANS
93 };
94 
95 static const unsigned long bu27034_scan_masks[] = {
96 	GENMASK(BU27034_CHAN_DATA2, BU27034_CHAN_ALS), 0
97 };
98 
99 /*
100  * Available scales with gain 1x - 4096x, timings 55, 100, 200, 400 mS
101  * Time impacts to gain: 1x, 2x, 4x, 8x.
102  *
103  * => Max total gain is HWGAIN * gain by integration time (8 * 4096) = 32768
104  *
105  * Using NANO precision for scale we must use scale 64x corresponding gain 1x
106  * to avoid precision loss. (32x would result scale 976 562.5(nanos).
107  */
108 #define BU27034_SCALE_1X	64
109 
110 /* See the data sheet for the "Gain Setting" table */
111 #define BU27034_GSEL_1X		0x00 /* 00000 */
112 #define BU27034_GSEL_4X		0x08 /* 01000 */
113 #define BU27034_GSEL_16X	0x0a /* 01010 */
114 #define BU27034_GSEL_32X	0x0b /* 01011 */
115 #define BU27034_GSEL_64X	0x0c /* 01100 */
116 #define BU27034_GSEL_256X	0x18 /* 11000 */
117 #define BU27034_GSEL_512X	0x19 /* 11001 */
118 #define BU27034_GSEL_1024X	0x1a /* 11010 */
119 #define BU27034_GSEL_2048X	0x1b /* 11011 */
120 #define BU27034_GSEL_4096X	0x1c /* 11100 */
121 
122 /* Available gain settings */
123 static const struct iio_gain_sel_pair bu27034_gains[] = {
124 	GAIN_SCALE_GAIN(1, BU27034_GSEL_1X),
125 	GAIN_SCALE_GAIN(4, BU27034_GSEL_4X),
126 	GAIN_SCALE_GAIN(16, BU27034_GSEL_16X),
127 	GAIN_SCALE_GAIN(32, BU27034_GSEL_32X),
128 	GAIN_SCALE_GAIN(64, BU27034_GSEL_64X),
129 	GAIN_SCALE_GAIN(256, BU27034_GSEL_256X),
130 	GAIN_SCALE_GAIN(512, BU27034_GSEL_512X),
131 	GAIN_SCALE_GAIN(1024, BU27034_GSEL_1024X),
132 	GAIN_SCALE_GAIN(2048, BU27034_GSEL_2048X),
133 	GAIN_SCALE_GAIN(4096, BU27034_GSEL_4096X),
134 };
135 
136 /*
137  * The IC has 5 modes for sampling time. 5 mS mode is exceptional as it limits
138  * the data collection to data0-channel only and cuts the supported range to
139  * 10 bit. It is not supported by the driver.
140  *
141  * "normal" modes are 55, 100, 200 and 400 mS modes - which do have direct
142  * multiplying impact to the register values (similar to gain).
143  *
144  * This means that if meas-mode is changed for example from 400 => 200,
145  * the scale is doubled. Eg, time impact to total gain is x1, x2, x4, x8.
146  */
147 #define BU27034_MEAS_MODE_100MS		0
148 #define BU27034_MEAS_MODE_55MS		1
149 #define BU27034_MEAS_MODE_200MS		2
150 #define BU27034_MEAS_MODE_400MS		4
151 
152 static const struct iio_itime_sel_mul bu27034_itimes[] = {
153 	GAIN_SCALE_ITIME_US(400000, BU27034_MEAS_MODE_400MS, 8),
154 	GAIN_SCALE_ITIME_US(200000, BU27034_MEAS_MODE_200MS, 4),
155 	GAIN_SCALE_ITIME_US(100000, BU27034_MEAS_MODE_100MS, 2),
156 	GAIN_SCALE_ITIME_US(55000, BU27034_MEAS_MODE_55MS, 1),
157 };
158 
159 #define BU27034_CHAN_DATA(_name, _ch2)					\
160 {									\
161 	.type = IIO_INTENSITY,						\
162 	.channel = BU27034_CHAN_##_name,				\
163 	.channel2 = (_ch2),						\
164 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |			\
165 			      BIT(IIO_CHAN_INFO_SCALE),			\
166 	.info_mask_separate_available = BIT(IIO_CHAN_INFO_SCALE),	\
167 	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_INT_TIME),		\
168 	.info_mask_shared_by_all_available =				\
169 					BIT(IIO_CHAN_INFO_INT_TIME),	\
170 	.address = BU27034_REG_##_name##_LO,				\
171 	.scan_index = BU27034_CHAN_##_name,				\
172 	.scan_type = {							\
173 		.sign = 'u',						\
174 		.realbits = 16,						\
175 		.storagebits = 16,					\
176 		.endianness = IIO_LE,					\
177 	},								\
178 	.indexed = 1,							\
179 }
180 
181 static const struct iio_chan_spec bu27034_channels[] = {
182 	{
183 		.type = IIO_LIGHT,
184 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
185 				      BIT(IIO_CHAN_INFO_SCALE),
186 		.channel = BU27034_CHAN_ALS,
187 		.scan_index = BU27034_CHAN_ALS,
188 		.scan_type = {
189 			.sign = 'u',
190 			.realbits = 32,
191 			.storagebits = 32,
192 			.endianness = IIO_CPU,
193 		},
194 	},
195 	/*
196 	 * The BU27034 DATA0 and DATA1 channels are both on the visible light
197 	 * area (mostly). The data0 sensitivity peaks at 500nm, DATA1 at 600nm.
198 	 * These wave lengths are pretty much on the border of colours making
199 	 * these a poor candidates for R/G/B standardization. Hence they're both
200 	 * marked as clear channels
201 	 */
202 	BU27034_CHAN_DATA(DATA0, IIO_MOD_LIGHT_CLEAR),
203 	BU27034_CHAN_DATA(DATA1, IIO_MOD_LIGHT_CLEAR),
204 	BU27034_CHAN_DATA(DATA2, IIO_MOD_LIGHT_IR),
205 	IIO_CHAN_SOFT_TIMESTAMP(4),
206 };
207 
208 struct bu27034_data {
209 	struct regmap *regmap;
210 	struct device *dev;
211 	/*
212 	 * Protect gain and time during scale adjustment and data reading.
213 	 * Protect measurement enabling/disabling.
214 	 */
215 	struct mutex mutex;
216 	struct iio_gts gts;
217 	struct task_struct *task;
218 	__le16 raw[3];
219 	struct {
220 		u32 mlux;
221 		__le16 channels[3];
222 		s64 ts __aligned(8);
223 	} scan;
224 };
225 
226 static const struct regmap_range bu27034_volatile_ranges[] = {
227 	{
228 		.range_min = BU27034_REG_SYSTEM_CONTROL,
229 		.range_max = BU27034_REG_SYSTEM_CONTROL,
230 	}, {
231 		.range_min = BU27034_REG_MODE_CONTROL4,
232 		.range_max = BU27034_REG_MODE_CONTROL4,
233 	}, {
234 		.range_min = BU27034_REG_DATA0_LO,
235 		.range_max = BU27034_REG_DATA2_HI,
236 	},
237 };
238 
239 static const struct regmap_access_table bu27034_volatile_regs = {
240 	.yes_ranges = &bu27034_volatile_ranges[0],
241 	.n_yes_ranges = ARRAY_SIZE(bu27034_volatile_ranges),
242 };
243 
244 static const struct regmap_range bu27034_read_only_ranges[] = {
245 	{
246 		.range_min = BU27034_REG_DATA0_LO,
247 		.range_max = BU27034_REG_DATA2_HI,
248 	}, {
249 		.range_min = BU27034_REG_MANUFACTURER_ID,
250 		.range_max = BU27034_REG_MANUFACTURER_ID,
251 	}
252 };
253 
254 static const struct regmap_access_table bu27034_ro_regs = {
255 	.no_ranges = &bu27034_read_only_ranges[0],
256 	.n_no_ranges = ARRAY_SIZE(bu27034_read_only_ranges),
257 };
258 
259 static const struct regmap_config bu27034_regmap = {
260 	.reg_bits = 8,
261 	.val_bits = 8,
262 	.max_register = BU27034_REG_MAX,
263 	.cache_type = REGCACHE_RBTREE,
264 	.volatile_table = &bu27034_volatile_regs,
265 	.wr_table = &bu27034_ro_regs,
266 };
267 
268 struct bu27034_gain_check {
269 	int old_gain;
270 	int new_gain;
271 	int chan;
272 };
273 
274 static int bu27034_get_gain_sel(struct bu27034_data *data, int chan)
275 {
276 	int ret, val;
277 
278 	switch (chan) {
279 	case BU27034_CHAN_DATA0:
280 	case BU27034_CHAN_DATA1:
281 	{
282 		int reg[] = {
283 			[BU27034_CHAN_DATA0] = BU27034_REG_MODE_CONTROL2,
284 			[BU27034_CHAN_DATA1] = BU27034_REG_MODE_CONTROL3,
285 		};
286 		ret = regmap_read(data->regmap, reg[chan], &val);
287 		if (ret)
288 			return ret;
289 
290 		return FIELD_GET(BU27034_MASK_D01_GAIN, val);
291 	}
292 	case BU27034_CHAN_DATA2:
293 	{
294 		int d2_lo_bits = fls(BU27034_MASK_D2_GAIN_LO);
295 
296 		ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL2, &val);
297 		if (ret)
298 			return ret;
299 
300 		/*
301 		 * The data2 channel gain is composed by 5 non continuous bits
302 		 * [7:6], [2:0]. Thus when we combine the 5-bit 'selector'
303 		 * from register value we must right shift the high bits by 3.
304 		 */
305 		return FIELD_GET(BU27034_MASK_D2_GAIN_HI, val) << d2_lo_bits |
306 		       FIELD_GET(BU27034_MASK_D2_GAIN_LO, val);
307 	}
308 	default:
309 		return -EINVAL;
310 	}
311 }
312 
313 static int bu27034_get_gain(struct bu27034_data *data, int chan, int *gain)
314 {
315 	int ret, sel;
316 
317 	ret = bu27034_get_gain_sel(data, chan);
318 	if (ret < 0)
319 		return ret;
320 
321 	sel = ret;
322 
323 	ret = iio_gts_find_gain_by_sel(&data->gts, sel);
324 	if (ret < 0) {
325 		dev_err(data->dev, "chan %u: unknown gain value 0x%x\n", chan,
326 			sel);
327 
328 		return ret;
329 	}
330 
331 	*gain = ret;
332 
333 	return 0;
334 }
335 
336 static int bu27034_get_int_time(struct bu27034_data *data)
337 {
338 	int ret, sel;
339 
340 	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &sel);
341 	if (ret)
342 		return ret;
343 
344 	return iio_gts_find_int_time_by_sel(&data->gts,
345 					    sel & BU27034_MASK_MEAS_MODE);
346 }
347 
348 static int _bu27034_get_scale(struct bu27034_data *data, int channel, int *val,
349 			      int *val2)
350 {
351 	int gain, ret;
352 
353 	ret = bu27034_get_gain(data, channel, &gain);
354 	if (ret)
355 		return ret;
356 
357 	ret = bu27034_get_int_time(data);
358 	if (ret < 0)
359 		return ret;
360 
361 	return iio_gts_get_scale(&data->gts, gain, ret, val, val2);
362 }
363 
364 static int bu27034_get_scale(struct bu27034_data *data, int channel, int *val,
365 			      int *val2)
366 {
367 	int ret;
368 
369 	if (channel == BU27034_CHAN_ALS) {
370 		*val = 0;
371 		*val2 = 1000;
372 		return IIO_VAL_INT_PLUS_MICRO;
373 	}
374 
375 	mutex_lock(&data->mutex);
376 	ret = _bu27034_get_scale(data, channel, val, val2);
377 	mutex_unlock(&data->mutex);
378 	if (ret)
379 		return ret;
380 
381 	return IIO_VAL_INT_PLUS_NANO;
382 }
383 
384 /* Caller should hold the lock to protect lux reading */
385 static int bu27034_write_gain_sel(struct bu27034_data *data, int chan, int sel)
386 {
387 	static const int reg[] = {
388 		[BU27034_CHAN_DATA0] = BU27034_REG_MODE_CONTROL2,
389 		[BU27034_CHAN_DATA1] = BU27034_REG_MODE_CONTROL3,
390 	};
391 	int mask, val;
392 
393 	if (chan != BU27034_CHAN_DATA0 && chan != BU27034_CHAN_DATA1)
394 		return -EINVAL;
395 
396 	val = FIELD_PREP(BU27034_MASK_D01_GAIN, sel);
397 
398 	mask = BU27034_MASK_D01_GAIN;
399 
400 	if (chan == BU27034_CHAN_DATA0) {
401 		/*
402 		 * We keep the same gain for channel 2 as we set for channel 0
403 		 * We can't allow them to be individually controlled because
404 		 * setting one will impact also the other. Also, if we don't
405 		 * always update both gains we may result unsupported bit
406 		 * combinations.
407 		 *
408 		 * This is not nice but this is yet another place where the
409 		 * user space must be prepared to surprizes. Namely, see chan 2
410 		 * gain changed when chan 0 gain is changed.
411 		 *
412 		 * This is not fatal for most users though. I don't expect the
413 		 * channel 2 to be used in any generic cases - the intensity
414 		 * values provided by the sensor for IR area are not openly
415 		 * documented. Also, channel 2 is not used for visible light.
416 		 *
417 		 * So, if there is application which is written to utilize the
418 		 * channel 2 - then it is probably specifically targeted to this
419 		 * sensor and knows how to utilize those values. It is safe to
420 		 * hope such user can also cope with the gain changes.
421 		 */
422 		mask |=  BU27034_MASK_D2_GAIN_LO;
423 
424 		/*
425 		 * The D2 gain bits are directly the lowest bits of selector.
426 		 * Just do add those bits to the value
427 		 */
428 		val |= sel & BU27034_MASK_D2_GAIN_LO;
429 	}
430 
431 	return regmap_update_bits(data->regmap, reg[chan], mask, val);
432 }
433 
434 static int bu27034_set_gain(struct bu27034_data *data, int chan, int gain)
435 {
436 	int ret;
437 
438 	/*
439 	 * We don't allow setting channel 2 gain as it messes up the
440 	 * gain for channel 0 - which shares the high bits
441 	 */
442 	if (chan != BU27034_CHAN_DATA0 && chan != BU27034_CHAN_DATA1)
443 		return -EINVAL;
444 
445 	ret = iio_gts_find_sel_by_gain(&data->gts, gain);
446 	if (ret < 0)
447 		return ret;
448 
449 	return bu27034_write_gain_sel(data, chan, ret);
450 }
451 
452 /* Caller should hold the lock to protect data->int_time */
453 static int bu27034_set_int_time(struct bu27034_data *data, int time)
454 {
455 	int ret;
456 
457 	ret = iio_gts_find_sel_by_int_time(&data->gts, time);
458 	if (ret < 0)
459 		return ret;
460 
461 	return regmap_update_bits(data->regmap, BU27034_REG_MODE_CONTROL1,
462 				 BU27034_MASK_MEAS_MODE, ret);
463 }
464 
465 /*
466  * We try to change the time in such way that the scale is maintained for
467  * given channels by adjusting gain so that it compensates the time change.
468  */
469 static int bu27034_try_set_int_time(struct bu27034_data *data, int time_us)
470 {
471 	struct bu27034_gain_check gains[] = {
472 		{ .chan = BU27034_CHAN_DATA0 },
473 		{ .chan = BU27034_CHAN_DATA1 },
474 	};
475 	int numg = ARRAY_SIZE(gains);
476 	int ret, int_time_old, i;
477 
478 	mutex_lock(&data->mutex);
479 	ret = bu27034_get_int_time(data);
480 	if (ret < 0)
481 		goto unlock_out;
482 
483 	int_time_old = ret;
484 
485 	if (!iio_gts_valid_time(&data->gts, time_us)) {
486 		dev_err(data->dev, "Unsupported integration time %u\n",
487 			time_us);
488 		ret = -EINVAL;
489 
490 		goto unlock_out;
491 	}
492 
493 	if (time_us == int_time_old) {
494 		ret = 0;
495 		goto unlock_out;
496 	}
497 
498 	for (i = 0; i < numg; i++) {
499 		ret = bu27034_get_gain(data, gains[i].chan, &gains[i].old_gain);
500 		if (ret)
501 			goto unlock_out;
502 
503 		ret = iio_gts_find_new_gain_by_old_gain_time(&data->gts,
504 							     gains[i].old_gain,
505 							     int_time_old, time_us,
506 							     &gains[i].new_gain);
507 		if (ret) {
508 			int scale1, scale2;
509 			bool ok;
510 
511 			_bu27034_get_scale(data, gains[i].chan, &scale1, &scale2);
512 			dev_dbg(data->dev,
513 				"chan %u, can't support time %u with scale %u %u\n",
514 				gains[i].chan, time_us, scale1, scale2);
515 
516 			if (gains[i].new_gain < 0)
517 				goto unlock_out;
518 
519 			/*
520 			 * If caller requests for integration time change and we
521 			 * can't support the scale - then the caller should be
522 			 * prepared to 'pick up the pieces and deal with the
523 			 * fact that the scale changed'.
524 			 */
525 			ret = iio_find_closest_gain_low(&data->gts,
526 							gains[i].new_gain, &ok);
527 
528 			if (!ok)
529 				dev_dbg(data->dev,
530 					"optimal gain out of range for chan %u\n",
531 					gains[i].chan);
532 
533 			if (ret < 0) {
534 				dev_dbg(data->dev,
535 					 "Total gain increase. Risk of saturation");
536 				ret = iio_gts_get_min_gain(&data->gts);
537 				if (ret < 0)
538 					goto unlock_out;
539 			}
540 			dev_dbg(data->dev, "chan %u scale changed\n",
541 				 gains[i].chan);
542 			gains[i].new_gain = ret;
543 			dev_dbg(data->dev, "chan %u new gain %u\n",
544 				gains[i].chan, gains[i].new_gain);
545 		}
546 	}
547 
548 	for (i = 0; i < numg; i++) {
549 		ret = bu27034_set_gain(data, gains[i].chan, gains[i].new_gain);
550 		if (ret)
551 			goto unlock_out;
552 	}
553 
554 	ret = bu27034_set_int_time(data, time_us);
555 
556 unlock_out:
557 	mutex_unlock(&data->mutex);
558 
559 	return ret;
560 }
561 
562 static int bu27034_set_scale(struct bu27034_data *data, int chan,
563 			    int val, int val2)
564 {
565 	int ret, time_sel, gain_sel, i;
566 	bool found = false;
567 
568 	if (chan == BU27034_CHAN_DATA2)
569 		return -EINVAL;
570 
571 	if (chan == BU27034_CHAN_ALS) {
572 		if (val == 0 && val2 == 1000000)
573 			return 0;
574 
575 		return -EINVAL;
576 	}
577 
578 	mutex_lock(&data->mutex);
579 	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &time_sel);
580 	if (ret)
581 		goto unlock_out;
582 
583 	ret = iio_gts_find_gain_sel_for_scale_using_time(&data->gts, time_sel,
584 						val, val2, &gain_sel);
585 	if (ret) {
586 		/*
587 		 * Could not support scale with given time. Need to change time.
588 		 * We still want to maintain the scale for all channels
589 		 */
590 		struct bu27034_gain_check gain;
591 		int new_time_sel;
592 
593 		/*
594 		 * Populate information for the other channel which should also
595 		 * maintain the scale. (Due to the HW limitations the chan2
596 		 * gets the same gain as chan0, so we only need to explicitly
597 		 * set the chan 0 and 1).
598 		 */
599 		if (chan == BU27034_CHAN_DATA0)
600 			gain.chan = BU27034_CHAN_DATA1;
601 		else if (chan == BU27034_CHAN_DATA1)
602 			gain.chan = BU27034_CHAN_DATA0;
603 
604 		ret = bu27034_get_gain(data, gain.chan, &gain.old_gain);
605 		if (ret)
606 			goto unlock_out;
607 
608 		/*
609 		 * Iterate through all the times to see if we find one which
610 		 * can support requested scale for requested channel, while
611 		 * maintaining the scale for other channels
612 		 */
613 		for (i = 0; i < data->gts.num_itime; i++) {
614 			new_time_sel = data->gts.itime_table[i].sel;
615 
616 			if (new_time_sel == time_sel)
617 				continue;
618 
619 			/* Can we provide requested scale with this time? */
620 			ret = iio_gts_find_gain_sel_for_scale_using_time(
621 				&data->gts, new_time_sel, val, val2,
622 				&gain_sel);
623 			if (ret)
624 				continue;
625 
626 			/* Can the other channel(s) maintain scale? */
627 			ret = iio_gts_find_new_gain_sel_by_old_gain_time(
628 				&data->gts, gain.old_gain, time_sel,
629 				new_time_sel, &gain.new_gain);
630 			if (!ret) {
631 				/* Yes - we found suitable time */
632 				found = true;
633 				break;
634 			}
635 		}
636 		if (!found) {
637 			dev_dbg(data->dev,
638 				"Can't set scale maintaining other channels\n");
639 			ret = -EINVAL;
640 
641 			goto unlock_out;
642 		}
643 
644 		ret = bu27034_set_gain(data, gain.chan, gain.new_gain);
645 		if (ret)
646 			goto unlock_out;
647 
648 		ret = regmap_update_bits(data->regmap, BU27034_REG_MODE_CONTROL1,
649 				  BU27034_MASK_MEAS_MODE, new_time_sel);
650 		if (ret)
651 			goto unlock_out;
652 	}
653 
654 	ret = bu27034_write_gain_sel(data, chan, gain_sel);
655 unlock_out:
656 	mutex_unlock(&data->mutex);
657 
658 	return ret;
659 }
660 
661 /*
662  * for (D1/D0 < 0.87):
663  * lx = 0.004521097 * D1 - 0.002663996 * D0 +
664  *	0.00012213 * D1 * D1 / D0
665  *
666  * =>	115.7400832 * ch1 / gain1 / mt -
667  *	68.1982976 * ch0 / gain0 / mt +
668  *	0.00012213 * 25600 * (ch1 / gain1 / mt) * 25600 *
669  *	(ch1 /gain1 / mt) / (25600 * ch0 / gain0 / mt)
670  *
671  * A =	0.00012213 * 25600 * (ch1 /gain1 / mt) * 25600 *
672  *	(ch1 /gain1 / mt) / (25600 * ch0 / gain0 / mt)
673  * =>	0.00012213 * 25600 * (ch1 /gain1 / mt) *
674  *	(ch1 /gain1 / mt) / (ch0 / gain0 / mt)
675  * =>	0.00012213 * 25600 * (ch1 / gain1) * (ch1 /gain1 / mt) /
676  *	(ch0 / gain0)
677  * =>	0.00012213 * 25600 * (ch1 / gain1) * (ch1 /gain1 / mt) *
678  *	gain0 / ch0
679  * =>	3.126528 * ch1 * ch1 * gain0 / gain1 / gain1 / mt /ch0
680  *
681  * lx = (115.7400832 * ch1 / gain1 - 68.1982976 * ch0 / gain0) /
682  *	mt + A
683  * =>	(115.7400832 * ch1 / gain1 - 68.1982976 * ch0 / gain0) /
684  *	mt + 3.126528 * ch1 * ch1 * gain0 / gain1 / gain1 / mt /
685  *	ch0
686  *
687  * =>	(115.7400832 * ch1 / gain1 - 68.1982976 * ch0 / gain0 +
688  *	  3.126528 * ch1 * ch1 * gain0 / gain1 / gain1 / ch0) /
689  *	  mt
690  *
691  * For (0.87 <= D1/D0 < 1.00)
692  * lx = (0.001331* D0 + 0.0000354 * D1) * ((D1/D0 – 0.87) * (0.385) + 1)
693  * =>	(0.001331 * 256 * 100 * ch0 / gain0 / mt + 0.0000354 * 256 *
694  *	100 * ch1 / gain1 / mt) * ((D1/D0 -  0.87) * (0.385) + 1)
695  * =>	(34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
696  *	((D1/D0 -  0.87) * (0.385) + 1)
697  * =>	(34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
698  *	(0.385 * D1/D0 - 0.66505)
699  * =>	(34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
700  *	(0.385 * 256 * 100 * ch1 / gain1 / mt / (256 * 100 * ch0 / gain0 / mt) - 0.66505)
701  * =>	(34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
702  *	(9856 * ch1 / gain1 / mt / (25600 * ch0 / gain0 / mt) + 0.66505)
703  * =>	13.118336 * ch1 / (gain1 * mt)
704  *	+ 22.66064768 * ch0 / (gain0 * mt)
705  *	+ 8931.90144 * ch1 * ch1 * gain0 /
706  *	  (25600 * ch0 * gain1 * gain1 * mt)
707  *	+ 0.602694912 * ch1 / (gain1 * mt)
708  *
709  * =>	[0.3489024 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1)
710  *	 + 22.66064768 * ch0 / gain0
711  *	 + 13.721030912 * ch1 / gain1
712  *	] / mt
713  *
714  * For (D1/D0 >= 1.00)
715  *
716  * lx	= (0.001331* D0 + 0.0000354 * D1) * ((D1/D0 – 2.0) * (-0.05) + 1)
717  *	=> (0.001331* D0 + 0.0000354 * D1) * (-0.05D1/D0 + 1.1)
718  *	=> (0.001331 * 256 * 100 * ch0 / gain0 / mt + 0.0000354 * 256 *
719  *	   100 * ch1 / gain1 / mt) * (-0.05D1/D0 + 1.1)
720  *	=> (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
721  *	   (-0.05 * 256 * 100 * ch1 / gain1 / mt / (256 * 100 * ch0 / gain0 / mt) + 1.1)
722  *	=> (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
723  *	   (-1280 * ch1 / (gain1 * mt * 25600 * ch0 / gain0 / mt) + 1.1)
724  *	=> (34.0736 * ch0 * -1280 * ch1 * gain0 * mt /( gain0 * mt * gain1 * mt * 25600 * ch0)
725  *	    + 34.0736 * 1.1 * ch0 / (gain0 * mt)
726  *	    + 0.90624 * ch1 * -1280 * ch1 *gain0 * mt / (gain1 * mt *gain1 * mt * 25600 * ch0)
727  *	    + 1.1 * 0.90624 * ch1 / (gain1 * mt)
728  *	=> -43614.208 * ch1 / (gain1 * mt * 25600)
729  *	    + 37.48096  ch0 / (gain0 * mt)
730  *	    - 1159.9872 * ch1 * ch1 * gain0 / (gain1 * gain1 * mt * 25600 * ch0)
731  *	    + 0.996864 ch1 / (gain1 * mt)
732  *	=> [
733  *		- 0.045312 * ch1 * ch1 * gain0 / (gain1 * gain1 * ch0)
734  *		- 0.706816 * ch1 / gain1
735  *		+ 37.48096  ch0 /gain0
736  *	   ] * mt
737  *
738  *
739  * So, the first case (D1/D0 < 0.87) can be computed to a form:
740  *
741  * lx = (3.126528 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
742  *	 115.7400832 * ch1 / gain1 +
743  *	-68.1982976 * ch0 / gain0
744  *	 / mt
745  *
746  * Second case (0.87 <= D1/D0 < 1.00) goes to form:
747  *
748  *	=> [0.3489024 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
749  *	    13.721030912 * ch1 / gain1 +
750  *	    22.66064768 * ch0 / gain0
751  *	   ] / mt
752  *
753  * Third case (D1/D0 >= 1.00) goes to form:
754  *	=> [-0.045312 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
755  *	    -0.706816 * ch1 / gain1 +
756  *	    37.48096  ch0 /(gain0
757  *	   ] / mt
758  *
759  * This can be unified to format:
760  * lx = [
761  *	 A * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
762  *	 B * ch1 / gain1 +
763  *	 C * ch0 / gain0
764  *	] / mt
765  *
766  * For case 1:
767  * A = 3.126528,
768  * B = 115.7400832
769  * C = -68.1982976
770  *
771  * For case 2:
772  * A = 0.3489024
773  * B = 13.721030912
774  * C = 22.66064768
775  *
776  * For case 3:
777  * A = -0.045312
778  * B = -0.706816
779  * C = 37.48096
780  */
781 
782 struct bu27034_lx_coeff {
783 	unsigned int A;
784 	unsigned int B;
785 	unsigned int C;
786 	/* Indicate which of the coefficients above are negative */
787 	bool is_neg[3];
788 };
789 
790 static inline u64 gain_mul_div_helper(u64 val, unsigned int gain,
791 				      unsigned int div)
792 {
793 	/*
794 	 * Max gain for a channel is 4096. The max u64 (0xffffffffffffffffULL)
795 	 * divided by 4096 is 0xFFFFFFFFFFFFF (GENMASK_ULL(51, 0)) (floored).
796 	 * Thus, the 0xFFFFFFFFFFFFF is the largest value we can safely multiply
797 	 * with the gain, no matter what gain is set.
798 	 *
799 	 * So, multiplication with max gain may overflow if val is greater than
800 	 * 0xFFFFFFFFFFFFF (52 bits set)..
801 	 *
802 	 * If this is the case we divide first.
803 	 */
804 	if (val < GENMASK_ULL(51, 0)) {
805 		val *= gain;
806 		do_div(val, div);
807 	} else {
808 		do_div(val, div);
809 		val *= gain;
810 	}
811 
812 	return val;
813 }
814 
815 static u64 bu27034_fixp_calc_t1_64bit(unsigned int coeff, unsigned int ch0,
816 				      unsigned int ch1, unsigned int gain0,
817 				      unsigned int gain1)
818 {
819 	unsigned int helper;
820 	u64 helper64;
821 
822 	helper64 = (u64)coeff * (u64)ch1 * (u64)ch1;
823 
824 	helper = gain1 * gain1;
825 	if (helper > ch0) {
826 		do_div(helper64, helper);
827 
828 		return gain_mul_div_helper(helper64, gain0, ch0);
829 	}
830 
831 	do_div(helper64, ch0);
832 
833 	return gain_mul_div_helper(helper64, gain0, helper);
834 
835 }
836 
837 static u64 bu27034_fixp_calc_t1(unsigned int coeff, unsigned int ch0,
838 				unsigned int ch1, unsigned int gain0,
839 				unsigned int gain1)
840 {
841 	unsigned int helper, tmp;
842 
843 	/*
844 	 * Here we could overflow even the 64bit value. Hence we
845 	 * multiply with gain0 only after the divisions - even though
846 	 * it may result loss of accuracy
847 	 */
848 	helper = coeff * ch1 * ch1;
849 	tmp = helper * gain0;
850 
851 	helper = ch1 * ch1;
852 
853 	if (check_mul_overflow(helper, coeff, &helper))
854 		return bu27034_fixp_calc_t1_64bit(coeff, ch0, ch1, gain0, gain1);
855 
856 	if (check_mul_overflow(helper, gain0, &tmp))
857 		return bu27034_fixp_calc_t1_64bit(coeff, ch0, ch1, gain0, gain1);
858 
859 	return tmp / (gain1 * gain1) / ch0;
860 
861 }
862 
863 static u64 bu27034_fixp_calc_t23(unsigned int coeff, unsigned int ch,
864 				 unsigned int gain)
865 {
866 	unsigned int helper;
867 	u64 helper64;
868 
869 	if (!check_mul_overflow(coeff, ch, &helper))
870 		return helper / gain;
871 
872 	helper64 = (u64)coeff * (u64)ch;
873 	do_div(helper64, gain);
874 
875 	return helper64;
876 }
877 
878 static int bu27034_fixp_calc_lx(unsigned int ch0, unsigned int ch1,
879 				unsigned int gain0, unsigned int gain1,
880 				unsigned int meastime, int coeff_idx)
881 {
882 	static const struct bu27034_lx_coeff coeff[] = {
883 		{
884 			.A = 31265280,		/* 3.126528 */
885 			.B = 1157400832,	/*115.7400832 */
886 			.C = 681982976,		/* -68.1982976 */
887 			.is_neg = {false, false, true},
888 		}, {
889 			.A = 3489024,		/* 0.3489024 */
890 			.B = 137210309,		/* 13.721030912 */
891 			.C = 226606476,		/* 22.66064768 */
892 			/* All terms positive */
893 		}, {
894 			.A = 453120,		/* -0.045312 */
895 			.B = 7068160,		/* -0.706816 */
896 			.C = 374809600,		/* 37.48096 */
897 			.is_neg = {true, true, false},
898 		}
899 	};
900 	const struct bu27034_lx_coeff *c = &coeff[coeff_idx];
901 	u64 res = 0, terms[3];
902 	int i;
903 
904 	if (coeff_idx >= ARRAY_SIZE(coeff))
905 		return -EINVAL;
906 
907 	terms[0] = bu27034_fixp_calc_t1(c->A, ch0, ch1, gain0, gain1);
908 	terms[1] = bu27034_fixp_calc_t23(c->B, ch1, gain1);
909 	terms[2] = bu27034_fixp_calc_t23(c->C, ch0, gain0);
910 
911 	/* First, add positive terms */
912 	for (i = 0; i < 3; i++)
913 		if (!c->is_neg[i])
914 			res += terms[i];
915 
916 	/* No positive term => zero lux */
917 	if (!res)
918 		return 0;
919 
920 	/* Then, subtract negative terms (if any) */
921 	for (i = 0; i < 3; i++)
922 		if (c->is_neg[i]) {
923 			/*
924 			 * If the negative term is greater than positive - then
925 			 * the darkness has taken over and we are all doomed! Eh,
926 			 * I mean, then we can just return 0 lx and go out
927 			 */
928 			if (terms[i] >= res)
929 				return 0;
930 
931 			res -= terms[i];
932 		}
933 
934 	meastime *= 10;
935 	do_div(res, meastime);
936 
937 	return (int) res;
938 }
939 
940 static bool bu27034_has_valid_sample(struct bu27034_data *data)
941 {
942 	int ret, val;
943 
944 	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL4, &val);
945 	if (ret) {
946 		dev_err(data->dev, "Read failed %d\n", ret);
947 
948 		return false;
949 	}
950 
951 	return val & BU27034_MASK_VALID;
952 }
953 
954 /*
955  * Reading the register where VALID bit is clears this bit. (So does changing
956  * any gain / integration time configuration registers) The bit gets
957  * set when we have acquired new data. We use this bit to indicate data
958  * validity.
959  */
960 static void bu27034_invalidate_read_data(struct bu27034_data *data)
961 {
962 	bu27034_has_valid_sample(data);
963 }
964 
965 static int bu27034_read_result(struct bu27034_data *data, int chan, int *res)
966 {
967 	int reg[] = {
968 		[BU27034_CHAN_DATA0] = BU27034_REG_DATA0_LO,
969 		[BU27034_CHAN_DATA1] = BU27034_REG_DATA1_LO,
970 		[BU27034_CHAN_DATA2] = BU27034_REG_DATA2_LO,
971 	};
972 	int valid, ret;
973 	__le16 val;
974 
975 	ret = regmap_read_poll_timeout(data->regmap, BU27034_REG_MODE_CONTROL4,
976 				       valid, (valid & BU27034_MASK_VALID),
977 				       BU27034_DATA_WAIT_TIME_US, 0);
978 	if (ret)
979 		return ret;
980 
981 	ret = regmap_bulk_read(data->regmap, reg[chan], &val, sizeof(val));
982 	if (ret)
983 		return ret;
984 
985 	*res = le16_to_cpu(val);
986 
987 	return 0;
988 }
989 
990 static int bu27034_get_result_unlocked(struct bu27034_data *data, __le16 *res,
991 				       int size)
992 {
993 	int ret = 0, retry_cnt = 0;
994 
995 retry:
996 	/* Get new value from sensor if data is ready */
997 	if (bu27034_has_valid_sample(data)) {
998 		ret = regmap_bulk_read(data->regmap, BU27034_REG_DATA0_LO,
999 				       res, size);
1000 		if (ret)
1001 			return ret;
1002 
1003 		bu27034_invalidate_read_data(data);
1004 	} else {
1005 		/* No new data in sensor. Wait and retry */
1006 		retry_cnt++;
1007 
1008 		if (retry_cnt > BU27034_RETRY_LIMIT) {
1009 			dev_err(data->dev, "No data from sensor\n");
1010 
1011 			return -ETIMEDOUT;
1012 		}
1013 
1014 		msleep(25);
1015 
1016 		goto retry;
1017 	}
1018 
1019 	return ret;
1020 }
1021 
1022 static int bu27034_meas_set(struct bu27034_data *data, bool en)
1023 {
1024 	if (en)
1025 		return regmap_set_bits(data->regmap, BU27034_REG_MODE_CONTROL4,
1026 				       BU27034_MASK_MEAS_EN);
1027 
1028 	return regmap_clear_bits(data->regmap, BU27034_REG_MODE_CONTROL4,
1029 				 BU27034_MASK_MEAS_EN);
1030 }
1031 
1032 static int bu27034_get_single_result(struct bu27034_data *data, int chan,
1033 				     int *val)
1034 {
1035 	int ret;
1036 
1037 	if (chan < BU27034_CHAN_DATA0 || chan > BU27034_CHAN_DATA2)
1038 		return -EINVAL;
1039 
1040 	ret = bu27034_meas_set(data, true);
1041 	if (ret)
1042 		return ret;
1043 
1044 	ret = bu27034_get_int_time(data);
1045 	if (ret < 0)
1046 		return ret;
1047 
1048 	msleep(ret / 1000);
1049 
1050 	return bu27034_read_result(data, chan, val);
1051 }
1052 
1053 /*
1054  * The formula given by vendor for computing luxes out of data0 and data1
1055  * (in open air) is as follows:
1056  *
1057  * Let's mark:
1058  * D0 = data0/ch0_gain/meas_time_ms * 25600
1059  * D1 = data1/ch1_gain/meas_time_ms * 25600
1060  *
1061  * Then:
1062  * if (D1/D0 < 0.87)
1063  *	lx = (0.001331 * D0 + 0.0000354 * D1) * ((D1 / D0 - 0.87) * 3.45 + 1)
1064  * else if (D1/D0 < 1)
1065  *	lx = (0.001331 * D0 + 0.0000354 * D1) * ((D1 / D0 - 0.87) * 0.385 + 1)
1066  * else
1067  *	lx = (0.001331 * D0 + 0.0000354 * D1) * ((D1 / D0 - 2) * -0.05 + 1)
1068  *
1069  * We use it here. Users who have for example some colored lens
1070  * need to modify the calculation but I hope this gives a starting point for
1071  * those working with such devices.
1072  */
1073 
1074 static int bu27034_calc_mlux(struct bu27034_data *data, __le16 *res, int *val)
1075 {
1076 	unsigned int gain0, gain1, meastime;
1077 	unsigned int d1_d0_ratio_scaled;
1078 	u16 ch0, ch1;
1079 	u64 helper64;
1080 	int ret;
1081 
1082 	/*
1083 	 * We return 0 lux if calculation fails. This should be reasonably
1084 	 * easy to spot from the buffers especially if raw-data channels show
1085 	 * valid values
1086 	 */
1087 	*val = 0;
1088 
1089 	ch0 = max_t(u16, 1, le16_to_cpu(res[0]));
1090 	ch1 = max_t(u16, 1, le16_to_cpu(res[1]));
1091 
1092 	ret = bu27034_get_gain(data, BU27034_CHAN_DATA0, &gain0);
1093 	if (ret)
1094 		return ret;
1095 
1096 	ret = bu27034_get_gain(data, BU27034_CHAN_DATA1, &gain1);
1097 	if (ret)
1098 		return ret;
1099 
1100 	ret = bu27034_get_int_time(data);
1101 	if (ret < 0)
1102 		return ret;
1103 
1104 	meastime = ret;
1105 
1106 	d1_d0_ratio_scaled = (unsigned int)ch1 * (unsigned int)gain0 * 100;
1107 	helper64 = (u64)ch1 * (u64)gain0 * 100LLU;
1108 
1109 	if (helper64 != d1_d0_ratio_scaled) {
1110 		unsigned int div = (unsigned int)ch0 * gain1;
1111 
1112 		do_div(helper64, div);
1113 		d1_d0_ratio_scaled = helper64;
1114 	} else {
1115 		d1_d0_ratio_scaled /= ch0 * gain1;
1116 	}
1117 
1118 	if (d1_d0_ratio_scaled < 87)
1119 		ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 0);
1120 	else if (d1_d0_ratio_scaled < 100)
1121 		ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 1);
1122 	else
1123 		ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 2);
1124 
1125 	if (ret < 0)
1126 		return ret;
1127 
1128 	*val = ret;
1129 
1130 	return 0;
1131 
1132 }
1133 
1134 static int bu27034_get_mlux(struct bu27034_data *data, int chan, int *val)
1135 {
1136 	__le16 res[3];
1137 	int ret;
1138 
1139 	ret = bu27034_meas_set(data, true);
1140 	if (ret)
1141 		return ret;
1142 
1143 	ret = bu27034_get_result_unlocked(data, &res[0], sizeof(res));
1144 	if (ret)
1145 		return ret;
1146 
1147 	ret = bu27034_calc_mlux(data, res, val);
1148 	if (ret)
1149 		return ret;
1150 
1151 	ret = bu27034_meas_set(data, false);
1152 	if (ret)
1153 		dev_err(data->dev, "failed to disable measurement\n");
1154 
1155 	return 0;
1156 }
1157 
1158 static int bu27034_read_raw(struct iio_dev *idev,
1159 			   struct iio_chan_spec const *chan,
1160 			   int *val, int *val2, long mask)
1161 {
1162 	struct bu27034_data *data = iio_priv(idev);
1163 	int ret;
1164 
1165 	switch (mask) {
1166 	case IIO_CHAN_INFO_INT_TIME:
1167 		*val = 0;
1168 		*val2 = bu27034_get_int_time(data);
1169 		if (*val2 < 0)
1170 			return *val2;
1171 
1172 		return IIO_VAL_INT_PLUS_MICRO;
1173 
1174 	case IIO_CHAN_INFO_SCALE:
1175 		return bu27034_get_scale(data, chan->channel, val, val2);
1176 
1177 	case IIO_CHAN_INFO_RAW:
1178 	{
1179 		int (*result_get)(struct bu27034_data *data, int chan, int *val);
1180 
1181 		if (chan->type == IIO_INTENSITY)
1182 			result_get = bu27034_get_single_result;
1183 		else if (chan->type == IIO_LIGHT)
1184 			result_get = bu27034_get_mlux;
1185 		else
1186 			return -EINVAL;
1187 
1188 		/* Don't mess with measurement enabling while buffering */
1189 		ret = iio_device_claim_direct_mode(idev);
1190 		if (ret)
1191 			return ret;
1192 
1193 		mutex_lock(&data->mutex);
1194 		/*
1195 		 * Reading one channel at a time is inefficient but we
1196 		 * don't care here. Buffered version should be used if
1197 		 * performance is an issue.
1198 		 */
1199 		ret = result_get(data, chan->channel, val);
1200 
1201 		mutex_unlock(&data->mutex);
1202 		iio_device_release_direct_mode(idev);
1203 
1204 		if (ret)
1205 			return ret;
1206 
1207 		return IIO_VAL_INT;
1208 	}
1209 	default:
1210 		return -EINVAL;
1211 	}
1212 }
1213 
1214 static int bu27034_write_raw_get_fmt(struct iio_dev *indio_dev,
1215 				     struct iio_chan_spec const *chan,
1216 				     long mask)
1217 {
1218 
1219 	switch (mask) {
1220 	case IIO_CHAN_INFO_SCALE:
1221 		return IIO_VAL_INT_PLUS_NANO;
1222 	case IIO_CHAN_INFO_INT_TIME:
1223 		return IIO_VAL_INT_PLUS_MICRO;
1224 	default:
1225 		return -EINVAL;
1226 	}
1227 }
1228 
1229 static int bu27034_write_raw(struct iio_dev *idev,
1230 			     struct iio_chan_spec const *chan,
1231 			     int val, int val2, long mask)
1232 {
1233 	struct bu27034_data *data = iio_priv(idev);
1234 	int ret;
1235 
1236 	ret = iio_device_claim_direct_mode(idev);
1237 	if (ret)
1238 		return ret;
1239 
1240 	switch (mask) {
1241 	case IIO_CHAN_INFO_SCALE:
1242 		ret = bu27034_set_scale(data, chan->channel, val, val2);
1243 		break;
1244 	case IIO_CHAN_INFO_INT_TIME:
1245 		if (!val)
1246 			ret = bu27034_try_set_int_time(data, val2);
1247 		else
1248 			ret = -EINVAL;
1249 		break;
1250 	default:
1251 		ret = -EINVAL;
1252 		break;
1253 	}
1254 
1255 	iio_device_release_direct_mode(idev);
1256 
1257 	return ret;
1258 }
1259 
1260 static int bu27034_read_avail(struct iio_dev *idev,
1261 			      struct iio_chan_spec const *chan, const int **vals,
1262 			      int *type, int *length, long mask)
1263 {
1264 	struct bu27034_data *data = iio_priv(idev);
1265 
1266 	switch (mask) {
1267 	case IIO_CHAN_INFO_INT_TIME:
1268 		return iio_gts_avail_times(&data->gts, vals, type, length);
1269 	case IIO_CHAN_INFO_SCALE:
1270 		return iio_gts_all_avail_scales(&data->gts, vals, type, length);
1271 	default:
1272 		return -EINVAL;
1273 	}
1274 }
1275 
1276 static const struct iio_info bu27034_info = {
1277 	.read_raw = &bu27034_read_raw,
1278 	.write_raw = &bu27034_write_raw,
1279 	.write_raw_get_fmt = &bu27034_write_raw_get_fmt,
1280 	.read_avail = &bu27034_read_avail,
1281 };
1282 
1283 static int bu27034_chip_init(struct bu27034_data *data)
1284 {
1285 	int ret, sel;
1286 
1287 	/* Reset */
1288 	ret = regmap_write_bits(data->regmap, BU27034_REG_SYSTEM_CONTROL,
1289 			   BU27034_MASK_SW_RESET, BU27034_MASK_SW_RESET);
1290 	if (ret)
1291 		return dev_err_probe(data->dev, ret, "Sensor reset failed\n");
1292 
1293 	msleep(1);
1294 
1295 	ret = regmap_reinit_cache(data->regmap, &bu27034_regmap);
1296 	if (ret) {
1297 		dev_err(data->dev, "Failed to reinit reg cache\n");
1298 		return ret;
1299 	}
1300 
1301 	/*
1302 	 * Read integration time here to ensure it is in regmap cache. We do
1303 	 * this to speed-up the int-time acquisition in the start of the buffer
1304 	 * handling thread where longer delays could make it more likely we end
1305 	 * up skipping a sample, and where the longer delays make timestamps
1306 	 * less accurate.
1307 	 */
1308 	ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &sel);
1309 	if (ret)
1310 		dev_err(data->dev, "reading integration time failed\n");
1311 
1312 	return 0;
1313 }
1314 
1315 static int bu27034_wait_for_data(struct bu27034_data *data)
1316 {
1317 	int ret, val;
1318 
1319 	ret = regmap_read_poll_timeout(data->regmap, BU27034_REG_MODE_CONTROL4,
1320 				       val, val & BU27034_MASK_VALID,
1321 				       BU27034_DATA_WAIT_TIME_US,
1322 				       BU27034_TOTAL_DATA_WAIT_TIME_US);
1323 	if (ret) {
1324 		dev_err(data->dev, "data polling %s\n",
1325 			!(val & BU27034_MASK_VALID) ? "timeout" : "fail");
1326 
1327 		return ret;
1328 	}
1329 
1330 	ret = regmap_bulk_read(data->regmap, BU27034_REG_DATA0_LO,
1331 			       &data->scan.channels[0],
1332 			       sizeof(data->scan.channels));
1333 	if (ret)
1334 		return ret;
1335 
1336 	bu27034_invalidate_read_data(data);
1337 
1338 	return 0;
1339 }
1340 
1341 static int bu27034_buffer_thread(void *arg)
1342 {
1343 	struct iio_dev *idev = arg;
1344 	struct bu27034_data *data;
1345 	int wait_ms;
1346 
1347 	data = iio_priv(idev);
1348 
1349 	wait_ms = bu27034_get_int_time(data);
1350 	wait_ms /= 1000;
1351 
1352 	wait_ms -= BU27034_MEAS_WAIT_PREMATURE_MS;
1353 
1354 	while (!kthread_should_stop()) {
1355 		int ret;
1356 		int64_t tstamp;
1357 
1358 		msleep(wait_ms);
1359 		ret = bu27034_wait_for_data(data);
1360 		if (ret)
1361 			continue;
1362 
1363 		tstamp = iio_get_time_ns(idev);
1364 
1365 		if (test_bit(BU27034_CHAN_ALS, idev->active_scan_mask)) {
1366 			int mlux;
1367 
1368 			ret = bu27034_calc_mlux(data, &data->scan.channels[0],
1369 					       &mlux);
1370 			if (ret)
1371 				dev_err(data->dev, "failed to calculate lux\n");
1372 
1373 			/*
1374 			 * The maximum Milli lux value we get with gain 1x time
1375 			 * 55mS data ch0 = 0xffff ch1 = 0xffff fits in 26 bits
1376 			 * so there should be no problem returning int from
1377 			 * computations and casting it to u32
1378 			 */
1379 			data->scan.mlux = (u32)mlux;
1380 		}
1381 		iio_push_to_buffers_with_timestamp(idev, &data->scan, tstamp);
1382 	}
1383 
1384 	return 0;
1385 }
1386 
1387 static int bu27034_buffer_enable(struct iio_dev *idev)
1388 {
1389 	struct bu27034_data *data = iio_priv(idev);
1390 	struct task_struct *task;
1391 	int ret;
1392 
1393 	mutex_lock(&data->mutex);
1394 	ret = bu27034_meas_set(data, true);
1395 	if (ret)
1396 		goto unlock_out;
1397 
1398 	task = kthread_run(bu27034_buffer_thread, idev,
1399 				 "bu27034-buffering-%u",
1400 				 iio_device_id(idev));
1401 	if (IS_ERR(task)) {
1402 		ret = PTR_ERR(task);
1403 		goto unlock_out;
1404 	}
1405 
1406 	data->task = task;
1407 
1408 unlock_out:
1409 	mutex_unlock(&data->mutex);
1410 
1411 	return ret;
1412 }
1413 
1414 static int bu27034_buffer_disable(struct iio_dev *idev)
1415 {
1416 	struct bu27034_data *data = iio_priv(idev);
1417 	int ret;
1418 
1419 	mutex_lock(&data->mutex);
1420 	if (data->task) {
1421 		kthread_stop(data->task);
1422 		data->task = NULL;
1423 	}
1424 
1425 	ret = bu27034_meas_set(data, false);
1426 	mutex_unlock(&data->mutex);
1427 
1428 	return ret;
1429 }
1430 
1431 static const struct iio_buffer_setup_ops bu27034_buffer_ops = {
1432 	.postenable = &bu27034_buffer_enable,
1433 	.predisable = &bu27034_buffer_disable,
1434 };
1435 
1436 static int bu27034_probe(struct i2c_client *i2c)
1437 {
1438 	struct device *dev = &i2c->dev;
1439 	struct bu27034_data *data;
1440 	struct regmap *regmap;
1441 	struct iio_dev *idev;
1442 	unsigned int part_id, reg;
1443 	int ret;
1444 
1445 	regmap = devm_regmap_init_i2c(i2c, &bu27034_regmap);
1446 	if (IS_ERR(regmap))
1447 		return dev_err_probe(dev, PTR_ERR(regmap),
1448 				     "Failed to initialize Regmap\n");
1449 
1450 	idev = devm_iio_device_alloc(dev, sizeof(*data));
1451 	if (!idev)
1452 		return -ENOMEM;
1453 
1454 	ret = devm_regulator_get_enable(dev, "vdd");
1455 	if (ret)
1456 		return dev_err_probe(dev, ret, "Failed to get regulator\n");
1457 
1458 	data = iio_priv(idev);
1459 
1460 	ret = regmap_read(regmap, BU27034_REG_SYSTEM_CONTROL, &reg);
1461 	if (ret)
1462 		return dev_err_probe(dev, ret, "Failed to access sensor\n");
1463 
1464 	part_id = FIELD_GET(BU27034_MASK_PART_ID, reg);
1465 
1466 	if (part_id != BU27034_ID)
1467 		dev_warn(dev, "unknown device 0x%x\n", part_id);
1468 
1469 	ret = devm_iio_init_iio_gts(dev, BU27034_SCALE_1X, 0, bu27034_gains,
1470 				    ARRAY_SIZE(bu27034_gains), bu27034_itimes,
1471 				    ARRAY_SIZE(bu27034_itimes), &data->gts);
1472 	if (ret)
1473 		return ret;
1474 
1475 	mutex_init(&data->mutex);
1476 	data->regmap = regmap;
1477 	data->dev = dev;
1478 
1479 	idev->channels = bu27034_channels;
1480 	idev->num_channels = ARRAY_SIZE(bu27034_channels);
1481 	idev->name = "bu27034";
1482 	idev->info = &bu27034_info;
1483 
1484 	idev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
1485 	idev->available_scan_masks = bu27034_scan_masks;
1486 
1487 	ret = bu27034_chip_init(data);
1488 	if (ret)
1489 		return ret;
1490 
1491 	ret = devm_iio_kfifo_buffer_setup(dev, idev, &bu27034_buffer_ops);
1492 	if (ret)
1493 		return dev_err_probe(dev, ret, "buffer setup failed\n");
1494 
1495 	ret = devm_iio_device_register(dev, idev);
1496 	if (ret < 0)
1497 		return dev_err_probe(dev, ret,
1498 				     "Unable to register iio device\n");
1499 
1500 	return ret;
1501 }
1502 
1503 static const struct of_device_id bu27034_of_match[] = {
1504 	{ .compatible = "rohm,bu27034" },
1505 	{ }
1506 };
1507 MODULE_DEVICE_TABLE(of, bu27034_of_match);
1508 
1509 static struct i2c_driver bu27034_i2c_driver = {
1510 	.driver = {
1511 		.name = "bu27034-als",
1512 		.of_match_table = bu27034_of_match,
1513 		.probe_type = PROBE_PREFER_ASYNCHRONOUS,
1514 	},
1515 	.probe = bu27034_probe,
1516 };
1517 module_i2c_driver(bu27034_i2c_driver);
1518 
1519 MODULE_LICENSE("GPL");
1520 MODULE_AUTHOR("Matti Vaittinen <matti.vaittinen@fi.rohmeurope.com>");
1521 MODULE_DESCRIPTION("ROHM BU27034 ambient light sensor driver");
1522 MODULE_IMPORT_NS(IIO_GTS_HELPER);
1523