Merge branch 'upstream' of git://git.linux-mips.org/pub/scm/ralf/upstream-linus
[sfrench/cifs-2.6.git] / drivers / iio / adc / ina2xx-adc.c
1 /*
2  * INA2XX Current and Power Monitors
3  *
4  * Copyright 2015 Baylibre SAS.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  * Based on linux/drivers/iio/adc/ad7291.c
11  * Copyright 2010-2011 Analog Devices Inc.
12  *
13  * Based on linux/drivers/hwmon/ina2xx.c
14  * Copyright 2012 Lothar Felten <l-felten@ti.com>
15  *
16  * Licensed under the GPL-2 or later.
17  *
18  * IIO driver for INA219-220-226-230-231
19  *
20  * Configurable 7-bit I2C slave address from 0x40 to 0x4F
21  */
22
23 #include <linux/delay.h>
24 #include <linux/i2c.h>
25 #include <linux/iio/iio.h>
26 #include <linux/iio/buffer.h>
27 #include <linux/iio/kfifo_buf.h>
28 #include <linux/iio/sysfs.h>
29 #include <linux/kthread.h>
30 #include <linux/module.h>
31 #include <linux/of_device.h>
32 #include <linux/regmap.h>
33 #include <linux/util_macros.h>
34
35 #include <linux/platform_data/ina2xx.h>
36
37 /* INA2XX registers definition */
38 #define INA2XX_CONFIG                   0x00
39 #define INA2XX_SHUNT_VOLTAGE            0x01    /* readonly */
40 #define INA2XX_BUS_VOLTAGE              0x02    /* readonly */
41 #define INA2XX_POWER                    0x03    /* readonly */
42 #define INA2XX_CURRENT                  0x04    /* readonly */
43 #define INA2XX_CALIBRATION              0x05
44
45 #define INA226_MASK_ENABLE              0x06
46 #define INA226_CVRF                     BIT(3)
47
48 #define INA2XX_MAX_REGISTERS            8
49
50 /* settings - depend on use case */
51 #define INA219_CONFIG_DEFAULT           0x399F  /* PGA=8 */
52 #define INA219_DEFAULT_IT               532
53 #define INA226_CONFIG_DEFAULT           0x4327
54 #define INA226_DEFAULT_AVG              4
55 #define INA226_DEFAULT_IT               1110
56
57 #define INA2XX_RSHUNT_DEFAULT           10000
58
59 /*
60  * bit masks for reading the settings in the configuration register
61  * FIXME: use regmap_fields.
62  */
63 #define INA2XX_MODE_MASK        GENMASK(3, 0)
64
65 /* Averaging for VBus/VShunt/Power */
66 #define INA226_AVG_MASK         GENMASK(11, 9)
67 #define INA226_SHIFT_AVG(val)   ((val) << 9)
68
69 /* Integration time for VBus */
70 #define INA219_ITB_MASK         GENMASK(10, 7)
71 #define INA219_SHIFT_ITB(val)   ((val) << 7)
72 #define INA226_ITB_MASK         GENMASK(8, 6)
73 #define INA226_SHIFT_ITB(val)   ((val) << 6)
74
75 /* Integration time for VShunt */
76 #define INA219_ITS_MASK         GENMASK(6, 3)
77 #define INA219_SHIFT_ITS(val)   ((val) << 3)
78 #define INA226_ITS_MASK         GENMASK(5, 3)
79 #define INA226_SHIFT_ITS(val)   ((val) << 3)
80
81 /* Cosmetic macro giving the sampling period for a full P=UxI cycle */
82 #define SAMPLING_PERIOD(c)      ((c->int_time_vbus + c->int_time_vshunt) \
83                                  * c->avg)
84
85 static bool ina2xx_is_writeable_reg(struct device *dev, unsigned int reg)
86 {
87         return (reg == INA2XX_CONFIG) || (reg > INA2XX_CURRENT);
88 }
89
90 static bool ina2xx_is_volatile_reg(struct device *dev, unsigned int reg)
91 {
92         return (reg != INA2XX_CONFIG);
93 }
94
95 static inline bool is_signed_reg(unsigned int reg)
96 {
97         return (reg == INA2XX_SHUNT_VOLTAGE) || (reg == INA2XX_CURRENT);
98 }
99
100 static const struct regmap_config ina2xx_regmap_config = {
101         .reg_bits = 8,
102         .val_bits = 16,
103         .max_register = INA2XX_MAX_REGISTERS,
104         .writeable_reg = ina2xx_is_writeable_reg,
105         .volatile_reg = ina2xx_is_volatile_reg,
106 };
107
108 enum ina2xx_ids { ina219, ina226 };
109
110 struct ina2xx_config {
111         u16 config_default;
112         int calibration_factor;
113         int shunt_div;
114         int bus_voltage_shift;
115         int bus_voltage_lsb;    /* uV */
116         int power_lsb;          /* uW */
117         enum ina2xx_ids chip_id;
118 };
119
120 struct ina2xx_chip_info {
121         struct regmap *regmap;
122         struct task_struct *task;
123         const struct ina2xx_config *config;
124         struct mutex state_lock;
125         unsigned int shunt_resistor;
126         int avg;
127         int int_time_vbus; /* Bus voltage integration time uS */
128         int int_time_vshunt; /* Shunt voltage integration time uS */
129         bool allow_async_readout;
130 };
131
132 static const struct ina2xx_config ina2xx_config[] = {
133         [ina219] = {
134                 .config_default = INA219_CONFIG_DEFAULT,
135                 .calibration_factor = 40960000,
136                 .shunt_div = 100,
137                 .bus_voltage_shift = 3,
138                 .bus_voltage_lsb = 4000,
139                 .power_lsb = 20000,
140                 .chip_id = ina219,
141         },
142         [ina226] = {
143                 .config_default = INA226_CONFIG_DEFAULT,
144                 .calibration_factor = 5120000,
145                 .shunt_div = 400,
146                 .bus_voltage_shift = 0,
147                 .bus_voltage_lsb = 1250,
148                 .power_lsb = 25000,
149                 .chip_id = ina226,
150         },
151 };
152
153 static int ina2xx_read_raw(struct iio_dev *indio_dev,
154                            struct iio_chan_spec const *chan,
155                            int *val, int *val2, long mask)
156 {
157         int ret;
158         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
159         unsigned int regval;
160
161         switch (mask) {
162         case IIO_CHAN_INFO_RAW:
163                 ret = regmap_read(chip->regmap, chan->address, &regval);
164                 if (ret)
165                         return ret;
166
167                 if (is_signed_reg(chan->address))
168                         *val = (s16) regval;
169                 else
170                         *val  = regval;
171
172                 return IIO_VAL_INT;
173
174         case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
175                 *val = chip->avg;
176                 return IIO_VAL_INT;
177
178         case IIO_CHAN_INFO_INT_TIME:
179                 *val = 0;
180                 if (chan->address == INA2XX_SHUNT_VOLTAGE)
181                         *val2 = chip->int_time_vshunt;
182                 else
183                         *val2 = chip->int_time_vbus;
184
185                 return IIO_VAL_INT_PLUS_MICRO;
186
187         case IIO_CHAN_INFO_SAMP_FREQ:
188                 /*
189                  * Sample freq is read only, it is a consequence of
190                  * 1/AVG*(CT_bus+CT_shunt).
191                  */
192                 *val = DIV_ROUND_CLOSEST(1000000, SAMPLING_PERIOD(chip));
193
194                 return IIO_VAL_INT;
195
196         case IIO_CHAN_INFO_SCALE:
197                 switch (chan->address) {
198                 case INA2XX_SHUNT_VOLTAGE:
199                         /* processed (mV) = raw/shunt_div */
200                         *val2 = chip->config->shunt_div;
201                         *val = 1;
202                         return IIO_VAL_FRACTIONAL;
203
204                 case INA2XX_BUS_VOLTAGE:
205                         /* processed (mV) = raw*lsb (uV) / (1000 << shift) */
206                         *val = chip->config->bus_voltage_lsb;
207                         *val2 = 1000 << chip->config->bus_voltage_shift;
208                         return IIO_VAL_FRACTIONAL;
209
210                 case INA2XX_POWER:
211                         /* processed (mW) = raw*lsb (uW) / 1000 */
212                         *val = chip->config->power_lsb;
213                         *val2 = 1000;
214                         return IIO_VAL_FRACTIONAL;
215
216                 case INA2XX_CURRENT:
217                         /* processed (mA) = raw (mA) */
218                         *val = 1;
219                         return IIO_VAL_INT;
220                 }
221         }
222
223         return -EINVAL;
224 }
225
226 /*
227  * Available averaging rates for ina226. The indices correspond with
228  * the bit values expected by the chip (according to the ina226 datasheet,
229  * table 3 AVG bit settings, found at
230  * http://www.ti.com/lit/ds/symlink/ina226.pdf.
231  */
232 static const int ina226_avg_tab[] = { 1, 4, 16, 64, 128, 256, 512, 1024 };
233
234 static int ina226_set_average(struct ina2xx_chip_info *chip, unsigned int val,
235                               unsigned int *config)
236 {
237         int bits;
238
239         if (val > 1024 || val < 1)
240                 return -EINVAL;
241
242         bits = find_closest(val, ina226_avg_tab,
243                             ARRAY_SIZE(ina226_avg_tab));
244
245         chip->avg = ina226_avg_tab[bits];
246
247         *config &= ~INA226_AVG_MASK;
248         *config |= INA226_SHIFT_AVG(bits) & INA226_AVG_MASK;
249
250         return 0;
251 }
252
253 /* Conversion times in uS */
254 static const int ina226_conv_time_tab[] = { 140, 204, 332, 588, 1100,
255                                             2116, 4156, 8244 };
256
257 static int ina226_set_int_time_vbus(struct ina2xx_chip_info *chip,
258                                     unsigned int val_us, unsigned int *config)
259 {
260         int bits;
261
262         if (val_us > 8244 || val_us < 140)
263                 return -EINVAL;
264
265         bits = find_closest(val_us, ina226_conv_time_tab,
266                             ARRAY_SIZE(ina226_conv_time_tab));
267
268         chip->int_time_vbus = ina226_conv_time_tab[bits];
269
270         *config &= ~INA226_ITB_MASK;
271         *config |= INA226_SHIFT_ITB(bits) & INA226_ITB_MASK;
272
273         return 0;
274 }
275
276 static int ina226_set_int_time_vshunt(struct ina2xx_chip_info *chip,
277                                       unsigned int val_us, unsigned int *config)
278 {
279         int bits;
280
281         if (val_us > 8244 || val_us < 140)
282                 return -EINVAL;
283
284         bits = find_closest(val_us, ina226_conv_time_tab,
285                             ARRAY_SIZE(ina226_conv_time_tab));
286
287         chip->int_time_vshunt = ina226_conv_time_tab[bits];
288
289         *config &= ~INA226_ITS_MASK;
290         *config |= INA226_SHIFT_ITS(bits) & INA226_ITS_MASK;
291
292         return 0;
293 }
294
295 /* Conversion times in uS. */
296 static const int ina219_conv_time_tab_subsample[] = { 84, 148, 276, 532 };
297 static const int ina219_conv_time_tab_average[] = { 532, 1060, 2130, 4260,
298                                                     8510, 17020, 34050, 68100};
299
300 static int ina219_lookup_int_time(unsigned int *val_us, int *bits)
301 {
302         if (*val_us > 68100 || *val_us < 84)
303                 return -EINVAL;
304
305         if (*val_us <= 532) {
306                 *bits = find_closest(*val_us, ina219_conv_time_tab_subsample,
307                                     ARRAY_SIZE(ina219_conv_time_tab_subsample));
308                 *val_us = ina219_conv_time_tab_subsample[*bits];
309         } else {
310                 *bits = find_closest(*val_us, ina219_conv_time_tab_average,
311                                     ARRAY_SIZE(ina219_conv_time_tab_average));
312                 *val_us = ina219_conv_time_tab_average[*bits];
313                 *bits |= 0x8;
314         }
315
316         return 0;
317 }
318
319 static int ina219_set_int_time_vbus(struct ina2xx_chip_info *chip,
320                                     unsigned int val_us, unsigned int *config)
321 {
322         int bits, ret;
323         unsigned int val_us_best = val_us;
324
325         ret = ina219_lookup_int_time(&val_us_best, &bits);
326         if (ret)
327                 return ret;
328
329         chip->int_time_vbus = val_us_best;
330
331         *config &= ~INA219_ITB_MASK;
332         *config |= INA219_SHIFT_ITB(bits) & INA219_ITB_MASK;
333
334         return 0;
335 }
336
337 static int ina219_set_int_time_vshunt(struct ina2xx_chip_info *chip,
338                                       unsigned int val_us, unsigned int *config)
339 {
340         int bits, ret;
341         unsigned int val_us_best = val_us;
342
343         ret = ina219_lookup_int_time(&val_us_best, &bits);
344         if (ret)
345                 return ret;
346
347         chip->int_time_vshunt = val_us_best;
348
349         *config &= ~INA219_ITS_MASK;
350         *config |= INA219_SHIFT_ITS(bits) & INA219_ITS_MASK;
351
352         return 0;
353 }
354
355 static int ina2xx_write_raw(struct iio_dev *indio_dev,
356                             struct iio_chan_spec const *chan,
357                             int val, int val2, long mask)
358 {
359         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
360         unsigned int config, tmp;
361         int ret;
362
363         if (iio_buffer_enabled(indio_dev))
364                 return -EBUSY;
365
366         mutex_lock(&chip->state_lock);
367
368         ret = regmap_read(chip->regmap, INA2XX_CONFIG, &config);
369         if (ret)
370                 goto err;
371
372         tmp = config;
373
374         switch (mask) {
375         case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
376                 ret = ina226_set_average(chip, val, &tmp);
377                 break;
378
379         case IIO_CHAN_INFO_INT_TIME:
380                 if (chip->config->chip_id == ina226) {
381                         if (chan->address == INA2XX_SHUNT_VOLTAGE)
382                                 ret = ina226_set_int_time_vshunt(chip, val2,
383                                                                  &tmp);
384                         else
385                                 ret = ina226_set_int_time_vbus(chip, val2,
386                                                                &tmp);
387                 } else {
388                         if (chan->address == INA2XX_SHUNT_VOLTAGE)
389                                 ret = ina219_set_int_time_vshunt(chip, val2,
390                                                                  &tmp);
391                         else
392                                 ret = ina219_set_int_time_vbus(chip, val2,
393                                                                &tmp);
394                 }
395                 break;
396
397         default:
398                 ret = -EINVAL;
399         }
400
401         if (!ret && (tmp != config))
402                 ret = regmap_write(chip->regmap, INA2XX_CONFIG, tmp);
403 err:
404         mutex_unlock(&chip->state_lock);
405
406         return ret;
407 }
408
409 static ssize_t ina2xx_allow_async_readout_show(struct device *dev,
410                                            struct device_attribute *attr,
411                                            char *buf)
412 {
413         struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
414
415         return sprintf(buf, "%d\n", chip->allow_async_readout);
416 }
417
418 static ssize_t ina2xx_allow_async_readout_store(struct device *dev,
419                                 struct device_attribute *attr,
420                                 const char *buf, size_t len)
421 {
422         struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
423         bool val;
424         int ret;
425
426         ret = strtobool((const char *) buf, &val);
427         if (ret)
428                 return ret;
429
430         chip->allow_async_readout = val;
431
432         return len;
433 }
434
435 /*
436  * Set current LSB to 1mA, shunt is in uOhms
437  * (equation 13 in datasheet). We hardcode a Current_LSB
438  * of 1.0 x10-6. The only remaining parameter is RShunt.
439  * There is no need to expose the CALIBRATION register
440  * to the user for now. But we need to reset this register
441  * if the user updates RShunt after driver init, e.g upon
442  * reading an EEPROM/Probe-type value.
443  */
444 static int ina2xx_set_calibration(struct ina2xx_chip_info *chip)
445 {
446         u16 regval = DIV_ROUND_CLOSEST(chip->config->calibration_factor,
447                                    chip->shunt_resistor);
448
449         return regmap_write(chip->regmap, INA2XX_CALIBRATION, regval);
450 }
451
452 static int set_shunt_resistor(struct ina2xx_chip_info *chip, unsigned int val)
453 {
454         if (val <= 0 || val > chip->config->calibration_factor)
455                 return -EINVAL;
456
457         chip->shunt_resistor = val;
458
459         return 0;
460 }
461
462 static ssize_t ina2xx_shunt_resistor_show(struct device *dev,
463                                           struct device_attribute *attr,
464                                           char *buf)
465 {
466         struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
467
468         return sprintf(buf, "%d\n", chip->shunt_resistor);
469 }
470
471 static ssize_t ina2xx_shunt_resistor_store(struct device *dev,
472                                            struct device_attribute *attr,
473                                            const char *buf, size_t len)
474 {
475         struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
476         unsigned long val;
477         int ret;
478
479         ret = kstrtoul((const char *) buf, 10, &val);
480         if (ret)
481                 return ret;
482
483         ret = set_shunt_resistor(chip, val);
484         if (ret)
485                 return ret;
486
487         /* Update the Calibration register */
488         ret = ina2xx_set_calibration(chip);
489         if (ret)
490                 return ret;
491
492         return len;
493 }
494
495 #define INA219_CHAN(_type, _index, _address) { \
496         .type = (_type), \
497         .address = (_address), \
498         .indexed = 1, \
499         .channel = (_index), \
500         .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
501                               BIT(IIO_CHAN_INFO_SCALE), \
502         .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ), \
503         .scan_index = (_index), \
504         .scan_type = { \
505                 .sign = 'u', \
506                 .realbits = 16, \
507                 .storagebits = 16, \
508                 .endianness = IIO_CPU, \
509         } \
510 }
511
512 #define INA226_CHAN(_type, _index, _address) { \
513         .type = (_type), \
514         .address = (_address), \
515         .indexed = 1, \
516         .channel = (_index), \
517         .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
518                               BIT(IIO_CHAN_INFO_SCALE), \
519         .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
520                                    BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
521         .scan_index = (_index), \
522         .scan_type = { \
523                 .sign = 'u', \
524                 .realbits = 16, \
525                 .storagebits = 16, \
526                 .endianness = IIO_CPU, \
527         } \
528 }
529
530 /*
531  * Sampling Freq is a consequence of the integration times of
532  * the Voltage channels.
533  */
534 #define INA219_CHAN_VOLTAGE(_index, _address) { \
535         .type = IIO_VOLTAGE, \
536         .address = (_address), \
537         .indexed = 1, \
538         .channel = (_index), \
539         .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
540                               BIT(IIO_CHAN_INFO_SCALE) | \
541                               BIT(IIO_CHAN_INFO_INT_TIME), \
542         .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ), \
543         .scan_index = (_index), \
544         .scan_type = { \
545                 .sign = 'u', \
546                 .realbits = 16, \
547                 .storagebits = 16, \
548                 .endianness = IIO_LE, \
549         } \
550 }
551
552 #define INA226_CHAN_VOLTAGE(_index, _address) { \
553         .type = IIO_VOLTAGE, \
554         .address = (_address), \
555         .indexed = 1, \
556         .channel = (_index), \
557         .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
558                               BIT(IIO_CHAN_INFO_SCALE) | \
559                               BIT(IIO_CHAN_INFO_INT_TIME), \
560         .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
561                                    BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
562         .scan_index = (_index), \
563         .scan_type = { \
564                 .sign = 'u', \
565                 .realbits = 16, \
566                 .storagebits = 16, \
567                 .endianness = IIO_LE, \
568         } \
569 }
570
571
572 static const struct iio_chan_spec ina226_channels[] = {
573         INA226_CHAN_VOLTAGE(0, INA2XX_SHUNT_VOLTAGE),
574         INA226_CHAN_VOLTAGE(1, INA2XX_BUS_VOLTAGE),
575         INA226_CHAN(IIO_POWER, 2, INA2XX_POWER),
576         INA226_CHAN(IIO_CURRENT, 3, INA2XX_CURRENT),
577         IIO_CHAN_SOFT_TIMESTAMP(4),
578 };
579
580 static const struct iio_chan_spec ina219_channels[] = {
581         INA219_CHAN_VOLTAGE(0, INA2XX_SHUNT_VOLTAGE),
582         INA219_CHAN_VOLTAGE(1, INA2XX_BUS_VOLTAGE),
583         INA219_CHAN(IIO_POWER, 2, INA2XX_POWER),
584         INA219_CHAN(IIO_CURRENT, 3, INA2XX_CURRENT),
585         IIO_CHAN_SOFT_TIMESTAMP(4),
586 };
587
588 static int ina2xx_work_buffer(struct iio_dev *indio_dev)
589 {
590         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
591         unsigned short data[8];
592         int bit, ret, i = 0;
593         s64 time_a, time_b;
594         unsigned int alert;
595
596         time_a = iio_get_time_ns(indio_dev);
597
598         /*
599          * Because the timer thread and the chip conversion clock
600          * are asynchronous, the period difference will eventually
601          * result in reading V[k-1] again, or skip V[k] at time Tk.
602          * In order to resync the timer with the conversion process
603          * we check the ConVersionReadyFlag.
604          * On hardware that supports using the ALERT pin to toggle a
605          * GPIO a triggered buffer could be used instead.
606          * For now, we pay for that extra read of the ALERT register
607          */
608         if (!chip->allow_async_readout)
609                 do {
610                         ret = regmap_read(chip->regmap, INA226_MASK_ENABLE,
611                                           &alert);
612                         if (ret < 0)
613                                 return ret;
614
615                         alert &= INA226_CVRF;
616                 } while (!alert);
617
618         /*
619          * Single register reads: bulk_read will not work with ina226
620          * as there is no auto-increment of the address register for
621          * data length longer than 16bits.
622          */
623         for_each_set_bit(bit, indio_dev->active_scan_mask,
624                          indio_dev->masklength) {
625                 unsigned int val;
626
627                 ret = regmap_read(chip->regmap,
628                                   INA2XX_SHUNT_VOLTAGE + bit, &val);
629                 if (ret < 0)
630                         return ret;
631
632                 data[i++] = val;
633         }
634
635         time_b = iio_get_time_ns(indio_dev);
636
637         iio_push_to_buffers_with_timestamp(indio_dev,
638                                            (unsigned int *)data, time_a);
639
640         return (unsigned long)(time_b - time_a) / 1000;
641 };
642
643 static int ina2xx_capture_thread(void *data)
644 {
645         struct iio_dev *indio_dev = data;
646         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
647         unsigned int sampling_us = SAMPLING_PERIOD(chip);
648         int buffer_us;
649
650         /*
651          * Poll a bit faster than the chip internal Fs, in case
652          * we wish to sync with the conversion ready flag.
653          */
654         if (!chip->allow_async_readout)
655                 sampling_us -= 200;
656
657         do {
658                 buffer_us = ina2xx_work_buffer(indio_dev);
659                 if (buffer_us < 0)
660                         return buffer_us;
661
662                 if (sampling_us > buffer_us)
663                         udelay(sampling_us - buffer_us);
664
665         } while (!kthread_should_stop());
666
667         return 0;
668 }
669
670 static int ina2xx_buffer_enable(struct iio_dev *indio_dev)
671 {
672         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
673         unsigned int sampling_us = SAMPLING_PERIOD(chip);
674
675         dev_dbg(&indio_dev->dev, "Enabling buffer w/ scan_mask %02x, freq = %d, avg =%u\n",
676                 (unsigned int)(*indio_dev->active_scan_mask),
677                 1000000 / sampling_us, chip->avg);
678
679         dev_dbg(&indio_dev->dev, "Expected work period: %u us\n", sampling_us);
680         dev_dbg(&indio_dev->dev, "Async readout mode: %d\n",
681                 chip->allow_async_readout);
682
683         chip->task = kthread_run(ina2xx_capture_thread, (void *)indio_dev,
684                                  "%s:%d-%uus", indio_dev->name, indio_dev->id,
685                                  sampling_us);
686
687         return PTR_ERR_OR_ZERO(chip->task);
688 }
689
690 static int ina2xx_buffer_disable(struct iio_dev *indio_dev)
691 {
692         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
693
694         if (chip->task) {
695                 kthread_stop(chip->task);
696                 chip->task = NULL;
697         }
698
699         return 0;
700 }
701
702 static const struct iio_buffer_setup_ops ina2xx_setup_ops = {
703         .postenable = &ina2xx_buffer_enable,
704         .predisable = &ina2xx_buffer_disable,
705 };
706
707 static int ina2xx_debug_reg(struct iio_dev *indio_dev,
708                             unsigned reg, unsigned writeval, unsigned *readval)
709 {
710         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
711
712         if (!readval)
713                 return regmap_write(chip->regmap, reg, writeval);
714
715         return regmap_read(chip->regmap, reg, readval);
716 }
717
718 /* Possible integration times for vshunt and vbus */
719 static IIO_CONST_ATTR_NAMED(ina219_integration_time_available,
720                             integration_time_available,
721                             "0.000084 0.000148 0.000276 0.000532 0.001060 0.002130 0.004260 0.008510 0.017020 0.034050 0.068100");
722
723 static IIO_CONST_ATTR_NAMED(ina226_integration_time_available,
724                             integration_time_available,
725                             "0.000140 0.000204 0.000332 0.000588 0.001100 0.002116 0.004156 0.008244");
726
727
728 static IIO_DEVICE_ATTR(in_allow_async_readout, S_IRUGO | S_IWUSR,
729                        ina2xx_allow_async_readout_show,
730                        ina2xx_allow_async_readout_store, 0);
731
732 static IIO_DEVICE_ATTR(in_shunt_resistor, S_IRUGO | S_IWUSR,
733                        ina2xx_shunt_resistor_show,
734                        ina2xx_shunt_resistor_store, 0);
735
736 static struct attribute *ina219_attributes[] = {
737         &iio_dev_attr_in_allow_async_readout.dev_attr.attr,
738         &iio_const_attr_ina219_integration_time_available.dev_attr.attr,
739         &iio_dev_attr_in_shunt_resistor.dev_attr.attr,
740         NULL,
741 };
742
743 static struct attribute *ina226_attributes[] = {
744         &iio_dev_attr_in_allow_async_readout.dev_attr.attr,
745         &iio_const_attr_ina226_integration_time_available.dev_attr.attr,
746         &iio_dev_attr_in_shunt_resistor.dev_attr.attr,
747         NULL,
748 };
749
750 static const struct attribute_group ina219_attribute_group = {
751         .attrs = ina219_attributes,
752 };
753
754 static const struct attribute_group ina226_attribute_group = {
755         .attrs = ina226_attributes,
756 };
757
758 static const struct iio_info ina219_info = {
759         .driver_module = THIS_MODULE,
760         .attrs = &ina219_attribute_group,
761         .read_raw = ina2xx_read_raw,
762         .write_raw = ina2xx_write_raw,
763         .debugfs_reg_access = ina2xx_debug_reg,
764 };
765
766 static const struct iio_info ina226_info = {
767         .driver_module = THIS_MODULE,
768         .attrs = &ina226_attribute_group,
769         .read_raw = ina2xx_read_raw,
770         .write_raw = ina2xx_write_raw,
771         .debugfs_reg_access = ina2xx_debug_reg,
772 };
773
774 /* Initialize the configuration and calibration registers. */
775 static int ina2xx_init(struct ina2xx_chip_info *chip, unsigned int config)
776 {
777         int ret = regmap_write(chip->regmap, INA2XX_CONFIG, config);
778         if (ret)
779                 return ret;
780
781         return ina2xx_set_calibration(chip);
782 }
783
784 static int ina2xx_probe(struct i2c_client *client,
785                         const struct i2c_device_id *id)
786 {
787         struct ina2xx_chip_info *chip;
788         struct iio_dev *indio_dev;
789         struct iio_buffer *buffer;
790         unsigned int val;
791         enum ina2xx_ids type;
792         int ret;
793
794         indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*chip));
795         if (!indio_dev)
796                 return -ENOMEM;
797
798         chip = iio_priv(indio_dev);
799
800         /* This is only used for device removal purposes. */
801         i2c_set_clientdata(client, indio_dev);
802
803         chip->regmap = devm_regmap_init_i2c(client, &ina2xx_regmap_config);
804         if (IS_ERR(chip->regmap)) {
805                 dev_err(&client->dev, "failed to allocate register map\n");
806                 return PTR_ERR(chip->regmap);
807         }
808
809         if (client->dev.of_node)
810                 type = (enum ina2xx_ids)of_device_get_match_data(&client->dev);
811         else
812                 type = id->driver_data;
813         chip->config = &ina2xx_config[type];
814
815         mutex_init(&chip->state_lock);
816
817         if (of_property_read_u32(client->dev.of_node,
818                                  "shunt-resistor", &val) < 0) {
819                 struct ina2xx_platform_data *pdata =
820                     dev_get_platdata(&client->dev);
821
822                 if (pdata)
823                         val = pdata->shunt_uohms;
824                 else
825                         val = INA2XX_RSHUNT_DEFAULT;
826         }
827
828         ret = set_shunt_resistor(chip, val);
829         if (ret)
830                 return ret;
831
832         /* Patch the current config register with default. */
833         val = chip->config->config_default;
834
835         if (id->driver_data == ina226) {
836                 ina226_set_average(chip, INA226_DEFAULT_AVG, &val);
837                 ina226_set_int_time_vbus(chip, INA226_DEFAULT_IT, &val);
838                 ina226_set_int_time_vshunt(chip, INA226_DEFAULT_IT, &val);
839         } else {
840                 chip->avg = 1;
841                 ina219_set_int_time_vbus(chip, INA219_DEFAULT_IT, &val);
842                 ina219_set_int_time_vshunt(chip, INA219_DEFAULT_IT, &val);
843         }
844
845         ret = ina2xx_init(chip, val);
846         if (ret) {
847                 dev_err(&client->dev, "error configuring the device\n");
848                 return ret;
849         }
850
851         indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
852         indio_dev->dev.parent = &client->dev;
853         indio_dev->dev.of_node = client->dev.of_node;
854         if (id->driver_data == ina226) {
855                 indio_dev->channels = ina226_channels;
856                 indio_dev->num_channels = ARRAY_SIZE(ina226_channels);
857                 indio_dev->info = &ina226_info;
858         } else {
859                 indio_dev->channels = ina219_channels;
860                 indio_dev->num_channels = ARRAY_SIZE(ina219_channels);
861                 indio_dev->info = &ina219_info;
862         }
863         indio_dev->name = id->name;
864         indio_dev->setup_ops = &ina2xx_setup_ops;
865
866         buffer = devm_iio_kfifo_allocate(&indio_dev->dev);
867         if (!buffer)
868                 return -ENOMEM;
869
870         iio_device_attach_buffer(indio_dev, buffer);
871
872         return iio_device_register(indio_dev);
873 }
874
875 static int ina2xx_remove(struct i2c_client *client)
876 {
877         struct iio_dev *indio_dev = i2c_get_clientdata(client);
878         struct ina2xx_chip_info *chip = iio_priv(indio_dev);
879
880         iio_device_unregister(indio_dev);
881
882         /* Powerdown */
883         return regmap_update_bits(chip->regmap, INA2XX_CONFIG,
884                                   INA2XX_MODE_MASK, 0);
885 }
886
887 static const struct i2c_device_id ina2xx_id[] = {
888         {"ina219", ina219},
889         {"ina220", ina219},
890         {"ina226", ina226},
891         {"ina230", ina226},
892         {"ina231", ina226},
893         {}
894 };
895 MODULE_DEVICE_TABLE(i2c, ina2xx_id);
896
897 static const struct of_device_id ina2xx_of_match[] = {
898         {
899                 .compatible = "ti,ina219",
900                 .data = (void *)ina219
901         },
902         {
903                 .compatible = "ti,ina220",
904                 .data = (void *)ina219
905         },
906         {
907                 .compatible = "ti,ina226",
908                 .data = (void *)ina226
909         },
910         {
911                 .compatible = "ti,ina230",
912                 .data = (void *)ina226
913         },
914         {
915                 .compatible = "ti,ina231",
916                 .data = (void *)ina226
917         },
918         {},
919 };
920 MODULE_DEVICE_TABLE(of, ina2xx_of_match);
921
922 static struct i2c_driver ina2xx_driver = {
923         .driver = {
924                    .name = KBUILD_MODNAME,
925                    .of_match_table = ina2xx_of_match,
926         },
927         .probe = ina2xx_probe,
928         .remove = ina2xx_remove,
929         .id_table = ina2xx_id,
930 };
931 module_i2c_driver(ina2xx_driver);
932
933 MODULE_AUTHOR("Marc Titinger <marc.titinger@baylibre.com>");
934 MODULE_DESCRIPTION("Texas Instruments INA2XX ADC driver");
935 MODULE_LICENSE("GPL v2");