usb: typec: mux: fix static inline syntax error
[platform/kernel/linux-starfive.git] / drivers / iio / light / rohm-bu27034.c
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 struct bu27034_result {
227         u16 ch0;
228         u16 ch1;
229         u16 ch2;
230 };
231
232 static const struct regmap_range bu27034_volatile_ranges[] = {
233         {
234                 .range_min = BU27034_REG_MODE_CONTROL4,
235                 .range_max = BU27034_REG_MODE_CONTROL4,
236         }, {
237                 .range_min = BU27034_REG_DATA0_LO,
238                 .range_max = BU27034_REG_DATA2_HI,
239         },
240 };
241
242 static const struct regmap_access_table bu27034_volatile_regs = {
243         .yes_ranges = &bu27034_volatile_ranges[0],
244         .n_yes_ranges = ARRAY_SIZE(bu27034_volatile_ranges),
245 };
246
247 static const struct regmap_range bu27034_read_only_ranges[] = {
248         {
249                 .range_min = BU27034_REG_DATA0_LO,
250                 .range_max = BU27034_REG_DATA2_HI,
251         }, {
252                 .range_min = BU27034_REG_MANUFACTURER_ID,
253                 .range_max = BU27034_REG_MANUFACTURER_ID,
254         }
255 };
256
257 static const struct regmap_access_table bu27034_ro_regs = {
258         .no_ranges = &bu27034_read_only_ranges[0],
259         .n_no_ranges = ARRAY_SIZE(bu27034_read_only_ranges),
260 };
261
262 static const struct regmap_config bu27034_regmap = {
263         .reg_bits = 8,
264         .val_bits = 8,
265         .max_register = BU27034_REG_MAX,
266         .cache_type = REGCACHE_RBTREE,
267         .volatile_table = &bu27034_volatile_regs,
268         .wr_table = &bu27034_ro_regs,
269 };
270
271 struct bu27034_gain_check {
272         int old_gain;
273         int new_gain;
274         int chan;
275 };
276
277 static int bu27034_get_gain_sel(struct bu27034_data *data, int chan)
278 {
279         int ret, val;
280
281         switch (chan) {
282         case BU27034_CHAN_DATA0:
283         case BU27034_CHAN_DATA1:
284         {
285                 int reg[] = {
286                         [BU27034_CHAN_DATA0] = BU27034_REG_MODE_CONTROL2,
287                         [BU27034_CHAN_DATA1] = BU27034_REG_MODE_CONTROL3,
288                 };
289                 ret = regmap_read(data->regmap, reg[chan], &val);
290                 if (ret)
291                         return ret;
292
293                 return FIELD_GET(BU27034_MASK_D01_GAIN, val);
294         }
295         case BU27034_CHAN_DATA2:
296         {
297                 int d2_lo_bits = fls(BU27034_MASK_D2_GAIN_LO);
298
299                 ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL2, &val);
300                 if (ret)
301                         return ret;
302
303                 /*
304                  * The data2 channel gain is composed by 5 non continuous bits
305                  * [7:6], [2:0]. Thus when we combine the 5-bit 'selector'
306                  * from register value we must right shift the high bits by 3.
307                  */
308                 return FIELD_GET(BU27034_MASK_D2_GAIN_HI, val) << d2_lo_bits |
309                        FIELD_GET(BU27034_MASK_D2_GAIN_LO, val);
310         }
311         default:
312                 return -EINVAL;
313         }
314 }
315
316 static int bu27034_get_gain(struct bu27034_data *data, int chan, int *gain)
317 {
318         int ret, sel;
319
320         ret = bu27034_get_gain_sel(data, chan);
321         if (ret < 0)
322                 return ret;
323
324         sel = ret;
325
326         ret = iio_gts_find_gain_by_sel(&data->gts, sel);
327         if (ret < 0) {
328                 dev_err(data->dev, "chan %u: unknown gain value 0x%x\n", chan,
329                         sel);
330
331                 return ret;
332         }
333
334         *gain = ret;
335
336         return 0;
337 }
338
339 static int bu27034_get_int_time(struct bu27034_data *data)
340 {
341         int ret, sel;
342
343         ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &sel);
344         if (ret)
345                 return ret;
346
347         return iio_gts_find_int_time_by_sel(&data->gts,
348                                             sel & BU27034_MASK_MEAS_MODE);
349 }
350
351 static int _bu27034_get_scale(struct bu27034_data *data, int channel, int *val,
352                               int *val2)
353 {
354         int gain, ret;
355
356         ret = bu27034_get_gain(data, channel, &gain);
357         if (ret)
358                 return ret;
359
360         ret = bu27034_get_int_time(data);
361         if (ret < 0)
362                 return ret;
363
364         return iio_gts_get_scale(&data->gts, gain, ret, val, val2);
365 }
366
367 static int bu27034_get_scale(struct bu27034_data *data, int channel, int *val,
368                               int *val2)
369 {
370         int ret;
371
372         if (channel == BU27034_CHAN_ALS) {
373                 *val = 0;
374                 *val2 = 1000;
375                 return IIO_VAL_INT_PLUS_MICRO;
376         }
377
378         mutex_lock(&data->mutex);
379         ret = _bu27034_get_scale(data, channel, val, val2);
380         mutex_unlock(&data->mutex);
381         if (ret)
382                 return ret;
383
384         return IIO_VAL_INT_PLUS_NANO;
385 }
386
387 /* Caller should hold the lock to protect lux reading */
388 static int bu27034_write_gain_sel(struct bu27034_data *data, int chan, int sel)
389 {
390         static const int reg[] = {
391                 [BU27034_CHAN_DATA0] = BU27034_REG_MODE_CONTROL2,
392                 [BU27034_CHAN_DATA1] = BU27034_REG_MODE_CONTROL3,
393         };
394         int mask, val;
395
396         if (chan != BU27034_CHAN_DATA0 && chan != BU27034_CHAN_DATA1)
397                 return -EINVAL;
398
399         val = FIELD_PREP(BU27034_MASK_D01_GAIN, sel);
400
401         mask = BU27034_MASK_D01_GAIN;
402
403         if (chan == BU27034_CHAN_DATA0) {
404                 /*
405                  * We keep the same gain for channel 2 as we set for channel 0
406                  * We can't allow them to be individually controlled because
407                  * setting one will impact also the other. Also, if we don't
408                  * always update both gains we may result unsupported bit
409                  * combinations.
410                  *
411                  * This is not nice but this is yet another place where the
412                  * user space must be prepared to surprizes. Namely, see chan 2
413                  * gain changed when chan 0 gain is changed.
414                  *
415                  * This is not fatal for most users though. I don't expect the
416                  * channel 2 to be used in any generic cases - the intensity
417                  * values provided by the sensor for IR area are not openly
418                  * documented. Also, channel 2 is not used for visible light.
419                  *
420                  * So, if there is application which is written to utilize the
421                  * channel 2 - then it is probably specifically targeted to this
422                  * sensor and knows how to utilize those values. It is safe to
423                  * hope such user can also cope with the gain changes.
424                  */
425                 mask |=  BU27034_MASK_D2_GAIN_LO;
426
427                 /*
428                  * The D2 gain bits are directly the lowest bits of selector.
429                  * Just do add those bits to the value
430                  */
431                 val |= sel & BU27034_MASK_D2_GAIN_LO;
432         }
433
434         return regmap_update_bits(data->regmap, reg[chan], mask, val);
435 }
436
437 static int bu27034_set_gain(struct bu27034_data *data, int chan, int gain)
438 {
439         int ret;
440
441         /*
442          * We don't allow setting channel 2 gain as it messes up the
443          * gain for channel 0 - which shares the high bits
444          */
445         if (chan != BU27034_CHAN_DATA0 && chan != BU27034_CHAN_DATA1)
446                 return -EINVAL;
447
448         ret = iio_gts_find_sel_by_gain(&data->gts, gain);
449         if (ret < 0)
450                 return ret;
451
452         return bu27034_write_gain_sel(data, chan, ret);
453 }
454
455 /* Caller should hold the lock to protect data->int_time */
456 static int bu27034_set_int_time(struct bu27034_data *data, int time)
457 {
458         int ret;
459
460         ret = iio_gts_find_sel_by_int_time(&data->gts, time);
461         if (ret < 0)
462                 return ret;
463
464         return regmap_update_bits(data->regmap, BU27034_REG_MODE_CONTROL1,
465                                  BU27034_MASK_MEAS_MODE, ret);
466 }
467
468 /*
469  * We try to change the time in such way that the scale is maintained for
470  * given channels by adjusting gain so that it compensates the time change.
471  */
472 static int bu27034_try_set_int_time(struct bu27034_data *data, int time_us)
473 {
474         struct bu27034_gain_check gains[] = {
475                 { .chan = BU27034_CHAN_DATA0 },
476                 { .chan = BU27034_CHAN_DATA1 },
477         };
478         int numg = ARRAY_SIZE(gains);
479         int ret, int_time_old, i;
480
481         mutex_lock(&data->mutex);
482         ret = bu27034_get_int_time(data);
483         if (ret < 0)
484                 goto unlock_out;
485
486         int_time_old = ret;
487
488         if (!iio_gts_valid_time(&data->gts, time_us)) {
489                 dev_err(data->dev, "Unsupported integration time %u\n",
490                         time_us);
491                 ret = -EINVAL;
492
493                 goto unlock_out;
494         }
495
496         if (time_us == int_time_old) {
497                 ret = 0;
498                 goto unlock_out;
499         }
500
501         for (i = 0; i < numg; i++) {
502                 ret = bu27034_get_gain(data, gains[i].chan, &gains[i].old_gain);
503                 if (ret)
504                         goto unlock_out;
505
506                 ret = iio_gts_find_new_gain_by_old_gain_time(&data->gts,
507                                                              gains[i].old_gain,
508                                                              int_time_old, time_us,
509                                                              &gains[i].new_gain);
510                 if (ret) {
511                         int scale1, scale2;
512                         bool ok;
513
514                         _bu27034_get_scale(data, gains[i].chan, &scale1, &scale2);
515                         dev_dbg(data->dev,
516                                 "chan %u, can't support time %u with scale %u %u\n",
517                                 gains[i].chan, time_us, scale1, scale2);
518
519                         if (gains[i].new_gain < 0)
520                                 goto unlock_out;
521
522                         /*
523                          * If caller requests for integration time change and we
524                          * can't support the scale - then the caller should be
525                          * prepared to 'pick up the pieces and deal with the
526                          * fact that the scale changed'.
527                          */
528                         ret = iio_find_closest_gain_low(&data->gts,
529                                                         gains[i].new_gain, &ok);
530
531                         if (!ok)
532                                 dev_dbg(data->dev,
533                                         "optimal gain out of range for chan %u\n",
534                                         gains[i].chan);
535
536                         if (ret < 0) {
537                                 dev_dbg(data->dev,
538                                          "Total gain increase. Risk of saturation");
539                                 ret = iio_gts_get_min_gain(&data->gts);
540                                 if (ret < 0)
541                                         goto unlock_out;
542                         }
543                         dev_dbg(data->dev, "chan %u scale changed\n",
544                                  gains[i].chan);
545                         gains[i].new_gain = ret;
546                         dev_dbg(data->dev, "chan %u new gain %u\n",
547                                 gains[i].chan, gains[i].new_gain);
548                 }
549         }
550
551         for (i = 0; i < numg; i++) {
552                 ret = bu27034_set_gain(data, gains[i].chan, gains[i].new_gain);
553                 if (ret)
554                         goto unlock_out;
555         }
556
557         ret = bu27034_set_int_time(data, time_us);
558
559 unlock_out:
560         mutex_unlock(&data->mutex);
561
562         return ret;
563 }
564
565 static int bu27034_set_scale(struct bu27034_data *data, int chan,
566                             int val, int val2)
567 {
568         int ret, time_sel, gain_sel, i;
569         bool found = false;
570
571         if (chan == BU27034_CHAN_DATA2)
572                 return -EINVAL;
573
574         if (chan == BU27034_CHAN_ALS) {
575                 if (val == 0 && val2 == 1000)
576                         return 0;
577
578                 return -EINVAL;
579         }
580
581         mutex_lock(&data->mutex);
582         ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &time_sel);
583         if (ret)
584                 goto unlock_out;
585
586         ret = iio_gts_find_gain_sel_for_scale_using_time(&data->gts, time_sel,
587                                                 val, val2 * 1000, &gain_sel);
588         if (ret) {
589                 /*
590                  * Could not support scale with given time. Need to change time.
591                  * We still want to maintain the scale for all channels
592                  */
593                 struct bu27034_gain_check gain;
594                 int new_time_sel;
595
596                 /*
597                  * Populate information for the other channel which should also
598                  * maintain the scale. (Due to the HW limitations the chan2
599                  * gets the same gain as chan0, so we only need to explicitly
600                  * set the chan 0 and 1).
601                  */
602                 if (chan == BU27034_CHAN_DATA0)
603                         gain.chan = BU27034_CHAN_DATA1;
604                 else if (chan == BU27034_CHAN_DATA1)
605                         gain.chan = BU27034_CHAN_DATA0;
606
607                 ret = bu27034_get_gain(data, gain.chan, &gain.old_gain);
608                 if (ret)
609                         goto unlock_out;
610
611                 /*
612                  * Iterate through all the times to see if we find one which
613                  * can support requested scale for requested channel, while
614                  * maintaining the scale for other channels
615                  */
616                 for (i = 0; i < data->gts.num_itime; i++) {
617                         new_time_sel = data->gts.itime_table[i].sel;
618
619                         if (new_time_sel == time_sel)
620                                 continue;
621
622                         /* Can we provide requested scale with this time? */
623                         ret = iio_gts_find_gain_sel_for_scale_using_time(
624                                 &data->gts, new_time_sel, val, val2 * 1000,
625                                 &gain_sel);
626                         if (ret)
627                                 continue;
628
629                         /* Can the other channel(s) maintain scale? */
630                         ret = iio_gts_find_new_gain_sel_by_old_gain_time(
631                                 &data->gts, gain.old_gain, time_sel,
632                                 new_time_sel, &gain.new_gain);
633                         if (!ret) {
634                                 /* Yes - we found suitable time */
635                                 found = true;
636                                 break;
637                         }
638                 }
639                 if (!found) {
640                         dev_dbg(data->dev,
641                                 "Can't set scale maintaining other channels\n");
642                         ret = -EINVAL;
643
644                         goto unlock_out;
645                 }
646
647                 ret = bu27034_set_gain(data, gain.chan, gain.new_gain);
648                 if (ret)
649                         goto unlock_out;
650
651                 ret = regmap_update_bits(data->regmap, BU27034_REG_MODE_CONTROL1,
652                                   BU27034_MASK_MEAS_MODE, new_time_sel);
653                 if (ret)
654                         goto unlock_out;
655         }
656
657         ret = bu27034_write_gain_sel(data, chan, gain_sel);
658 unlock_out:
659         mutex_unlock(&data->mutex);
660
661         return ret;
662 }
663
664 /*
665  * for (D1/D0 < 0.87):
666  * lx = 0.004521097 * D1 - 0.002663996 * D0 +
667  *      0.00012213 * D1 * D1 / D0
668  *
669  * =>   115.7400832 * ch1 / gain1 / mt -
670  *      68.1982976 * ch0 / gain0 / mt +
671  *      0.00012213 * 25600 * (ch1 / gain1 / mt) * 25600 *
672  *      (ch1 /gain1 / mt) / (25600 * ch0 / gain0 / mt)
673  *
674  * A =  0.00012213 * 25600 * (ch1 /gain1 / mt) * 25600 *
675  *      (ch1 /gain1 / mt) / (25600 * ch0 / gain0 / mt)
676  * =>   0.00012213 * 25600 * (ch1 /gain1 / mt) *
677  *      (ch1 /gain1 / mt) / (ch0 / gain0 / mt)
678  * =>   0.00012213 * 25600 * (ch1 / gain1) * (ch1 /gain1 / mt) /
679  *      (ch0 / gain0)
680  * =>   0.00012213 * 25600 * (ch1 / gain1) * (ch1 /gain1 / mt) *
681  *      gain0 / ch0
682  * =>   3.126528 * ch1 * ch1 * gain0 / gain1 / gain1 / mt /ch0
683  *
684  * lx = (115.7400832 * ch1 / gain1 - 68.1982976 * ch0 / gain0) /
685  *      mt + A
686  * =>   (115.7400832 * ch1 / gain1 - 68.1982976 * ch0 / gain0) /
687  *      mt + 3.126528 * ch1 * ch1 * gain0 / gain1 / gain1 / mt /
688  *      ch0
689  *
690  * =>   (115.7400832 * ch1 / gain1 - 68.1982976 * ch0 / gain0 +
691  *        3.126528 * ch1 * ch1 * gain0 / gain1 / gain1 / ch0) /
692  *        mt
693  *
694  * For (0.87 <= D1/D0 < 1.00)
695  * lx = (0.001331* D0 + 0.0000354 * D1) * ((D1/D0 â€“ 0.87) * (0.385) + 1)
696  * =>   (0.001331 * 256 * 100 * ch0 / gain0 / mt + 0.0000354 * 256 *
697  *      100 * ch1 / gain1 / mt) * ((D1/D0 -  0.87) * (0.385) + 1)
698  * =>   (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
699  *      ((D1/D0 -  0.87) * (0.385) + 1)
700  * =>   (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
701  *      (0.385 * D1/D0 - 0.66505)
702  * =>   (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
703  *      (0.385 * 256 * 100 * ch1 / gain1 / mt / (256 * 100 * ch0 / gain0 / mt) - 0.66505)
704  * =>   (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
705  *      (9856 * ch1 / gain1 / mt / (25600 * ch0 / gain0 / mt) + 0.66505)
706  * =>   13.118336 * ch1 / (gain1 * mt)
707  *      + 22.66064768 * ch0 / (gain0 * mt)
708  *      + 8931.90144 * ch1 * ch1 * gain0 /
709  *        (25600 * ch0 * gain1 * gain1 * mt)
710  *      + 0.602694912 * ch1 / (gain1 * mt)
711  *
712  * =>   [0.3489024 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1)
713  *       + 22.66064768 * ch0 / gain0
714  *       + 13.721030912 * ch1 / gain1
715  *      ] / mt
716  *
717  * For (D1/D0 >= 1.00)
718  *
719  * lx   = (0.001331* D0 + 0.0000354 * D1) * ((D1/D0 â€“ 2.0) * (-0.05) + 1)
720  *      => (0.001331* D0 + 0.0000354 * D1) * (-0.05D1/D0 + 1.1)
721  *      => (0.001331 * 256 * 100 * ch0 / gain0 / mt + 0.0000354 * 256 *
722  *         100 * ch1 / gain1 / mt) * (-0.05D1/D0 + 1.1)
723  *      => (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
724  *         (-0.05 * 256 * 100 * ch1 / gain1 / mt / (256 * 100 * ch0 / gain0 / mt) + 1.1)
725  *      => (34.0736 * ch0 / gain0 / mt + 0.90624 * ch1 / gain1 / mt) *
726  *         (-1280 * ch1 / (gain1 * mt * 25600 * ch0 / gain0 / mt) + 1.1)
727  *      => (34.0736 * ch0 * -1280 * ch1 * gain0 * mt /( gain0 * mt * gain1 * mt * 25600 * ch0)
728  *          + 34.0736 * 1.1 * ch0 / (gain0 * mt)
729  *          + 0.90624 * ch1 * -1280 * ch1 *gain0 * mt / (gain1 * mt *gain1 * mt * 25600 * ch0)
730  *          + 1.1 * 0.90624 * ch1 / (gain1 * mt)
731  *      => -43614.208 * ch1 / (gain1 * mt * 25600)
732  *          + 37.48096  ch0 / (gain0 * mt)
733  *          - 1159.9872 * ch1 * ch1 * gain0 / (gain1 * gain1 * mt * 25600 * ch0)
734  *          + 0.996864 ch1 / (gain1 * mt)
735  *      => [
736  *              - 0.045312 * ch1 * ch1 * gain0 / (gain1 * gain1 * ch0)
737  *              - 0.706816 * ch1 / gain1
738  *              + 37.48096  ch0 /gain0
739  *         ] * mt
740  *
741  *
742  * So, the first case (D1/D0 < 0.87) can be computed to a form:
743  *
744  * lx = (3.126528 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
745  *       115.7400832 * ch1 / gain1 +
746  *      -68.1982976 * ch0 / gain0
747  *       / mt
748  *
749  * Second case (0.87 <= D1/D0 < 1.00) goes to form:
750  *
751  *      => [0.3489024 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
752  *          13.721030912 * ch1 / gain1 +
753  *          22.66064768 * ch0 / gain0
754  *         ] / mt
755  *
756  * Third case (D1/D0 >= 1.00) goes to form:
757  *      => [-0.045312 * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
758  *          -0.706816 * ch1 / gain1 +
759  *          37.48096  ch0 /(gain0
760  *         ] / mt
761  *
762  * This can be unified to format:
763  * lx = [
764  *       A * ch1 * ch1 * gain0 / (ch0 * gain1 * gain1) +
765  *       B * ch1 / gain1 +
766  *       C * ch0 / gain0
767  *      ] / mt
768  *
769  * For case 1:
770  * A = 3.126528,
771  * B = 115.7400832
772  * C = -68.1982976
773  *
774  * For case 2:
775  * A = 0.3489024
776  * B = 13.721030912
777  * C = 22.66064768
778  *
779  * For case 3:
780  * A = -0.045312
781  * B = -0.706816
782  * C = 37.48096
783  */
784
785 struct bu27034_lx_coeff {
786         unsigned int A;
787         unsigned int B;
788         unsigned int C;
789         /* Indicate which of the coefficients above are negative */
790         bool is_neg[3];
791 };
792
793 static inline u64 gain_mul_div_helper(u64 val, unsigned int gain,
794                                       unsigned int div)
795 {
796         /*
797          * Max gain for a channel is 4096. The max u64 (0xffffffffffffffffULL)
798          * divided by 4096 is 0xFFFFFFFFFFFFF (GENMASK_ULL(51, 0)) (floored).
799          * Thus, the 0xFFFFFFFFFFFFF is the largest value we can safely multiply
800          * with the gain, no matter what gain is set.
801          *
802          * So, multiplication with max gain may overflow if val is greater than
803          * 0xFFFFFFFFFFFFF (52 bits set)..
804          *
805          * If this is the case we divide first.
806          */
807         if (val < GENMASK_ULL(51, 0)) {
808                 val *= gain;
809                 do_div(val, div);
810         } else {
811                 do_div(val, div);
812                 val *= gain;
813         }
814
815         return val;
816 }
817
818 static u64 bu27034_fixp_calc_t1_64bit(unsigned int coeff, unsigned int ch0,
819                                       unsigned int ch1, unsigned int gain0,
820                                       unsigned int gain1)
821 {
822         unsigned int helper;
823         u64 helper64;
824
825         helper64 = (u64)coeff * (u64)ch1 * (u64)ch1;
826
827         helper = gain1 * gain1;
828         if (helper > ch0) {
829                 do_div(helper64, helper);
830
831                 return gain_mul_div_helper(helper64, gain0, ch0);
832         }
833
834         do_div(helper64, ch0);
835
836         return gain_mul_div_helper(helper64, gain0, helper);
837
838 }
839
840 static u64 bu27034_fixp_calc_t1(unsigned int coeff, unsigned int ch0,
841                                 unsigned int ch1, unsigned int gain0,
842                                 unsigned int gain1)
843 {
844         unsigned int helper, tmp;
845
846         /*
847          * Here we could overflow even the 64bit value. Hence we
848          * multiply with gain0 only after the divisions - even though
849          * it may result loss of accuracy
850          */
851         helper = coeff * ch1 * ch1;
852         tmp = helper * gain0;
853
854         helper = ch1 * ch1;
855
856         if (check_mul_overflow(helper, coeff, &helper))
857                 return bu27034_fixp_calc_t1_64bit(coeff, ch0, ch1, gain0, gain1);
858
859         if (check_mul_overflow(helper, gain0, &tmp))
860                 return bu27034_fixp_calc_t1_64bit(coeff, ch0, ch1, gain0, gain1);
861
862         return tmp / (gain1 * gain1) / ch0;
863
864 }
865
866 static u64 bu27034_fixp_calc_t23(unsigned int coeff, unsigned int ch,
867                                  unsigned int gain)
868 {
869         unsigned int helper;
870         u64 helper64;
871
872         if (!check_mul_overflow(coeff, ch, &helper))
873                 return helper / gain;
874
875         helper64 = (u64)coeff * (u64)ch;
876         do_div(helper64, gain);
877
878         return helper64;
879 }
880
881 static int bu27034_fixp_calc_lx(unsigned int ch0, unsigned int ch1,
882                                 unsigned int gain0, unsigned int gain1,
883                                 unsigned int meastime, int coeff_idx)
884 {
885         static const struct bu27034_lx_coeff coeff[] = {
886                 {
887                         .A = 31265280,          /* 3.126528 */
888                         .B = 1157400832,        /*115.7400832 */
889                         .C = 681982976,         /* -68.1982976 */
890                         .is_neg = {false, false, true},
891                 }, {
892                         .A = 3489024,           /* 0.3489024 */
893                         .B = 137210309,         /* 13.721030912 */
894                         .C = 226606476,         /* 22.66064768 */
895                         /* All terms positive */
896                 }, {
897                         .A = 453120,            /* -0.045312 */
898                         .B = 7068160,           /* -0.706816 */
899                         .C = 374809600,         /* 37.48096 */
900                         .is_neg = {true, true, false},
901                 }
902         };
903         const struct bu27034_lx_coeff *c = &coeff[coeff_idx];
904         u64 res = 0, terms[3];
905         int i;
906
907         if (coeff_idx >= ARRAY_SIZE(coeff))
908                 return -EINVAL;
909
910         terms[0] = bu27034_fixp_calc_t1(c->A, ch0, ch1, gain0, gain1);
911         terms[1] = bu27034_fixp_calc_t23(c->B, ch1, gain1);
912         terms[2] = bu27034_fixp_calc_t23(c->C, ch0, gain0);
913
914         /* First, add positive terms */
915         for (i = 0; i < 3; i++)
916                 if (!c->is_neg[i])
917                         res += terms[i];
918
919         /* No positive term => zero lux */
920         if (!res)
921                 return 0;
922
923         /* Then, subtract negative terms (if any) */
924         for (i = 0; i < 3; i++)
925                 if (c->is_neg[i]) {
926                         /*
927                          * If the negative term is greater than positive - then
928                          * the darkness has taken over and we are all doomed! Eh,
929                          * I mean, then we can just return 0 lx and go out
930                          */
931                         if (terms[i] >= res)
932                                 return 0;
933
934                         res -= terms[i];
935                 }
936
937         meastime *= 10;
938         do_div(res, meastime);
939
940         return (int) res;
941 }
942
943 static bool bu27034_has_valid_sample(struct bu27034_data *data)
944 {
945         int ret, val;
946
947         ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL4, &val);
948         if (ret) {
949                 dev_err(data->dev, "Read failed %d\n", ret);
950
951                 return false;
952         }
953
954         return val & BU27034_MASK_VALID;
955 }
956
957 /*
958  * Reading the register where VALID bit is clears this bit. (So does changing
959  * any gain / integration time configuration registers) The bit gets
960  * set when we have acquired new data. We use this bit to indicate data
961  * validity.
962  */
963 static void bu27034_invalidate_read_data(struct bu27034_data *data)
964 {
965         bu27034_has_valid_sample(data);
966 }
967
968 static int bu27034_read_result(struct bu27034_data *data, int chan, int *res)
969 {
970         int reg[] = {
971                 [BU27034_CHAN_DATA0] = BU27034_REG_DATA0_LO,
972                 [BU27034_CHAN_DATA1] = BU27034_REG_DATA1_LO,
973                 [BU27034_CHAN_DATA2] = BU27034_REG_DATA2_LO,
974         };
975         int valid, ret;
976         __le16 val;
977
978         ret = regmap_read_poll_timeout(data->regmap, BU27034_REG_MODE_CONTROL4,
979                                        valid, (valid & BU27034_MASK_VALID),
980                                        BU27034_DATA_WAIT_TIME_US, 0);
981         if (ret)
982                 return ret;
983
984         ret = regmap_bulk_read(data->regmap, reg[chan], &val, sizeof(val));
985         if (ret)
986                 return ret;
987
988         *res = le16_to_cpu(val);
989
990         return 0;
991 }
992
993 static int bu27034_get_result_unlocked(struct bu27034_data *data, __le16 *res,
994                                        int size)
995 {
996         int ret = 0, retry_cnt = 0;
997
998 retry:
999         /* Get new value from sensor if data is ready */
1000         if (bu27034_has_valid_sample(data)) {
1001                 ret = regmap_bulk_read(data->regmap, BU27034_REG_DATA0_LO,
1002                                        res, size);
1003                 if (ret)
1004                         return ret;
1005
1006                 bu27034_invalidate_read_data(data);
1007         } else {
1008                 /* No new data in sensor. Wait and retry */
1009                 retry_cnt++;
1010
1011                 if (retry_cnt > BU27034_RETRY_LIMIT) {
1012                         dev_err(data->dev, "No data from sensor\n");
1013
1014                         return -ETIMEDOUT;
1015                 }
1016
1017                 msleep(25);
1018
1019                 goto retry;
1020         }
1021
1022         return ret;
1023 }
1024
1025 static int bu27034_meas_set(struct bu27034_data *data, bool en)
1026 {
1027         if (en)
1028                 return regmap_set_bits(data->regmap, BU27034_REG_MODE_CONTROL4,
1029                                        BU27034_MASK_MEAS_EN);
1030
1031         return regmap_clear_bits(data->regmap, BU27034_REG_MODE_CONTROL4,
1032                                  BU27034_MASK_MEAS_EN);
1033 }
1034
1035 static int bu27034_get_single_result(struct bu27034_data *data, int chan,
1036                                      int *val)
1037 {
1038         int ret;
1039
1040         if (chan < BU27034_CHAN_DATA0 || chan > BU27034_CHAN_DATA2)
1041                 return -EINVAL;
1042
1043         ret = bu27034_meas_set(data, true);
1044         if (ret)
1045                 return ret;
1046
1047         ret = bu27034_get_int_time(data);
1048         if (ret < 0)
1049                 return ret;
1050
1051         msleep(ret / 1000);
1052
1053         return bu27034_read_result(data, chan, val);
1054 }
1055
1056 /*
1057  * The formula given by vendor for computing luxes out of data0 and data1
1058  * (in open air) is as follows:
1059  *
1060  * Let's mark:
1061  * D0 = data0/ch0_gain/meas_time_ms * 25600
1062  * D1 = data1/ch1_gain/meas_time_ms * 25600
1063  *
1064  * Then:
1065  * if (D1/D0 < 0.87)
1066  *      lx = (0.001331 * D0 + 0.0000354 * D1) * ((D1 / D0 - 0.87) * 3.45 + 1)
1067  * else if (D1/D0 < 1)
1068  *      lx = (0.001331 * D0 + 0.0000354 * D1) * ((D1 / D0 - 0.87) * 0.385 + 1)
1069  * else
1070  *      lx = (0.001331 * D0 + 0.0000354 * D1) * ((D1 / D0 - 2) * -0.05 + 1)
1071  *
1072  * We use it here. Users who have for example some colored lens
1073  * need to modify the calculation but I hope this gives a starting point for
1074  * those working with such devices.
1075  */
1076
1077 static int bu27034_calc_mlux(struct bu27034_data *data, __le16 *res, int *val)
1078 {
1079         unsigned int gain0, gain1, meastime;
1080         unsigned int d1_d0_ratio_scaled;
1081         u16 ch0, ch1;
1082         u64 helper64;
1083         int ret;
1084
1085         /*
1086          * We return 0 lux if calculation fails. This should be reasonably
1087          * easy to spot from the buffers especially if raw-data channels show
1088          * valid values
1089          */
1090         *val = 0;
1091
1092         ch0 = max_t(u16, 1, le16_to_cpu(res[0]));
1093         ch1 = max_t(u16, 1, le16_to_cpu(res[1]));
1094
1095         ret = bu27034_get_gain(data, BU27034_CHAN_DATA0, &gain0);
1096         if (ret)
1097                 return ret;
1098
1099         ret = bu27034_get_gain(data, BU27034_CHAN_DATA1, &gain1);
1100         if (ret)
1101                 return ret;
1102
1103         ret = bu27034_get_int_time(data);
1104         if (ret < 0)
1105                 return ret;
1106
1107         meastime = ret;
1108
1109         d1_d0_ratio_scaled = (unsigned int)ch1 * (unsigned int)gain0 * 100;
1110         helper64 = (u64)ch1 * (u64)gain0 * 100LLU;
1111
1112         if (helper64 != d1_d0_ratio_scaled) {
1113                 unsigned int div = (unsigned int)ch0 * gain1;
1114
1115                 do_div(helper64, div);
1116                 d1_d0_ratio_scaled = helper64;
1117         } else {
1118                 d1_d0_ratio_scaled /= ch0 * gain1;
1119         }
1120
1121         if (d1_d0_ratio_scaled < 87)
1122                 ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 0);
1123         else if (d1_d0_ratio_scaled < 100)
1124                 ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 1);
1125         else
1126                 ret = bu27034_fixp_calc_lx(ch0, ch1, gain0, gain1, meastime, 2);
1127
1128         if (ret < 0)
1129                 return ret;
1130
1131         *val = ret;
1132
1133         return 0;
1134
1135 }
1136
1137 static int bu27034_get_mlux(struct bu27034_data *data, int chan, int *val)
1138 {
1139         __le16 res[3];
1140         int ret;
1141
1142         ret = bu27034_meas_set(data, true);
1143         if (ret)
1144                 return ret;
1145
1146         ret = bu27034_get_result_unlocked(data, &res[0], sizeof(res));
1147         if (ret)
1148                 return ret;
1149
1150         ret = bu27034_calc_mlux(data, res, val);
1151         if (ret)
1152                 return ret;
1153
1154         ret = bu27034_meas_set(data, false);
1155         if (ret)
1156                 dev_err(data->dev, "failed to disable measurement\n");
1157
1158         return 0;
1159 }
1160
1161 static int bu27034_read_raw(struct iio_dev *idev,
1162                            struct iio_chan_spec const *chan,
1163                            int *val, int *val2, long mask)
1164 {
1165         struct bu27034_data *data = iio_priv(idev);
1166         int ret;
1167
1168         switch (mask) {
1169         case IIO_CHAN_INFO_INT_TIME:
1170                 *val = bu27034_get_int_time(data);
1171                 if (*val < 0)
1172                         return *val;
1173
1174                 return IIO_VAL_INT;
1175
1176         case IIO_CHAN_INFO_SCALE:
1177                 return bu27034_get_scale(data, chan->channel, val, val2);
1178
1179         case IIO_CHAN_INFO_RAW:
1180         {
1181                 int (*result_get)(struct bu27034_data *data, int chan, int *val);
1182
1183                 if (chan->type == IIO_INTENSITY)
1184                         result_get = bu27034_get_single_result;
1185                 else if (chan->type == IIO_LIGHT)
1186                         result_get = bu27034_get_mlux;
1187                 else
1188                         return -EINVAL;
1189
1190                 /* Don't mess with measurement enabling while buffering */
1191                 ret = iio_device_claim_direct_mode(idev);
1192                 if (ret)
1193                         return ret;
1194
1195                 mutex_lock(&data->mutex);
1196                 /*
1197                  * Reading one channel at a time is inefficient but we
1198                  * don't care here. Buffered version should be used if
1199                  * performance is an issue.
1200                  */
1201                 ret = result_get(data, chan->channel, val);
1202
1203                 mutex_unlock(&data->mutex);
1204                 iio_device_release_direct_mode(idev);
1205
1206                 if (ret)
1207                         return ret;
1208
1209                 return IIO_VAL_INT;
1210         }
1211         default:
1212                 return -EINVAL;
1213         }
1214 }
1215
1216 static int bu27034_write_raw(struct iio_dev *idev,
1217                              struct iio_chan_spec const *chan,
1218                              int val, int val2, long mask)
1219 {
1220         struct bu27034_data *data = iio_priv(idev);
1221         int ret;
1222
1223         ret = iio_device_claim_direct_mode(idev);
1224         if (ret)
1225                 return ret;
1226
1227         switch (mask) {
1228         case IIO_CHAN_INFO_SCALE:
1229                 ret = bu27034_set_scale(data, chan->channel, val, val2);
1230                 break;
1231         case IIO_CHAN_INFO_INT_TIME:
1232                 ret = bu27034_try_set_int_time(data, val);
1233                 break;
1234         default:
1235                 ret = -EINVAL;
1236                 break;
1237         }
1238
1239         iio_device_release_direct_mode(idev);
1240
1241         return ret;
1242 }
1243
1244 static int bu27034_read_avail(struct iio_dev *idev,
1245                               struct iio_chan_spec const *chan, const int **vals,
1246                               int *type, int *length, long mask)
1247 {
1248         struct bu27034_data *data = iio_priv(idev);
1249
1250         switch (mask) {
1251         case IIO_CHAN_INFO_INT_TIME:
1252                 return iio_gts_avail_times(&data->gts, vals, type, length);
1253         case IIO_CHAN_INFO_SCALE:
1254                 return iio_gts_all_avail_scales(&data->gts, vals, type, length);
1255         default:
1256                 return -EINVAL;
1257         }
1258 }
1259
1260 static const struct iio_info bu27034_info = {
1261         .read_raw = &bu27034_read_raw,
1262         .write_raw = &bu27034_write_raw,
1263         .read_avail = &bu27034_read_avail,
1264 };
1265
1266 static int bu27034_chip_init(struct bu27034_data *data)
1267 {
1268         int ret, sel;
1269
1270         /* Reset */
1271         ret = regmap_update_bits(data->regmap, BU27034_REG_SYSTEM_CONTROL,
1272                            BU27034_MASK_SW_RESET, BU27034_MASK_SW_RESET);
1273         if (ret)
1274                 return dev_err_probe(data->dev, ret, "Sensor reset failed\n");
1275
1276         msleep(1);
1277         /*
1278          * Read integration time here to ensure it is in regmap cache. We do
1279          * this to speed-up the int-time acquisition in the start of the buffer
1280          * handling thread where longer delays could make it more likely we end
1281          * up skipping a sample, and where the longer delays make timestamps
1282          * less accurate.
1283          */
1284         ret = regmap_read(data->regmap, BU27034_REG_MODE_CONTROL1, &sel);
1285         if (ret)
1286                 dev_err(data->dev, "reading integration time failed\n");
1287
1288         return 0;
1289 }
1290
1291 static int bu27034_wait_for_data(struct bu27034_data *data)
1292 {
1293         int ret, val;
1294
1295         ret = regmap_read_poll_timeout(data->regmap, BU27034_REG_MODE_CONTROL4,
1296                                        val, val & BU27034_MASK_VALID,
1297                                        BU27034_DATA_WAIT_TIME_US,
1298                                        BU27034_TOTAL_DATA_WAIT_TIME_US);
1299         if (ret) {
1300                 dev_err(data->dev, "data polling %s\n",
1301                         !(val & BU27034_MASK_VALID) ? "timeout" : "fail");
1302
1303                 return ret;
1304         }
1305
1306         ret = regmap_bulk_read(data->regmap, BU27034_REG_DATA0_LO,
1307                                &data->scan.channels[0],
1308                                sizeof(data->scan.channels));
1309         if (ret)
1310                 return ret;
1311
1312         bu27034_invalidate_read_data(data);
1313
1314         return 0;
1315 }
1316
1317 static int bu27034_buffer_thread(void *arg)
1318 {
1319         struct iio_dev *idev = arg;
1320         struct bu27034_data *data;
1321         int wait_ms;
1322
1323         data = iio_priv(idev);
1324
1325         wait_ms = bu27034_get_int_time(data);
1326         wait_ms /= 1000;
1327
1328         wait_ms -= BU27034_MEAS_WAIT_PREMATURE_MS;
1329
1330         while (!kthread_should_stop()) {
1331                 int ret;
1332                 int64_t tstamp;
1333
1334                 msleep(wait_ms);
1335                 ret = bu27034_wait_for_data(data);
1336                 if (ret)
1337                         continue;
1338
1339                 tstamp = iio_get_time_ns(idev);
1340
1341                 if (test_bit(BU27034_CHAN_ALS, idev->active_scan_mask)) {
1342                         int mlux;
1343
1344                         ret = bu27034_calc_mlux(data, &data->scan.channels[0],
1345                                                &mlux);
1346                         if (ret)
1347                                 dev_err(data->dev, "failed to calculate lux\n");
1348
1349                         /*
1350                          * The maximum Milli lux value we get with gain 1x time
1351                          * 55mS data ch0 = 0xffff ch1 = 0xffff fits in 26 bits
1352                          * so there should be no problem returning int from
1353                          * computations and casting it to u32
1354                          */
1355                         data->scan.mlux = (u32)mlux;
1356                 }
1357                 iio_push_to_buffers_with_timestamp(idev, &data->scan, tstamp);
1358         }
1359
1360         return 0;
1361 }
1362
1363 static int bu27034_buffer_enable(struct iio_dev *idev)
1364 {
1365         struct bu27034_data *data = iio_priv(idev);
1366         struct task_struct *task;
1367         int ret;
1368
1369         mutex_lock(&data->mutex);
1370         ret = bu27034_meas_set(data, true);
1371         if (ret)
1372                 goto unlock_out;
1373
1374         task = kthread_run(bu27034_buffer_thread, idev,
1375                                  "bu27034-buffering-%u",
1376                                  iio_device_id(idev));
1377         if (IS_ERR(task)) {
1378                 ret = PTR_ERR(task);
1379                 goto unlock_out;
1380         }
1381
1382         data->task = task;
1383
1384 unlock_out:
1385         mutex_unlock(&data->mutex);
1386
1387         return ret;
1388 }
1389
1390 static int bu27034_buffer_disable(struct iio_dev *idev)
1391 {
1392         struct bu27034_data *data = iio_priv(idev);
1393         int ret;
1394
1395         mutex_lock(&data->mutex);
1396         if (data->task) {
1397                 kthread_stop(data->task);
1398                 data->task = NULL;
1399         }
1400
1401         ret = bu27034_meas_set(data, false);
1402         mutex_unlock(&data->mutex);
1403
1404         return ret;
1405 }
1406
1407 static const struct iio_buffer_setup_ops bu27034_buffer_ops = {
1408         .postenable = &bu27034_buffer_enable,
1409         .predisable = &bu27034_buffer_disable,
1410 };
1411
1412 static int bu27034_probe(struct i2c_client *i2c)
1413 {
1414         struct device *dev = &i2c->dev;
1415         struct bu27034_data *data;
1416         struct regmap *regmap;
1417         struct iio_dev *idev;
1418         unsigned int part_id, reg;
1419         int ret;
1420
1421         regmap = devm_regmap_init_i2c(i2c, &bu27034_regmap);
1422         if (IS_ERR(regmap))
1423                 return dev_err_probe(dev, PTR_ERR(regmap),
1424                                      "Failed to initialize Regmap\n");
1425
1426         idev = devm_iio_device_alloc(dev, sizeof(*data));
1427         if (!idev)
1428                 return -ENOMEM;
1429
1430         ret = devm_regulator_get_enable(dev, "vdd");
1431         if (ret)
1432                 return dev_err_probe(dev, ret, "Failed to get regulator\n");
1433
1434         data = iio_priv(idev);
1435
1436         ret = regmap_read(regmap, BU27034_REG_SYSTEM_CONTROL, &reg);
1437         if (ret)
1438                 return dev_err_probe(dev, ret, "Failed to access sensor\n");
1439
1440         part_id = FIELD_GET(BU27034_MASK_PART_ID, reg);
1441
1442         if (part_id != BU27034_ID)
1443                 dev_warn(dev, "unknown device 0x%x\n", part_id);
1444
1445         ret = devm_iio_init_iio_gts(dev, BU27034_SCALE_1X, 0, bu27034_gains,
1446                                     ARRAY_SIZE(bu27034_gains), bu27034_itimes,
1447                                     ARRAY_SIZE(bu27034_itimes), &data->gts);
1448         if (ret)
1449                 return ret;
1450
1451         mutex_init(&data->mutex);
1452         data->regmap = regmap;
1453         data->dev = dev;
1454
1455         idev->channels = bu27034_channels;
1456         idev->num_channels = ARRAY_SIZE(bu27034_channels);
1457         idev->name = "bu27034";
1458         idev->info = &bu27034_info;
1459
1460         idev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
1461         idev->available_scan_masks = bu27034_scan_masks;
1462
1463         ret = bu27034_chip_init(data);
1464         if (ret)
1465                 return ret;
1466
1467         ret = devm_iio_kfifo_buffer_setup(dev, idev, &bu27034_buffer_ops);
1468         if (ret)
1469                 return dev_err_probe(dev, ret, "buffer setup failed\n");
1470
1471         ret = devm_iio_device_register(dev, idev);
1472         if (ret < 0)
1473                 return dev_err_probe(dev, ret,
1474                                      "Unable to register iio device\n");
1475
1476         return ret;
1477 }
1478
1479 static const struct of_device_id bu27034_of_match[] = {
1480         { .compatible = "rohm,bu27034" },
1481         { }
1482 };
1483 MODULE_DEVICE_TABLE(of, bu27034_of_match);
1484
1485 static struct i2c_driver bu27034_i2c_driver = {
1486         .driver = {
1487                 .name = "bu27034-als",
1488                 .of_match_table = bu27034_of_match,
1489         },
1490         .probe_new = bu27034_probe,
1491 };
1492 module_i2c_driver(bu27034_i2c_driver);
1493
1494 MODULE_LICENSE("GPL");
1495 MODULE_AUTHOR("Matti Vaittinen <matti.vaittinen@fi.rohmeurope.com>");
1496 MODULE_DESCRIPTION("ROHM BU27034 ambient light sensor driver");
1497 MODULE_IMPORT_NS(IIO_GTS_HELPER);