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