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