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