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