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