Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * INA2XX Current and Power Monitors
0003  *
0004  * Copyright 2015 Baylibre SAS.
0005  *
0006  * This program is free software; you can redistribute it and/or modify
0007  * it under the terms of the GNU General Public License version 2 as
0008  * published by the Free Software Foundation.
0009  *
0010  * Based on linux/drivers/iio/adc/ad7291.c
0011  * Copyright 2010-2011 Analog Devices Inc.
0012  *
0013  * Based on linux/drivers/hwmon/ina2xx.c
0014  * Copyright 2012 Lothar Felten <l-felten@ti.com>
0015  *
0016  * Licensed under the GPL-2 or later.
0017  *
0018  * IIO driver for INA219-220-226-230-231
0019  *
0020  * Configurable 7-bit I2C slave address from 0x40 to 0x4F
0021  */
0022 
0023 #include <linux/delay.h>
0024 #include <linux/i2c.h>
0025 #include <linux/iio/iio.h>
0026 #include <linux/iio/buffer.h>
0027 #include <linux/iio/kfifo_buf.h>
0028 #include <linux/iio/sysfs.h>
0029 #include <linux/kthread.h>
0030 #include <linux/module.h>
0031 #include <linux/of_device.h>
0032 #include <linux/regmap.h>
0033 #include <linux/sched/task.h>
0034 #include <linux/util_macros.h>
0035 
0036 #include <linux/platform_data/ina2xx.h>
0037 
0038 /* INA2XX registers definition */
0039 #define INA2XX_CONFIG                   0x00
0040 #define INA2XX_SHUNT_VOLTAGE            0x01    /* readonly */
0041 #define INA2XX_BUS_VOLTAGE              0x02    /* readonly */
0042 #define INA2XX_POWER                    0x03    /* readonly */
0043 #define INA2XX_CURRENT                  0x04    /* readonly */
0044 #define INA2XX_CALIBRATION              0x05
0045 
0046 #define INA226_MASK_ENABLE      0x06
0047 #define INA226_CVRF         BIT(3)
0048 
0049 #define INA2XX_MAX_REGISTERS            8
0050 
0051 /* settings - depend on use case */
0052 #define INA219_CONFIG_DEFAULT           0x399F  /* PGA=1/8, BRNG=32V */
0053 #define INA219_DEFAULT_IT       532
0054 #define INA219_DEFAULT_BRNG             1   /* 32V */
0055 #define INA219_DEFAULT_PGA              125 /* 1000/8 */
0056 #define INA226_CONFIG_DEFAULT           0x4327
0057 #define INA226_DEFAULT_AVG              4
0058 #define INA226_DEFAULT_IT       1110
0059 
0060 #define INA2XX_RSHUNT_DEFAULT           10000
0061 
0062 /*
0063  * bit masks for reading the settings in the configuration register
0064  * FIXME: use regmap_fields.
0065  */
0066 #define INA2XX_MODE_MASK    GENMASK(3, 0)
0067 
0068 /* Gain for VShunt: 1/8 (default), 1/4, 1/2, 1 */
0069 #define INA219_PGA_MASK     GENMASK(12, 11)
0070 #define INA219_SHIFT_PGA(val)   ((val) << 11)
0071 
0072 /* VBus range: 32V (default), 16V */
0073 #define INA219_BRNG_MASK    BIT(13)
0074 #define INA219_SHIFT_BRNG(val)  ((val) << 13)
0075 
0076 /* Averaging for VBus/VShunt/Power */
0077 #define INA226_AVG_MASK     GENMASK(11, 9)
0078 #define INA226_SHIFT_AVG(val)   ((val) << 9)
0079 
0080 /* Integration time for VBus */
0081 #define INA219_ITB_MASK     GENMASK(10, 7)
0082 #define INA219_SHIFT_ITB(val)   ((val) << 7)
0083 #define INA226_ITB_MASK     GENMASK(8, 6)
0084 #define INA226_SHIFT_ITB(val)   ((val) << 6)
0085 
0086 /* Integration time for VShunt */
0087 #define INA219_ITS_MASK     GENMASK(6, 3)
0088 #define INA219_SHIFT_ITS(val)   ((val) << 3)
0089 #define INA226_ITS_MASK     GENMASK(5, 3)
0090 #define INA226_SHIFT_ITS(val)   ((val) << 3)
0091 
0092 /* INA219 Bus voltage register, low bits are flags */
0093 #define INA219_OVF      BIT(0)
0094 #define INA219_CNVR     BIT(1)
0095 #define INA219_BUS_VOLTAGE_SHIFT    3
0096 
0097 /* Cosmetic macro giving the sampling period for a full P=UxI cycle */
0098 #define SAMPLING_PERIOD(c)  ((c->int_time_vbus + c->int_time_vshunt) \
0099                  * c->avg)
0100 
0101 static bool ina2xx_is_writeable_reg(struct device *dev, unsigned int reg)
0102 {
0103     return (reg == INA2XX_CONFIG) || (reg > INA2XX_CURRENT);
0104 }
0105 
0106 static bool ina2xx_is_volatile_reg(struct device *dev, unsigned int reg)
0107 {
0108     return (reg != INA2XX_CONFIG);
0109 }
0110 
0111 static inline bool is_signed_reg(unsigned int reg)
0112 {
0113     return (reg == INA2XX_SHUNT_VOLTAGE) || (reg == INA2XX_CURRENT);
0114 }
0115 
0116 static const struct regmap_config ina2xx_regmap_config = {
0117     .reg_bits = 8,
0118     .val_bits = 16,
0119     .max_register = INA2XX_MAX_REGISTERS,
0120     .writeable_reg = ina2xx_is_writeable_reg,
0121     .volatile_reg = ina2xx_is_volatile_reg,
0122 };
0123 
0124 enum ina2xx_ids { ina219, ina226 };
0125 
0126 struct ina2xx_config {
0127     u16 config_default;
0128     int calibration_value;
0129     int shunt_voltage_lsb;  /* nV */
0130     int bus_voltage_shift;  /* position of lsb */
0131     int bus_voltage_lsb;    /* uV */
0132     /* fixed relation between current and power lsb, uW/uA */
0133     int power_lsb_factor;
0134     enum ina2xx_ids chip_id;
0135 };
0136 
0137 struct ina2xx_chip_info {
0138     struct regmap *regmap;
0139     struct task_struct *task;
0140     const struct ina2xx_config *config;
0141     struct mutex state_lock;
0142     unsigned int shunt_resistor_uohm;
0143     int avg;
0144     int int_time_vbus; /* Bus voltage integration time uS */
0145     int int_time_vshunt; /* Shunt voltage integration time uS */
0146     int range_vbus; /* Bus voltage maximum in V */
0147     int pga_gain_vshunt; /* Shunt voltage PGA gain */
0148     bool allow_async_readout;
0149     /* data buffer needs space for channel data and timestamp */
0150     struct {
0151         u16 chan[4];
0152         u64 ts __aligned(8);
0153     } scan;
0154 };
0155 
0156 static const struct ina2xx_config ina2xx_config[] = {
0157     [ina219] = {
0158         .config_default = INA219_CONFIG_DEFAULT,
0159         .calibration_value = 4096,
0160         .shunt_voltage_lsb = 10000,
0161         .bus_voltage_shift = INA219_BUS_VOLTAGE_SHIFT,
0162         .bus_voltage_lsb = 4000,
0163         .power_lsb_factor = 20,
0164         .chip_id = ina219,
0165     },
0166     [ina226] = {
0167         .config_default = INA226_CONFIG_DEFAULT,
0168         .calibration_value = 2048,
0169         .shunt_voltage_lsb = 2500,
0170         .bus_voltage_shift = 0,
0171         .bus_voltage_lsb = 1250,
0172         .power_lsb_factor = 25,
0173         .chip_id = ina226,
0174     },
0175 };
0176 
0177 static int ina2xx_read_raw(struct iio_dev *indio_dev,
0178                struct iio_chan_spec const *chan,
0179                int *val, int *val2, long mask)
0180 {
0181     int ret;
0182     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0183     unsigned int regval;
0184 
0185     switch (mask) {
0186     case IIO_CHAN_INFO_RAW:
0187         ret = regmap_read(chip->regmap, chan->address, &regval);
0188         if (ret)
0189             return ret;
0190 
0191         if (is_signed_reg(chan->address))
0192             *val = (s16) regval;
0193         else
0194             *val  = regval;
0195 
0196         if (chan->address == INA2XX_BUS_VOLTAGE)
0197             *val >>= chip->config->bus_voltage_shift;
0198 
0199         return IIO_VAL_INT;
0200 
0201     case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
0202         *val = chip->avg;
0203         return IIO_VAL_INT;
0204 
0205     case IIO_CHAN_INFO_INT_TIME:
0206         *val = 0;
0207         if (chan->address == INA2XX_SHUNT_VOLTAGE)
0208             *val2 = chip->int_time_vshunt;
0209         else
0210             *val2 = chip->int_time_vbus;
0211 
0212         return IIO_VAL_INT_PLUS_MICRO;
0213 
0214     case IIO_CHAN_INFO_SAMP_FREQ:
0215         /*
0216          * Sample freq is read only, it is a consequence of
0217          * 1/AVG*(CT_bus+CT_shunt).
0218          */
0219         *val = DIV_ROUND_CLOSEST(1000000, SAMPLING_PERIOD(chip));
0220 
0221         return IIO_VAL_INT;
0222 
0223     case IIO_CHAN_INFO_SCALE:
0224         switch (chan->address) {
0225         case INA2XX_SHUNT_VOLTAGE:
0226             /* processed (mV) = raw * lsb(nV) / 1000000 */
0227             *val = chip->config->shunt_voltage_lsb;
0228             *val2 = 1000000;
0229             return IIO_VAL_FRACTIONAL;
0230 
0231         case INA2XX_BUS_VOLTAGE:
0232             /* processed (mV) = raw * lsb (uV) / 1000 */
0233             *val = chip->config->bus_voltage_lsb;
0234             *val2 = 1000;
0235             return IIO_VAL_FRACTIONAL;
0236 
0237         case INA2XX_CURRENT:
0238             /*
0239              * processed (mA) = raw * current_lsb (mA)
0240              * current_lsb (mA) = shunt_voltage_lsb (nV) /
0241              *                    shunt_resistor (uOhm)
0242              */
0243             *val = chip->config->shunt_voltage_lsb;
0244             *val2 = chip->shunt_resistor_uohm;
0245             return IIO_VAL_FRACTIONAL;
0246 
0247         case INA2XX_POWER:
0248             /*
0249              * processed (mW) = raw * power_lsb (mW)
0250              * power_lsb (mW) = power_lsb_factor (mW/mA) *
0251              *                  current_lsb (mA)
0252              */
0253             *val = chip->config->power_lsb_factor *
0254                    chip->config->shunt_voltage_lsb;
0255             *val2 = chip->shunt_resistor_uohm;
0256             return IIO_VAL_FRACTIONAL;
0257         }
0258         return -EINVAL;
0259 
0260     case IIO_CHAN_INFO_HARDWAREGAIN:
0261         switch (chan->address) {
0262         case INA2XX_SHUNT_VOLTAGE:
0263             *val = chip->pga_gain_vshunt;
0264             *val2 = 1000;
0265             return IIO_VAL_FRACTIONAL;
0266 
0267         case INA2XX_BUS_VOLTAGE:
0268             *val = chip->range_vbus == 32 ? 1 : 2;
0269             return IIO_VAL_INT;
0270         }
0271         return -EINVAL;
0272     }
0273 
0274     return -EINVAL;
0275 }
0276 
0277 /*
0278  * Available averaging rates for ina226. The indices correspond with
0279  * the bit values expected by the chip (according to the ina226 datasheet,
0280  * table 3 AVG bit settings, found at
0281  * https://www.ti.com/lit/ds/symlink/ina226.pdf.
0282  */
0283 static const int ina226_avg_tab[] = { 1, 4, 16, 64, 128, 256, 512, 1024 };
0284 
0285 static int ina226_set_average(struct ina2xx_chip_info *chip, unsigned int val,
0286                   unsigned int *config)
0287 {
0288     int bits;
0289 
0290     if (val > 1024 || val < 1)
0291         return -EINVAL;
0292 
0293     bits = find_closest(val, ina226_avg_tab,
0294                 ARRAY_SIZE(ina226_avg_tab));
0295 
0296     chip->avg = ina226_avg_tab[bits];
0297 
0298     *config &= ~INA226_AVG_MASK;
0299     *config |= INA226_SHIFT_AVG(bits) & INA226_AVG_MASK;
0300 
0301     return 0;
0302 }
0303 
0304 /* Conversion times in uS */
0305 static const int ina226_conv_time_tab[] = { 140, 204, 332, 588, 1100,
0306                         2116, 4156, 8244 };
0307 
0308 static int ina226_set_int_time_vbus(struct ina2xx_chip_info *chip,
0309                     unsigned int val_us, unsigned int *config)
0310 {
0311     int bits;
0312 
0313     if (val_us > 8244 || val_us < 140)
0314         return -EINVAL;
0315 
0316     bits = find_closest(val_us, ina226_conv_time_tab,
0317                 ARRAY_SIZE(ina226_conv_time_tab));
0318 
0319     chip->int_time_vbus = ina226_conv_time_tab[bits];
0320 
0321     *config &= ~INA226_ITB_MASK;
0322     *config |= INA226_SHIFT_ITB(bits) & INA226_ITB_MASK;
0323 
0324     return 0;
0325 }
0326 
0327 static int ina226_set_int_time_vshunt(struct ina2xx_chip_info *chip,
0328                       unsigned int val_us, unsigned int *config)
0329 {
0330     int bits;
0331 
0332     if (val_us > 8244 || val_us < 140)
0333         return -EINVAL;
0334 
0335     bits = find_closest(val_us, ina226_conv_time_tab,
0336                 ARRAY_SIZE(ina226_conv_time_tab));
0337 
0338     chip->int_time_vshunt = ina226_conv_time_tab[bits];
0339 
0340     *config &= ~INA226_ITS_MASK;
0341     *config |= INA226_SHIFT_ITS(bits) & INA226_ITS_MASK;
0342 
0343     return 0;
0344 }
0345 
0346 /* Conversion times in uS. */
0347 static const int ina219_conv_time_tab_subsample[] = { 84, 148, 276, 532 };
0348 static const int ina219_conv_time_tab_average[] = { 532, 1060, 2130, 4260,
0349                             8510, 17020, 34050, 68100};
0350 
0351 static int ina219_lookup_int_time(unsigned int *val_us, int *bits)
0352 {
0353     if (*val_us > 68100 || *val_us < 84)
0354         return -EINVAL;
0355 
0356     if (*val_us <= 532) {
0357         *bits = find_closest(*val_us, ina219_conv_time_tab_subsample,
0358                     ARRAY_SIZE(ina219_conv_time_tab_subsample));
0359         *val_us = ina219_conv_time_tab_subsample[*bits];
0360     } else {
0361         *bits = find_closest(*val_us, ina219_conv_time_tab_average,
0362                     ARRAY_SIZE(ina219_conv_time_tab_average));
0363         *val_us = ina219_conv_time_tab_average[*bits];
0364         *bits |= 0x8;
0365     }
0366 
0367     return 0;
0368 }
0369 
0370 static int ina219_set_int_time_vbus(struct ina2xx_chip_info *chip,
0371                     unsigned int val_us, unsigned int *config)
0372 {
0373     int bits, ret;
0374     unsigned int val_us_best = val_us;
0375 
0376     ret = ina219_lookup_int_time(&val_us_best, &bits);
0377     if (ret)
0378         return ret;
0379 
0380     chip->int_time_vbus = val_us_best;
0381 
0382     *config &= ~INA219_ITB_MASK;
0383     *config |= INA219_SHIFT_ITB(bits) & INA219_ITB_MASK;
0384 
0385     return 0;
0386 }
0387 
0388 static int ina219_set_int_time_vshunt(struct ina2xx_chip_info *chip,
0389                       unsigned int val_us, unsigned int *config)
0390 {
0391     int bits, ret;
0392     unsigned int val_us_best = val_us;
0393 
0394     ret = ina219_lookup_int_time(&val_us_best, &bits);
0395     if (ret)
0396         return ret;
0397 
0398     chip->int_time_vshunt = val_us_best;
0399 
0400     *config &= ~INA219_ITS_MASK;
0401     *config |= INA219_SHIFT_ITS(bits) & INA219_ITS_MASK;
0402 
0403     return 0;
0404 }
0405 
0406 static const int ina219_vbus_range_tab[] = { 1, 2 };
0407 static int ina219_set_vbus_range_denom(struct ina2xx_chip_info *chip,
0408                        unsigned int range,
0409                        unsigned int *config)
0410 {
0411     if (range == 1)
0412         chip->range_vbus = 32;
0413     else if (range == 2)
0414         chip->range_vbus = 16;
0415     else
0416         return -EINVAL;
0417 
0418     *config &= ~INA219_BRNG_MASK;
0419     *config |= INA219_SHIFT_BRNG(range == 1 ? 1 : 0) & INA219_BRNG_MASK;
0420 
0421     return 0;
0422 }
0423 
0424 static const int ina219_vshunt_gain_tab[] = { 125, 250, 500, 1000 };
0425 static const int ina219_vshunt_gain_frac[] = {
0426     125, 1000, 250, 1000, 500, 1000, 1000, 1000 };
0427 
0428 static int ina219_set_vshunt_pga_gain(struct ina2xx_chip_info *chip,
0429                       unsigned int gain,
0430                       unsigned int *config)
0431 {
0432     int bits;
0433 
0434     if (gain < 125 || gain > 1000)
0435         return -EINVAL;
0436 
0437     bits = find_closest(gain, ina219_vshunt_gain_tab,
0438                 ARRAY_SIZE(ina219_vshunt_gain_tab));
0439 
0440     chip->pga_gain_vshunt = ina219_vshunt_gain_tab[bits];
0441     bits = 3 - bits;
0442 
0443     *config &= ~INA219_PGA_MASK;
0444     *config |= INA219_SHIFT_PGA(bits) & INA219_PGA_MASK;
0445 
0446     return 0;
0447 }
0448 
0449 static int ina2xx_read_avail(struct iio_dev *indio_dev,
0450                  struct iio_chan_spec const *chan,
0451                  const int **vals, int *type, int *length,
0452                  long mask)
0453 {
0454     switch (mask) {
0455     case IIO_CHAN_INFO_HARDWAREGAIN:
0456         switch (chan->address) {
0457         case INA2XX_SHUNT_VOLTAGE:
0458             *type = IIO_VAL_FRACTIONAL;
0459             *length = sizeof(ina219_vshunt_gain_frac) / sizeof(int);
0460             *vals = ina219_vshunt_gain_frac;
0461             return IIO_AVAIL_LIST;
0462 
0463         case INA2XX_BUS_VOLTAGE:
0464             *type = IIO_VAL_INT;
0465             *length = sizeof(ina219_vbus_range_tab) / sizeof(int);
0466             *vals = ina219_vbus_range_tab;
0467             return IIO_AVAIL_LIST;
0468         }
0469     }
0470 
0471     return -EINVAL;
0472 }
0473 
0474 static int ina2xx_write_raw(struct iio_dev *indio_dev,
0475                 struct iio_chan_spec const *chan,
0476                 int val, int val2, long mask)
0477 {
0478     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0479     unsigned int config, tmp;
0480     int ret;
0481 
0482     if (iio_buffer_enabled(indio_dev))
0483         return -EBUSY;
0484 
0485     mutex_lock(&chip->state_lock);
0486 
0487     ret = regmap_read(chip->regmap, INA2XX_CONFIG, &config);
0488     if (ret)
0489         goto err;
0490 
0491     tmp = config;
0492 
0493     switch (mask) {
0494     case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
0495         ret = ina226_set_average(chip, val, &tmp);
0496         break;
0497 
0498     case IIO_CHAN_INFO_INT_TIME:
0499         if (chip->config->chip_id == ina226) {
0500             if (chan->address == INA2XX_SHUNT_VOLTAGE)
0501                 ret = ina226_set_int_time_vshunt(chip, val2,
0502                                  &tmp);
0503             else
0504                 ret = ina226_set_int_time_vbus(chip, val2,
0505                                    &tmp);
0506         } else {
0507             if (chan->address == INA2XX_SHUNT_VOLTAGE)
0508                 ret = ina219_set_int_time_vshunt(chip, val2,
0509                                  &tmp);
0510             else
0511                 ret = ina219_set_int_time_vbus(chip, val2,
0512                                    &tmp);
0513         }
0514         break;
0515 
0516     case IIO_CHAN_INFO_HARDWAREGAIN:
0517         if (chan->address == INA2XX_SHUNT_VOLTAGE)
0518             ret = ina219_set_vshunt_pga_gain(chip, val * 1000 +
0519                              val2 / 1000, &tmp);
0520         else
0521             ret = ina219_set_vbus_range_denom(chip, val, &tmp);
0522         break;
0523 
0524     default:
0525         ret = -EINVAL;
0526     }
0527 
0528     if (!ret && (tmp != config))
0529         ret = regmap_write(chip->regmap, INA2XX_CONFIG, tmp);
0530 err:
0531     mutex_unlock(&chip->state_lock);
0532 
0533     return ret;
0534 }
0535 
0536 static ssize_t ina2xx_allow_async_readout_show(struct device *dev,
0537                        struct device_attribute *attr,
0538                        char *buf)
0539 {
0540     struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
0541 
0542     return sysfs_emit(buf, "%d\n", chip->allow_async_readout);
0543 }
0544 
0545 static ssize_t ina2xx_allow_async_readout_store(struct device *dev,
0546                 struct device_attribute *attr,
0547                 const char *buf, size_t len)
0548 {
0549     struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
0550     bool val;
0551     int ret;
0552 
0553     ret = kstrtobool(buf, &val);
0554     if (ret)
0555         return ret;
0556 
0557     chip->allow_async_readout = val;
0558 
0559     return len;
0560 }
0561 
0562 /*
0563  * Calibration register is set to the best value, which eliminates
0564  * truncation errors on calculating current register in hardware.
0565  * According to datasheet (INA 226: eq. 3, INA219: eq. 4) the best values
0566  * are 2048 for ina226 and 4096 for ina219. They are hardcoded as
0567  * calibration_value.
0568  */
0569 static int ina2xx_set_calibration(struct ina2xx_chip_info *chip)
0570 {
0571     return regmap_write(chip->regmap, INA2XX_CALIBRATION,
0572                 chip->config->calibration_value);
0573 }
0574 
0575 static int set_shunt_resistor(struct ina2xx_chip_info *chip, unsigned int val)
0576 {
0577     if (val == 0 || val > INT_MAX)
0578         return -EINVAL;
0579 
0580     chip->shunt_resistor_uohm = val;
0581 
0582     return 0;
0583 }
0584 
0585 static ssize_t ina2xx_shunt_resistor_show(struct device *dev,
0586                       struct device_attribute *attr,
0587                       char *buf)
0588 {
0589     struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
0590     int vals[2] = { chip->shunt_resistor_uohm, 1000000 };
0591 
0592     return iio_format_value(buf, IIO_VAL_FRACTIONAL, 1, vals);
0593 }
0594 
0595 static ssize_t ina2xx_shunt_resistor_store(struct device *dev,
0596                        struct device_attribute *attr,
0597                        const char *buf, size_t len)
0598 {
0599     struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
0600     int val, val_fract, ret;
0601 
0602     ret = iio_str_to_fixpoint(buf, 100000, &val, &val_fract);
0603     if (ret)
0604         return ret;
0605 
0606     ret = set_shunt_resistor(chip, val * 1000000 + val_fract);
0607     if (ret)
0608         return ret;
0609 
0610     return len;
0611 }
0612 
0613 #define INA219_CHAN(_type, _index, _address) { \
0614     .type = (_type), \
0615     .address = (_address), \
0616     .indexed = 1, \
0617     .channel = (_index), \
0618     .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
0619                   BIT(IIO_CHAN_INFO_SCALE), \
0620     .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ), \
0621     .scan_index = (_index), \
0622     .scan_type = { \
0623         .sign = 'u', \
0624         .realbits = 16, \
0625         .storagebits = 16, \
0626         .endianness = IIO_CPU, \
0627     } \
0628 }
0629 
0630 #define INA226_CHAN(_type, _index, _address) { \
0631     .type = (_type), \
0632     .address = (_address), \
0633     .indexed = 1, \
0634     .channel = (_index), \
0635     .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
0636                   BIT(IIO_CHAN_INFO_SCALE), \
0637     .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
0638                    BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
0639     .scan_index = (_index), \
0640     .scan_type = { \
0641         .sign = 'u', \
0642         .realbits = 16, \
0643         .storagebits = 16, \
0644         .endianness = IIO_CPU, \
0645     } \
0646 }
0647 
0648 /*
0649  * Sampling Freq is a consequence of the integration times of
0650  * the Voltage channels.
0651  */
0652 #define INA219_CHAN_VOLTAGE(_index, _address, _shift) { \
0653     .type = IIO_VOLTAGE, \
0654     .address = (_address), \
0655     .indexed = 1, \
0656     .channel = (_index), \
0657     .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
0658                   BIT(IIO_CHAN_INFO_SCALE) | \
0659                   BIT(IIO_CHAN_INFO_INT_TIME) | \
0660                   BIT(IIO_CHAN_INFO_HARDWAREGAIN), \
0661     .info_mask_separate_available = \
0662                   BIT(IIO_CHAN_INFO_HARDWAREGAIN), \
0663     .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ), \
0664     .scan_index = (_index), \
0665     .scan_type = { \
0666         .sign = 'u', \
0667         .shift = _shift, \
0668         .realbits = 16 - _shift, \
0669         .storagebits = 16, \
0670         .endianness = IIO_LE, \
0671     } \
0672 }
0673 
0674 #define INA226_CHAN_VOLTAGE(_index, _address) { \
0675     .type = IIO_VOLTAGE, \
0676     .address = (_address), \
0677     .indexed = 1, \
0678     .channel = (_index), \
0679     .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
0680                   BIT(IIO_CHAN_INFO_SCALE) | \
0681                   BIT(IIO_CHAN_INFO_INT_TIME), \
0682     .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
0683                    BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
0684     .scan_index = (_index), \
0685     .scan_type = { \
0686         .sign = 'u', \
0687         .realbits = 16, \
0688         .storagebits = 16, \
0689         .endianness = IIO_LE, \
0690     } \
0691 }
0692 
0693 
0694 static const struct iio_chan_spec ina226_channels[] = {
0695     INA226_CHAN_VOLTAGE(0, INA2XX_SHUNT_VOLTAGE),
0696     INA226_CHAN_VOLTAGE(1, INA2XX_BUS_VOLTAGE),
0697     INA226_CHAN(IIO_POWER, 2, INA2XX_POWER),
0698     INA226_CHAN(IIO_CURRENT, 3, INA2XX_CURRENT),
0699     IIO_CHAN_SOFT_TIMESTAMP(4),
0700 };
0701 
0702 static const struct iio_chan_spec ina219_channels[] = {
0703     INA219_CHAN_VOLTAGE(0, INA2XX_SHUNT_VOLTAGE, 0),
0704     INA219_CHAN_VOLTAGE(1, INA2XX_BUS_VOLTAGE, INA219_BUS_VOLTAGE_SHIFT),
0705     INA219_CHAN(IIO_POWER, 2, INA2XX_POWER),
0706     INA219_CHAN(IIO_CURRENT, 3, INA2XX_CURRENT),
0707     IIO_CHAN_SOFT_TIMESTAMP(4),
0708 };
0709 
0710 static int ina2xx_conversion_ready(struct iio_dev *indio_dev)
0711 {
0712     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0713     int ret;
0714     unsigned int alert;
0715 
0716     /*
0717      * Because the timer thread and the chip conversion clock
0718      * are asynchronous, the period difference will eventually
0719      * result in reading V[k-1] again, or skip V[k] at time Tk.
0720      * In order to resync the timer with the conversion process
0721      * we check the ConVersionReadyFlag.
0722      * On hardware that supports using the ALERT pin to toggle a
0723      * GPIO a triggered buffer could be used instead.
0724      * For now, we do an extra read of the MASK_ENABLE register (INA226)
0725      * resp. the BUS_VOLTAGE register (INA219).
0726      */
0727     if (chip->config->chip_id == ina226) {
0728         ret = regmap_read(chip->regmap,
0729                   INA226_MASK_ENABLE, &alert);
0730         alert &= INA226_CVRF;
0731     } else {
0732         ret = regmap_read(chip->regmap,
0733                   INA2XX_BUS_VOLTAGE, &alert);
0734         alert &= INA219_CNVR;
0735     }
0736 
0737     if (ret < 0)
0738         return ret;
0739 
0740     return !!alert;
0741 }
0742 
0743 static int ina2xx_work_buffer(struct iio_dev *indio_dev)
0744 {
0745     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0746     int bit, ret, i = 0;
0747     s64 time;
0748 
0749     time = iio_get_time_ns(indio_dev);
0750 
0751     /*
0752      * Single register reads: bulk_read will not work with ina226/219
0753      * as there is no auto-increment of the register pointer.
0754      */
0755     for_each_set_bit(bit, indio_dev->active_scan_mask,
0756              indio_dev->masklength) {
0757         unsigned int val;
0758 
0759         ret = regmap_read(chip->regmap,
0760                   INA2XX_SHUNT_VOLTAGE + bit, &val);
0761         if (ret < 0)
0762             return ret;
0763 
0764         chip->scan.chan[i++] = val;
0765     }
0766 
0767     iio_push_to_buffers_with_timestamp(indio_dev, &chip->scan, time);
0768 
0769     return 0;
0770 };
0771 
0772 static int ina2xx_capture_thread(void *data)
0773 {
0774     struct iio_dev *indio_dev = data;
0775     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0776     int sampling_us = SAMPLING_PERIOD(chip);
0777     int ret;
0778     struct timespec64 next, now, delta;
0779     s64 delay_us;
0780 
0781     /*
0782      * Poll a bit faster than the chip internal Fs, in case
0783      * we wish to sync with the conversion ready flag.
0784      */
0785     if (!chip->allow_async_readout)
0786         sampling_us -= 200;
0787 
0788     ktime_get_ts64(&next);
0789 
0790     do {
0791         while (!chip->allow_async_readout) {
0792             ret = ina2xx_conversion_ready(indio_dev);
0793             if (ret < 0)
0794                 return ret;
0795 
0796             /*
0797              * If the conversion was not yet finished,
0798              * reset the reference timestamp.
0799              */
0800             if (ret == 0)
0801                 ktime_get_ts64(&next);
0802             else
0803                 break;
0804         }
0805 
0806         ret = ina2xx_work_buffer(indio_dev);
0807         if (ret < 0)
0808             return ret;
0809 
0810         ktime_get_ts64(&now);
0811 
0812         /*
0813          * Advance the timestamp for the next poll by one sampling
0814          * interval, and sleep for the remainder (next - now)
0815          * In case "next" has already passed, the interval is added
0816          * multiple times, i.e. samples are dropped.
0817          */
0818         do {
0819             timespec64_add_ns(&next, 1000 * sampling_us);
0820             delta = timespec64_sub(next, now);
0821             delay_us = div_s64(timespec64_to_ns(&delta), 1000);
0822         } while (delay_us <= 0);
0823 
0824         usleep_range(delay_us, (delay_us * 3) >> 1);
0825 
0826     } while (!kthread_should_stop());
0827 
0828     return 0;
0829 }
0830 
0831 static int ina2xx_buffer_enable(struct iio_dev *indio_dev)
0832 {
0833     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0834     unsigned int sampling_us = SAMPLING_PERIOD(chip);
0835     struct task_struct *task;
0836 
0837     dev_dbg(&indio_dev->dev, "Enabling buffer w/ scan_mask %02x, freq = %d, avg =%u\n",
0838         (unsigned int)(*indio_dev->active_scan_mask),
0839         1000000 / sampling_us, chip->avg);
0840 
0841     dev_dbg(&indio_dev->dev, "Expected work period: %u us\n", sampling_us);
0842     dev_dbg(&indio_dev->dev, "Async readout mode: %d\n",
0843         chip->allow_async_readout);
0844 
0845     task = kthread_run(ina2xx_capture_thread, (void *)indio_dev,
0846                "%s:%d-%uus", indio_dev->name,
0847                iio_device_id(indio_dev),
0848                sampling_us);
0849     if (IS_ERR(task))
0850         return PTR_ERR(task);
0851 
0852     chip->task = task;
0853 
0854     return 0;
0855 }
0856 
0857 static int ina2xx_buffer_disable(struct iio_dev *indio_dev)
0858 {
0859     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0860 
0861     if (chip->task) {
0862         kthread_stop(chip->task);
0863         chip->task = NULL;
0864     }
0865 
0866     return 0;
0867 }
0868 
0869 static const struct iio_buffer_setup_ops ina2xx_setup_ops = {
0870     .postenable = &ina2xx_buffer_enable,
0871     .predisable = &ina2xx_buffer_disable,
0872 };
0873 
0874 static int ina2xx_debug_reg(struct iio_dev *indio_dev,
0875                 unsigned reg, unsigned writeval, unsigned *readval)
0876 {
0877     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
0878 
0879     if (!readval)
0880         return regmap_write(chip->regmap, reg, writeval);
0881 
0882     return regmap_read(chip->regmap, reg, readval);
0883 }
0884 
0885 /* Possible integration times for vshunt and vbus */
0886 static IIO_CONST_ATTR_NAMED(ina219_integration_time_available,
0887                 integration_time_available,
0888                 "0.000084 0.000148 0.000276 0.000532 0.001060 0.002130 0.004260 0.008510 0.017020 0.034050 0.068100");
0889 
0890 static IIO_CONST_ATTR_NAMED(ina226_integration_time_available,
0891                 integration_time_available,
0892                 "0.000140 0.000204 0.000332 0.000588 0.001100 0.002116 0.004156 0.008244");
0893 
0894 static IIO_DEVICE_ATTR(in_allow_async_readout, S_IRUGO | S_IWUSR,
0895                ina2xx_allow_async_readout_show,
0896                ina2xx_allow_async_readout_store, 0);
0897 
0898 static IIO_DEVICE_ATTR(in_shunt_resistor, S_IRUGO | S_IWUSR,
0899                ina2xx_shunt_resistor_show,
0900                ina2xx_shunt_resistor_store, 0);
0901 
0902 static struct attribute *ina219_attributes[] = {
0903     &iio_dev_attr_in_allow_async_readout.dev_attr.attr,
0904     &iio_const_attr_ina219_integration_time_available.dev_attr.attr,
0905     &iio_dev_attr_in_shunt_resistor.dev_attr.attr,
0906     NULL,
0907 };
0908 
0909 static struct attribute *ina226_attributes[] = {
0910     &iio_dev_attr_in_allow_async_readout.dev_attr.attr,
0911     &iio_const_attr_ina226_integration_time_available.dev_attr.attr,
0912     &iio_dev_attr_in_shunt_resistor.dev_attr.attr,
0913     NULL,
0914 };
0915 
0916 static const struct attribute_group ina219_attribute_group = {
0917     .attrs = ina219_attributes,
0918 };
0919 
0920 static const struct attribute_group ina226_attribute_group = {
0921     .attrs = ina226_attributes,
0922 };
0923 
0924 static const struct iio_info ina219_info = {
0925     .attrs = &ina219_attribute_group,
0926     .read_raw = ina2xx_read_raw,
0927     .read_avail = ina2xx_read_avail,
0928     .write_raw = ina2xx_write_raw,
0929     .debugfs_reg_access = ina2xx_debug_reg,
0930 };
0931 
0932 static const struct iio_info ina226_info = {
0933     .attrs = &ina226_attribute_group,
0934     .read_raw = ina2xx_read_raw,
0935     .write_raw = ina2xx_write_raw,
0936     .debugfs_reg_access = ina2xx_debug_reg,
0937 };
0938 
0939 /* Initialize the configuration and calibration registers. */
0940 static int ina2xx_init(struct ina2xx_chip_info *chip, unsigned int config)
0941 {
0942     int ret = regmap_write(chip->regmap, INA2XX_CONFIG, config);
0943     if (ret)
0944         return ret;
0945 
0946     return ina2xx_set_calibration(chip);
0947 }
0948 
0949 static int ina2xx_probe(struct i2c_client *client,
0950             const struct i2c_device_id *id)
0951 {
0952     struct ina2xx_chip_info *chip;
0953     struct iio_dev *indio_dev;
0954     unsigned int val;
0955     enum ina2xx_ids type;
0956     int ret;
0957 
0958     indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*chip));
0959     if (!indio_dev)
0960         return -ENOMEM;
0961 
0962     chip = iio_priv(indio_dev);
0963 
0964     /* This is only used for device removal purposes. */
0965     i2c_set_clientdata(client, indio_dev);
0966 
0967     chip->regmap = devm_regmap_init_i2c(client, &ina2xx_regmap_config);
0968     if (IS_ERR(chip->regmap)) {
0969         dev_err(&client->dev, "failed to allocate register map\n");
0970         return PTR_ERR(chip->regmap);
0971     }
0972 
0973     if (client->dev.of_node)
0974         type = (uintptr_t)of_device_get_match_data(&client->dev);
0975     else
0976         type = id->driver_data;
0977     chip->config = &ina2xx_config[type];
0978 
0979     mutex_init(&chip->state_lock);
0980 
0981     if (of_property_read_u32(client->dev.of_node,
0982                  "shunt-resistor", &val) < 0) {
0983         struct ina2xx_platform_data *pdata =
0984             dev_get_platdata(&client->dev);
0985 
0986         if (pdata)
0987             val = pdata->shunt_uohms;
0988         else
0989             val = INA2XX_RSHUNT_DEFAULT;
0990     }
0991 
0992     ret = set_shunt_resistor(chip, val);
0993     if (ret)
0994         return ret;
0995 
0996     /* Patch the current config register with default. */
0997     val = chip->config->config_default;
0998 
0999     if (id->driver_data == ina226) {
1000         ina226_set_average(chip, INA226_DEFAULT_AVG, &val);
1001         ina226_set_int_time_vbus(chip, INA226_DEFAULT_IT, &val);
1002         ina226_set_int_time_vshunt(chip, INA226_DEFAULT_IT, &val);
1003     } else {
1004         chip->avg = 1;
1005         ina219_set_int_time_vbus(chip, INA219_DEFAULT_IT, &val);
1006         ina219_set_int_time_vshunt(chip, INA219_DEFAULT_IT, &val);
1007         ina219_set_vbus_range_denom(chip, INA219_DEFAULT_BRNG, &val);
1008         ina219_set_vshunt_pga_gain(chip, INA219_DEFAULT_PGA, &val);
1009     }
1010 
1011     ret = ina2xx_init(chip, val);
1012     if (ret) {
1013         dev_err(&client->dev, "error configuring the device\n");
1014         return ret;
1015     }
1016 
1017     indio_dev->modes = INDIO_DIRECT_MODE;
1018     if (id->driver_data == ina226) {
1019         indio_dev->channels = ina226_channels;
1020         indio_dev->num_channels = ARRAY_SIZE(ina226_channels);
1021         indio_dev->info = &ina226_info;
1022     } else {
1023         indio_dev->channels = ina219_channels;
1024         indio_dev->num_channels = ARRAY_SIZE(ina219_channels);
1025         indio_dev->info = &ina219_info;
1026     }
1027     indio_dev->name = id->name;
1028 
1029     ret = devm_iio_kfifo_buffer_setup(&client->dev, indio_dev,
1030                       &ina2xx_setup_ops);
1031     if (ret)
1032         return ret;
1033 
1034     return iio_device_register(indio_dev);
1035 }
1036 
1037 static int ina2xx_remove(struct i2c_client *client)
1038 {
1039     struct iio_dev *indio_dev = i2c_get_clientdata(client);
1040     struct ina2xx_chip_info *chip = iio_priv(indio_dev);
1041     int ret;
1042 
1043     iio_device_unregister(indio_dev);
1044 
1045     /* Powerdown */
1046     ret = regmap_update_bits(chip->regmap, INA2XX_CONFIG,
1047                  INA2XX_MODE_MASK, 0);
1048     if (ret)
1049         dev_warn(&client->dev, "Failed to power down device (%pe)\n",
1050              ERR_PTR(ret));
1051 
1052     return 0;
1053 }
1054 
1055 static const struct i2c_device_id ina2xx_id[] = {
1056     {"ina219", ina219},
1057     {"ina220", ina219},
1058     {"ina226", ina226},
1059     {"ina230", ina226},
1060     {"ina231", ina226},
1061     {}
1062 };
1063 MODULE_DEVICE_TABLE(i2c, ina2xx_id);
1064 
1065 static const struct of_device_id ina2xx_of_match[] = {
1066     {
1067         .compatible = "ti,ina219",
1068         .data = (void *)ina219
1069     },
1070     {
1071         .compatible = "ti,ina220",
1072         .data = (void *)ina219
1073     },
1074     {
1075         .compatible = "ti,ina226",
1076         .data = (void *)ina226
1077     },
1078     {
1079         .compatible = "ti,ina230",
1080         .data = (void *)ina226
1081     },
1082     {
1083         .compatible = "ti,ina231",
1084         .data = (void *)ina226
1085     },
1086     {},
1087 };
1088 MODULE_DEVICE_TABLE(of, ina2xx_of_match);
1089 
1090 static struct i2c_driver ina2xx_driver = {
1091     .driver = {
1092            .name = KBUILD_MODNAME,
1093            .of_match_table = ina2xx_of_match,
1094     },
1095     .probe = ina2xx_probe,
1096     .remove = ina2xx_remove,
1097     .id_table = ina2xx_id,
1098 };
1099 module_i2c_driver(ina2xx_driver);
1100 
1101 MODULE_AUTHOR("Marc Titinger <marc.titinger@baylibre.com>");
1102 MODULE_DESCRIPTION("Texas Instruments INA2XX ADC driver");
1103 MODULE_LICENSE("GPL v2");