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