GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / iio / light / tsl2583.c
1 /*
2  * Device driver for monitoring ambient light intensity (lux)
3  * within the TAOS tsl258x family of devices (tsl2580, tsl2581, tsl2583).
4  *
5  * Copyright (c) 2011, TAOS Corporation.
6  * Copyright (c) 2016-2017 Brian Masney <masneyb@onstation.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
16  * more details.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/i2c.h>
21 #include <linux/errno.h>
22 #include <linux/delay.h>
23 #include <linux/string.h>
24 #include <linux/mutex.h>
25 #include <linux/unistd.h>
26 #include <linux/slab.h>
27 #include <linux/module.h>
28 #include <linux/iio/iio.h>
29 #include <linux/iio/sysfs.h>
30 #include <linux/pm_runtime.h>
31
32 /* Device Registers and Masks */
33 #define TSL2583_CNTRL                   0x00
34 #define TSL2583_ALS_TIME                0X01
35 #define TSL2583_INTERRUPT               0x02
36 #define TSL2583_GAIN                    0x07
37 #define TSL2583_REVID                   0x11
38 #define TSL2583_CHIPID                  0x12
39 #define TSL2583_ALS_CHAN0LO             0x14
40 #define TSL2583_ALS_CHAN0HI             0x15
41 #define TSL2583_ALS_CHAN1LO             0x16
42 #define TSL2583_ALS_CHAN1HI             0x17
43 #define TSL2583_TMR_LO                  0x18
44 #define TSL2583_TMR_HI                  0x19
45
46 /* tsl2583 cmd reg masks */
47 #define TSL2583_CMD_REG                 0x80
48 #define TSL2583_CMD_SPL_FN              0x60
49 #define TSL2583_CMD_ALS_INT_CLR         0x01
50
51 /* tsl2583 cntrl reg masks */
52 #define TSL2583_CNTL_ADC_ENBL           0x02
53 #define TSL2583_CNTL_PWR_OFF            0x00
54 #define TSL2583_CNTL_PWR_ON             0x01
55
56 /* tsl2583 status reg masks */
57 #define TSL2583_STA_ADC_VALID           0x01
58 #define TSL2583_STA_ADC_INTR            0x10
59
60 /* Lux calculation constants */
61 #define TSL2583_LUX_CALC_OVER_FLOW      65535
62
63 #define TSL2583_INTERRUPT_DISABLED      0x00
64
65 #define TSL2583_CHIP_ID                 0x90
66 #define TSL2583_CHIP_ID_MASK            0xf0
67
68 #define TSL2583_POWER_OFF_DELAY_MS      2000
69
70 /* Per-device data */
71 struct tsl2583_als_info {
72         u16 als_ch0;
73         u16 als_ch1;
74         u16 lux;
75 };
76
77 struct tsl2583_lux {
78         unsigned int ratio;
79         unsigned int ch0;
80         unsigned int ch1;
81 };
82
83 static const struct tsl2583_lux tsl2583_default_lux[] = {
84         {  9830,  8520, 15729 },
85         { 12452, 10807, 23344 },
86         { 14746,  6383, 11705 },
87         { 17695,  4063,  6554 },
88         {     0,     0,     0 }  /* Termination segment */
89 };
90
91 #define TSL2583_MAX_LUX_TABLE_ENTRIES 11
92
93 struct tsl2583_settings {
94         int als_time;
95         int als_gain;
96         int als_gain_trim;
97         int als_cal_target;
98
99         /*
100          * This structure is intentionally large to accommodate updates via
101          * sysfs. Sized to 11 = max 10 segments + 1 termination segment.
102          * Assumption is that one and only one type of glass used.
103          */
104         struct tsl2583_lux als_device_lux[TSL2583_MAX_LUX_TABLE_ENTRIES];
105 };
106
107 struct tsl2583_chip {
108         struct mutex als_mutex;
109         struct i2c_client *client;
110         struct tsl2583_als_info als_cur_info;
111         struct tsl2583_settings als_settings;
112         int als_time_scale;
113         int als_saturation;
114 };
115
116 struct gainadj {
117         s16 ch0;
118         s16 ch1;
119         s16 mean;
120 };
121
122 /* Index = (0 - 3) Used to validate the gain selection index */
123 static const struct gainadj gainadj[] = {
124         { 1, 1, 1 },
125         { 8, 8, 8 },
126         { 16, 16, 16 },
127         { 107, 115, 111 }
128 };
129
130 /*
131  * Provides initial operational parameter defaults.
132  * These defaults may be changed through the device's sysfs files.
133  */
134 static void tsl2583_defaults(struct tsl2583_chip *chip)
135 {
136         /*
137          * The integration time must be a multiple of 50ms and within the
138          * range [50, 600] ms.
139          */
140         chip->als_settings.als_time = 100;
141
142         /*
143          * This is an index into the gainadj table. Assume clear glass as the
144          * default.
145          */
146         chip->als_settings.als_gain = 0;
147
148         /* Default gain trim to account for aperture effects */
149         chip->als_settings.als_gain_trim = 1000;
150
151         /* Known external ALS reading used for calibration */
152         chip->als_settings.als_cal_target = 130;
153
154         /* Default lux table. */
155         memcpy(chip->als_settings.als_device_lux, tsl2583_default_lux,
156                sizeof(tsl2583_default_lux));
157 }
158
159 /*
160  * Reads and calculates current lux value.
161  * The raw ch0 and ch1 values of the ambient light sensed in the last
162  * integration cycle are read from the device.
163  * Time scale factor array values are adjusted based on the integration time.
164  * The raw values are multiplied by a scale factor, and device gain is obtained
165  * using gain index. Limit checks are done next, then the ratio of a multiple
166  * of ch1 value, to the ch0 value, is calculated. The array als_device_lux[]
167  * declared above is then scanned to find the first ratio value that is just
168  * above the ratio we just calculated. The ch0 and ch1 multiplier constants in
169  * the array are then used along with the time scale factor array values, to
170  * calculate the lux.
171  */
172 static int tsl2583_get_lux(struct iio_dev *indio_dev)
173 {
174         u16 ch0, ch1; /* separated ch0/ch1 data from device */
175         u32 lux; /* raw lux calculated from device data */
176         u64 lux64;
177         u32 ratio;
178         u8 buf[5];
179         struct tsl2583_lux *p;
180         struct tsl2583_chip *chip = iio_priv(indio_dev);
181         int i, ret;
182
183         ret = i2c_smbus_read_byte_data(chip->client, TSL2583_CMD_REG);
184         if (ret < 0) {
185                 dev_err(&chip->client->dev, "%s: failed to read CMD_REG register\n",
186                         __func__);
187                 goto done;
188         }
189
190         /* is data new & valid */
191         if (!(ret & TSL2583_STA_ADC_INTR)) {
192                 dev_err(&chip->client->dev, "%s: data not valid; returning last value\n",
193                         __func__);
194                 ret = chip->als_cur_info.lux; /* return LAST VALUE */
195                 goto done;
196         }
197
198         for (i = 0; i < 4; i++) {
199                 int reg = TSL2583_CMD_REG | (TSL2583_ALS_CHAN0LO + i);
200
201                 ret = i2c_smbus_read_byte_data(chip->client, reg);
202                 if (ret < 0) {
203                         dev_err(&chip->client->dev, "%s: failed to read register %x\n",
204                                 __func__, reg);
205                         goto done;
206                 }
207                 buf[i] = ret;
208         }
209
210         /*
211          * Clear the pending interrupt status bit on the chip to allow the next
212          * integration cycle to start. This has to be done even though this
213          * driver currently does not support interrupts.
214          */
215         ret = i2c_smbus_write_byte(chip->client,
216                                    (TSL2583_CMD_REG | TSL2583_CMD_SPL_FN |
217                                     TSL2583_CMD_ALS_INT_CLR));
218         if (ret < 0) {
219                 dev_err(&chip->client->dev, "%s: failed to clear the interrupt bit\n",
220                         __func__);
221                 goto done; /* have no data, so return failure */
222         }
223
224         /* extract ALS/lux data */
225         ch0 = le16_to_cpup((const __le16 *)&buf[0]);
226         ch1 = le16_to_cpup((const __le16 *)&buf[2]);
227
228         chip->als_cur_info.als_ch0 = ch0;
229         chip->als_cur_info.als_ch1 = ch1;
230
231         if ((ch0 >= chip->als_saturation) || (ch1 >= chip->als_saturation))
232                 goto return_max;
233
234         if (!ch0) {
235                 /*
236                  * The sensor appears to be in total darkness so set the
237                  * calculated lux to 0 and return early to avoid a division by
238                  * zero below when calculating the ratio.
239                  */
240                 ret = 0;
241                 chip->als_cur_info.lux = 0;
242                 goto done;
243         }
244
245         /* calculate ratio */
246         ratio = (ch1 << 15) / ch0;
247
248         /* convert to unscaled lux using the pointer to the table */
249         for (p = (struct tsl2583_lux *)chip->als_settings.als_device_lux;
250              p->ratio != 0 && p->ratio < ratio; p++)
251                 ;
252
253         if (p->ratio == 0) {
254                 lux = 0;
255         } else {
256                 u32 ch0lux, ch1lux;
257
258                 ch0lux = ((ch0 * p->ch0) +
259                           (gainadj[chip->als_settings.als_gain].ch0 >> 1))
260                          / gainadj[chip->als_settings.als_gain].ch0;
261                 ch1lux = ((ch1 * p->ch1) +
262                           (gainadj[chip->als_settings.als_gain].ch1 >> 1))
263                          / gainadj[chip->als_settings.als_gain].ch1;
264
265                 /* note: lux is 31 bit max at this point */
266                 if (ch1lux > ch0lux) {
267                         dev_dbg(&chip->client->dev, "%s: No Data - Returning 0\n",
268                                 __func__);
269                         ret = 0;
270                         chip->als_cur_info.lux = 0;
271                         goto done;
272                 }
273
274                 lux = ch0lux - ch1lux;
275         }
276
277         /* adjust for active time scale */
278         if (chip->als_time_scale == 0)
279                 lux = 0;
280         else
281                 lux = (lux + (chip->als_time_scale >> 1)) /
282                         chip->als_time_scale;
283
284         /*
285          * Adjust for active gain scale.
286          * The tsl2583_default_lux tables above have a factor of 8192 built in,
287          * so we need to shift right.
288          * User-specified gain provides a multiplier.
289          * Apply user-specified gain before shifting right to retain precision.
290          * Use 64 bits to avoid overflow on multiplication.
291          * Then go back to 32 bits before division to avoid using div_u64().
292          */
293         lux64 = lux;
294         lux64 = lux64 * chip->als_settings.als_gain_trim;
295         lux64 >>= 13;
296         lux = lux64;
297         lux = (lux + 500) / 1000;
298
299         if (lux > TSL2583_LUX_CALC_OVER_FLOW) { /* check for overflow */
300 return_max:
301                 lux = TSL2583_LUX_CALC_OVER_FLOW;
302         }
303
304         /* Update the structure with the latest VALID lux. */
305         chip->als_cur_info.lux = lux;
306         ret = lux;
307
308 done:
309         return ret;
310 }
311
312 /*
313  * Obtain single reading and calculate the als_gain_trim (later used
314  * to derive actual lux).
315  * Return updated gain_trim value.
316  */
317 static int tsl2583_als_calibrate(struct iio_dev *indio_dev)
318 {
319         struct tsl2583_chip *chip = iio_priv(indio_dev);
320         unsigned int gain_trim_val;
321         int ret;
322         int lux_val;
323
324         ret = i2c_smbus_read_byte_data(chip->client,
325                                        TSL2583_CMD_REG | TSL2583_CNTRL);
326         if (ret < 0) {
327                 dev_err(&chip->client->dev,
328                         "%s: failed to read from the CNTRL register\n",
329                         __func__);
330                 return ret;
331         }
332
333         if ((ret & (TSL2583_CNTL_ADC_ENBL | TSL2583_CNTL_PWR_ON))
334                         != (TSL2583_CNTL_ADC_ENBL | TSL2583_CNTL_PWR_ON)) {
335                 dev_err(&chip->client->dev,
336                         "%s: Device is not powered on and/or ADC is not enabled\n",
337                         __func__);
338                 return -EINVAL;
339         } else if ((ret & TSL2583_STA_ADC_VALID) != TSL2583_STA_ADC_VALID) {
340                 dev_err(&chip->client->dev,
341                         "%s: The two ADC channels have not completed an integration cycle\n",
342                         __func__);
343                 return -ENODATA;
344         }
345
346         lux_val = tsl2583_get_lux(indio_dev);
347         if (lux_val < 0) {
348                 dev_err(&chip->client->dev, "%s: failed to get lux\n",
349                         __func__);
350                 return lux_val;
351         }
352
353         /* Avoid division by zero of lux_value later on */
354         if (lux_val == 0) {
355                 dev_err(&chip->client->dev,
356                         "%s: lux_val of 0 will produce out of range trim_value\n",
357                         __func__);
358                 return -ENODATA;
359         }
360
361         gain_trim_val = (unsigned int)(((chip->als_settings.als_cal_target)
362                         * chip->als_settings.als_gain_trim) / lux_val);
363         if ((gain_trim_val < 250) || (gain_trim_val > 4000)) {
364                 dev_err(&chip->client->dev,
365                         "%s: trim_val of %d is not within the range [250, 4000]\n",
366                         __func__, gain_trim_val);
367                 return -ENODATA;
368         }
369
370         chip->als_settings.als_gain_trim = (int)gain_trim_val;
371
372         return 0;
373 }
374
375 static int tsl2583_set_als_time(struct tsl2583_chip *chip)
376 {
377         int als_count, als_time, ret;
378         u8 val;
379
380         /* determine als integration register */
381         als_count = (chip->als_settings.als_time * 100 + 135) / 270;
382         if (!als_count)
383                 als_count = 1; /* ensure at least one cycle */
384
385         /* convert back to time (encompasses overrides) */
386         als_time = (als_count * 27 + 5) / 10;
387
388         val = 256 - als_count;
389         ret = i2c_smbus_write_byte_data(chip->client,
390                                         TSL2583_CMD_REG | TSL2583_ALS_TIME,
391                                         val);
392         if (ret < 0) {
393                 dev_err(&chip->client->dev, "%s: failed to set the als time to %d\n",
394                         __func__, val);
395                 return ret;
396         }
397
398         /* set chip struct re scaling and saturation */
399         chip->als_saturation = als_count * 922; /* 90% of full scale */
400         chip->als_time_scale = (als_time + 25) / 50;
401
402         return ret;
403 }
404
405 static int tsl2583_set_als_gain(struct tsl2583_chip *chip)
406 {
407         int ret;
408
409         /* Set the gain based on als_settings struct */
410         ret = i2c_smbus_write_byte_data(chip->client,
411                                         TSL2583_CMD_REG | TSL2583_GAIN,
412                                         chip->als_settings.als_gain);
413         if (ret < 0)
414                 dev_err(&chip->client->dev,
415                         "%s: failed to set the gain to %d\n", __func__,
416                         chip->als_settings.als_gain);
417
418         return ret;
419 }
420
421 static int tsl2583_set_power_state(struct tsl2583_chip *chip, u8 state)
422 {
423         int ret;
424
425         ret = i2c_smbus_write_byte_data(chip->client,
426                                         TSL2583_CMD_REG | TSL2583_CNTRL, state);
427         if (ret < 0)
428                 dev_err(&chip->client->dev,
429                         "%s: failed to set the power state to %d\n", __func__,
430                         state);
431
432         return ret;
433 }
434
435 /*
436  * Turn the device on.
437  * Configuration must be set before calling this function.
438  */
439 static int tsl2583_chip_init_and_power_on(struct iio_dev *indio_dev)
440 {
441         struct tsl2583_chip *chip = iio_priv(indio_dev);
442         int ret;
443
444         /* Power on the device; ADC off. */
445         ret = tsl2583_set_power_state(chip, TSL2583_CNTL_PWR_ON);
446         if (ret < 0)
447                 return ret;
448
449         ret = i2c_smbus_write_byte_data(chip->client,
450                                         TSL2583_CMD_REG | TSL2583_INTERRUPT,
451                                         TSL2583_INTERRUPT_DISABLED);
452         if (ret < 0) {
453                 dev_err(&chip->client->dev,
454                         "%s: failed to disable interrupts\n", __func__);
455                 return ret;
456         }
457
458         ret = tsl2583_set_als_time(chip);
459         if (ret < 0)
460                 return ret;
461
462         ret = tsl2583_set_als_gain(chip);
463         if (ret < 0)
464                 return ret;
465
466         usleep_range(3000, 3500);
467
468         ret = tsl2583_set_power_state(chip, TSL2583_CNTL_PWR_ON |
469                                             TSL2583_CNTL_ADC_ENBL);
470         if (ret < 0)
471                 return ret;
472
473         return ret;
474 }
475
476 /* Sysfs Interface Functions */
477
478 static ssize_t in_illuminance_input_target_show(struct device *dev,
479                                                 struct device_attribute *attr,
480                                                 char *buf)
481 {
482         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
483         struct tsl2583_chip *chip = iio_priv(indio_dev);
484         int ret;
485
486         mutex_lock(&chip->als_mutex);
487         ret = sprintf(buf, "%d\n", chip->als_settings.als_cal_target);
488         mutex_unlock(&chip->als_mutex);
489
490         return ret;
491 }
492
493 static ssize_t in_illuminance_input_target_store(struct device *dev,
494                                                  struct device_attribute *attr,
495                                                  const char *buf, size_t len)
496 {
497         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
498         struct tsl2583_chip *chip = iio_priv(indio_dev);
499         int value;
500
501         if (kstrtoint(buf, 0, &value) || !value)
502                 return -EINVAL;
503
504         mutex_lock(&chip->als_mutex);
505         chip->als_settings.als_cal_target = value;
506         mutex_unlock(&chip->als_mutex);
507
508         return len;
509 }
510
511 static ssize_t in_illuminance_calibrate_store(struct device *dev,
512                                               struct device_attribute *attr,
513                                               const char *buf, size_t len)
514 {
515         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
516         struct tsl2583_chip *chip = iio_priv(indio_dev);
517         int value, ret;
518
519         if (kstrtoint(buf, 0, &value) || value != 1)
520                 return -EINVAL;
521
522         mutex_lock(&chip->als_mutex);
523
524         ret = tsl2583_als_calibrate(indio_dev);
525         if (ret < 0)
526                 goto done;
527
528         ret = len;
529 done:
530         mutex_unlock(&chip->als_mutex);
531
532         return ret;
533 }
534
535 static ssize_t in_illuminance_lux_table_show(struct device *dev,
536                                              struct device_attribute *attr,
537                                              char *buf)
538 {
539         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
540         struct tsl2583_chip *chip = iio_priv(indio_dev);
541         unsigned int i;
542         int offset = 0;
543
544         for (i = 0; i < ARRAY_SIZE(chip->als_settings.als_device_lux); i++) {
545                 offset += sprintf(buf + offset, "%u,%u,%u,",
546                                   chip->als_settings.als_device_lux[i].ratio,
547                                   chip->als_settings.als_device_lux[i].ch0,
548                                   chip->als_settings.als_device_lux[i].ch1);
549                 if (chip->als_settings.als_device_lux[i].ratio == 0) {
550                         /*
551                          * We just printed the first "0" entry.
552                          * Now get rid of the extra "," and break.
553                          */
554                         offset--;
555                         break;
556                 }
557         }
558
559         offset += sprintf(buf + offset, "\n");
560
561         return offset;
562 }
563
564 static ssize_t in_illuminance_lux_table_store(struct device *dev,
565                                               struct device_attribute *attr,
566                                               const char *buf, size_t len)
567 {
568         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
569         struct tsl2583_chip *chip = iio_priv(indio_dev);
570         const unsigned int max_ints = TSL2583_MAX_LUX_TABLE_ENTRIES * 3;
571         int value[TSL2583_MAX_LUX_TABLE_ENTRIES * 3 + 1];
572         int ret = -EINVAL;
573         unsigned int n;
574
575         mutex_lock(&chip->als_mutex);
576
577         get_options(buf, ARRAY_SIZE(value), value);
578
579         /*
580          * We now have an array of ints starting at value[1], and
581          * enumerated by value[0].
582          * We expect each group of three ints is one table entry,
583          * and the last table entry is all 0.
584          */
585         n = value[0];
586         if ((n % 3) || n < 6 || n > max_ints) {
587                 dev_err(dev,
588                         "%s: The number of entries in the lux table must be a multiple of 3 and within the range [6, %d]\n",
589                         __func__, max_ints);
590                 goto done;
591         }
592         if ((value[n - 2] | value[n - 1] | value[n]) != 0) {
593                 dev_err(dev, "%s: The last 3 entries in the lux table must be zeros.\n",
594                         __func__);
595                 goto done;
596         }
597
598         memcpy(chip->als_settings.als_device_lux, &value[1],
599                value[0] * sizeof(value[1]));
600
601         ret = len;
602
603 done:
604         mutex_unlock(&chip->als_mutex);
605
606         return ret;
607 }
608
609 static IIO_CONST_ATTR(in_illuminance_calibscale_available, "1 8 16 111");
610 static IIO_CONST_ATTR(in_illuminance_integration_time_available,
611                       "0.000050 0.000100 0.000150 0.000200 0.000250 0.000300 0.000350 0.000400 0.000450 0.000500 0.000550 0.000600 0.000650");
612 static IIO_DEVICE_ATTR_RW(in_illuminance_input_target, 0);
613 static IIO_DEVICE_ATTR_WO(in_illuminance_calibrate, 0);
614 static IIO_DEVICE_ATTR_RW(in_illuminance_lux_table, 0);
615
616 static struct attribute *sysfs_attrs_ctrl[] = {
617         &iio_const_attr_in_illuminance_calibscale_available.dev_attr.attr,
618         &iio_const_attr_in_illuminance_integration_time_available.dev_attr.attr,
619         &iio_dev_attr_in_illuminance_input_target.dev_attr.attr,
620         &iio_dev_attr_in_illuminance_calibrate.dev_attr.attr,
621         &iio_dev_attr_in_illuminance_lux_table.dev_attr.attr,
622         NULL
623 };
624
625 static const struct attribute_group tsl2583_attribute_group = {
626         .attrs = sysfs_attrs_ctrl,
627 };
628
629 static const struct iio_chan_spec tsl2583_channels[] = {
630         {
631                 .type = IIO_LIGHT,
632                 .modified = 1,
633                 .channel2 = IIO_MOD_LIGHT_IR,
634                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
635         },
636         {
637                 .type = IIO_LIGHT,
638                 .modified = 1,
639                 .channel2 = IIO_MOD_LIGHT_BOTH,
640                 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
641         },
642         {
643                 .type = IIO_LIGHT,
644                 .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED) |
645                                       BIT(IIO_CHAN_INFO_CALIBBIAS) |
646                                       BIT(IIO_CHAN_INFO_CALIBSCALE) |
647                                       BIT(IIO_CHAN_INFO_INT_TIME),
648         },
649 };
650
651 static int tsl2583_set_pm_runtime_busy(struct tsl2583_chip *chip, bool on)
652 {
653         int ret;
654
655         if (on) {
656                 ret = pm_runtime_get_sync(&chip->client->dev);
657                 if (ret < 0)
658                         pm_runtime_put_noidle(&chip->client->dev);
659         } else {
660                 pm_runtime_mark_last_busy(&chip->client->dev);
661                 ret = pm_runtime_put_autosuspend(&chip->client->dev);
662         }
663
664         return ret;
665 }
666
667 static int tsl2583_read_raw(struct iio_dev *indio_dev,
668                             struct iio_chan_spec const *chan,
669                             int *val, int *val2, long mask)
670 {
671         struct tsl2583_chip *chip = iio_priv(indio_dev);
672         int ret, pm_ret;
673
674         ret = tsl2583_set_pm_runtime_busy(chip, true);
675         if (ret < 0)
676                 return ret;
677
678         mutex_lock(&chip->als_mutex);
679
680         ret = -EINVAL;
681         switch (mask) {
682         case IIO_CHAN_INFO_RAW:
683                 if (chan->type == IIO_LIGHT) {
684                         ret = tsl2583_get_lux(indio_dev);
685                         if (ret < 0)
686                                 goto read_done;
687
688                         /*
689                          * From page 20 of the TSL2581, TSL2583 data
690                          * sheet (TAOS134 âˆ’ MARCH 2011):
691                          *
692                          * One of the photodiodes (channel 0) is
693                          * sensitive to both visible and infrared light,
694                          * while the second photodiode (channel 1) is
695                          * sensitive primarily to infrared light.
696                          */
697                         if (chan->channel2 == IIO_MOD_LIGHT_BOTH)
698                                 *val = chip->als_cur_info.als_ch0;
699                         else
700                                 *val = chip->als_cur_info.als_ch1;
701
702                         ret = IIO_VAL_INT;
703                 }
704                 break;
705         case IIO_CHAN_INFO_PROCESSED:
706                 if (chan->type == IIO_LIGHT) {
707                         ret = tsl2583_get_lux(indio_dev);
708                         if (ret < 0)
709                                 goto read_done;
710
711                         *val = ret;
712                         ret = IIO_VAL_INT;
713                 }
714                 break;
715         case IIO_CHAN_INFO_CALIBBIAS:
716                 if (chan->type == IIO_LIGHT) {
717                         *val = chip->als_settings.als_gain_trim;
718                         ret = IIO_VAL_INT;
719                 }
720                 break;
721         case IIO_CHAN_INFO_CALIBSCALE:
722                 if (chan->type == IIO_LIGHT) {
723                         *val = gainadj[chip->als_settings.als_gain].mean;
724                         ret = IIO_VAL_INT;
725                 }
726                 break;
727         case IIO_CHAN_INFO_INT_TIME:
728                 if (chan->type == IIO_LIGHT) {
729                         *val = 0;
730                         *val2 = chip->als_settings.als_time;
731                         ret = IIO_VAL_INT_PLUS_MICRO;
732                 }
733                 break;
734         default:
735                 break;
736         }
737
738 read_done:
739         mutex_unlock(&chip->als_mutex);
740
741         if (ret < 0)
742                 return ret;
743
744         /*
745          * Preserve the ret variable if the call to
746          * tsl2583_set_pm_runtime_busy() is successful so the reading
747          * (if applicable) is returned to user space.
748          */
749         pm_ret = tsl2583_set_pm_runtime_busy(chip, false);
750         if (pm_ret < 0)
751                 return pm_ret;
752
753         return ret;
754 }
755
756 static int tsl2583_write_raw(struct iio_dev *indio_dev,
757                              struct iio_chan_spec const *chan,
758                              int val, int val2, long mask)
759 {
760         struct tsl2583_chip *chip = iio_priv(indio_dev);
761         int ret;
762
763         ret = tsl2583_set_pm_runtime_busy(chip, true);
764         if (ret < 0)
765                 return ret;
766
767         mutex_lock(&chip->als_mutex);
768
769         ret = -EINVAL;
770         switch (mask) {
771         case IIO_CHAN_INFO_CALIBBIAS:
772                 if (chan->type == IIO_LIGHT) {
773                         chip->als_settings.als_gain_trim = val;
774                         ret = 0;
775                 }
776                 break;
777         case IIO_CHAN_INFO_CALIBSCALE:
778                 if (chan->type == IIO_LIGHT) {
779                         unsigned int i;
780
781                         for (i = 0; i < ARRAY_SIZE(gainadj); i++) {
782                                 if (gainadj[i].mean == val) {
783                                         chip->als_settings.als_gain = i;
784                                         ret = tsl2583_set_als_gain(chip);
785                                         break;
786                                 }
787                         }
788                 }
789                 break;
790         case IIO_CHAN_INFO_INT_TIME:
791                 if (chan->type == IIO_LIGHT && !val && val2 >= 50 &&
792                     val2 <= 650 && !(val2 % 50)) {
793                         chip->als_settings.als_time = val2;
794                         ret = tsl2583_set_als_time(chip);
795                 }
796                 break;
797         default:
798                 break;
799         }
800
801         mutex_unlock(&chip->als_mutex);
802
803         if (ret < 0)
804                 return ret;
805
806         ret = tsl2583_set_pm_runtime_busy(chip, false);
807         if (ret < 0)
808                 return ret;
809
810         return ret;
811 }
812
813 static const struct iio_info tsl2583_info = {
814         .attrs = &tsl2583_attribute_group,
815         .driver_module = THIS_MODULE,
816         .read_raw = tsl2583_read_raw,
817         .write_raw = tsl2583_write_raw,
818 };
819
820 static int tsl2583_probe(struct i2c_client *clientp,
821                          const struct i2c_device_id *idp)
822 {
823         int ret;
824         struct tsl2583_chip *chip;
825         struct iio_dev *indio_dev;
826
827         if (!i2c_check_functionality(clientp->adapter,
828                                      I2C_FUNC_SMBUS_BYTE_DATA)) {
829                 dev_err(&clientp->dev, "%s: i2c smbus byte data functionality is unsupported\n",
830                         __func__);
831                 return -EOPNOTSUPP;
832         }
833
834         indio_dev = devm_iio_device_alloc(&clientp->dev, sizeof(*chip));
835         if (!indio_dev)
836                 return -ENOMEM;
837
838         chip = iio_priv(indio_dev);
839         chip->client = clientp;
840         i2c_set_clientdata(clientp, indio_dev);
841
842         mutex_init(&chip->als_mutex);
843
844         ret = i2c_smbus_read_byte_data(clientp,
845                                        TSL2583_CMD_REG | TSL2583_CHIPID);
846         if (ret < 0) {
847                 dev_err(&clientp->dev,
848                         "%s: failed to read the chip ID register\n", __func__);
849                 return ret;
850         }
851
852         if ((ret & TSL2583_CHIP_ID_MASK) != TSL2583_CHIP_ID) {
853                 dev_err(&clientp->dev, "%s: received an unknown chip ID %x\n",
854                         __func__, ret);
855                 return -EINVAL;
856         }
857
858         indio_dev->info = &tsl2583_info;
859         indio_dev->channels = tsl2583_channels;
860         indio_dev->num_channels = ARRAY_SIZE(tsl2583_channels);
861         indio_dev->dev.parent = &clientp->dev;
862         indio_dev->modes = INDIO_DIRECT_MODE;
863         indio_dev->name = chip->client->name;
864
865         pm_runtime_enable(&clientp->dev);
866         pm_runtime_set_autosuspend_delay(&clientp->dev,
867                                          TSL2583_POWER_OFF_DELAY_MS);
868         pm_runtime_use_autosuspend(&clientp->dev);
869
870         ret = devm_iio_device_register(indio_dev->dev.parent, indio_dev);
871         if (ret) {
872                 dev_err(&clientp->dev, "%s: iio registration failed\n",
873                         __func__);
874                 return ret;
875         }
876
877         /* Load up the V2 defaults (these are hard coded defaults for now) */
878         tsl2583_defaults(chip);
879
880         dev_info(&clientp->dev, "Light sensor found.\n");
881
882         return 0;
883 }
884
885 static int tsl2583_remove(struct i2c_client *client)
886 {
887         struct iio_dev *indio_dev = i2c_get_clientdata(client);
888         struct tsl2583_chip *chip = iio_priv(indio_dev);
889
890         iio_device_unregister(indio_dev);
891
892         pm_runtime_disable(&client->dev);
893         pm_runtime_set_suspended(&client->dev);
894         pm_runtime_put_noidle(&client->dev);
895
896         return tsl2583_set_power_state(chip, TSL2583_CNTL_PWR_OFF);
897 }
898
899 static int __maybe_unused tsl2583_suspend(struct device *dev)
900 {
901         struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
902         struct tsl2583_chip *chip = iio_priv(indio_dev);
903         int ret;
904
905         mutex_lock(&chip->als_mutex);
906
907         ret = tsl2583_set_power_state(chip, TSL2583_CNTL_PWR_OFF);
908
909         mutex_unlock(&chip->als_mutex);
910
911         return ret;
912 }
913
914 static int __maybe_unused tsl2583_resume(struct device *dev)
915 {
916         struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
917         struct tsl2583_chip *chip = iio_priv(indio_dev);
918         int ret;
919
920         mutex_lock(&chip->als_mutex);
921
922         ret = tsl2583_chip_init_and_power_on(indio_dev);
923
924         mutex_unlock(&chip->als_mutex);
925
926         return ret;
927 }
928
929 static const struct dev_pm_ops tsl2583_pm_ops = {
930         SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
931                                 pm_runtime_force_resume)
932         SET_RUNTIME_PM_OPS(tsl2583_suspend, tsl2583_resume, NULL)
933 };
934
935 static const struct i2c_device_id tsl2583_idtable[] = {
936         { "tsl2580", 0 },
937         { "tsl2581", 1 },
938         { "tsl2583", 2 },
939         {}
940 };
941 MODULE_DEVICE_TABLE(i2c, tsl2583_idtable);
942
943 static const struct of_device_id tsl2583_of_match[] = {
944         { .compatible = "amstaos,tsl2580", },
945         { .compatible = "amstaos,tsl2581", },
946         { .compatible = "amstaos,tsl2583", },
947         { },
948 };
949 MODULE_DEVICE_TABLE(of, tsl2583_of_match);
950
951 /* Driver definition */
952 static struct i2c_driver tsl2583_driver = {
953         .driver = {
954                 .name = "tsl2583",
955                 .pm = &tsl2583_pm_ops,
956                 .of_match_table = tsl2583_of_match,
957         },
958         .id_table = tsl2583_idtable,
959         .probe = tsl2583_probe,
960         .remove = tsl2583_remove,
961 };
962 module_i2c_driver(tsl2583_driver);
963
964 MODULE_AUTHOR("J. August Brenner <jbrenner@taosinc.com>");
965 MODULE_AUTHOR("Brian Masney <masneyb@onstation.org>");
966 MODULE_DESCRIPTION("TAOS tsl2583 ambient light sensor driver");
967 MODULE_LICENSE("GPL");