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
101static bool ina2xx_is_writeable_reg(struct device *dev, unsigned int reg)
102{
103	return (reg == INA2XX_CONFIG) || (reg > INA2XX_CURRENT);
104}
105
106static bool ina2xx_is_volatile_reg(struct device *dev, unsigned int reg)
107{
108	return (reg != INA2XX_CONFIG);
109}
110
111static inline bool is_signed_reg(unsigned int reg)
112{
113	return (reg == INA2XX_SHUNT_VOLTAGE) || (reg == INA2XX_CURRENT);
114}
115
116static 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
124enum ina2xx_ids { ina219, ina226 };
125
126struct 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
137struct 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
156static 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
177static 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		return -EINVAL;
259
260	case IIO_CHAN_INFO_HARDWAREGAIN:
261		switch (chan->address) {
262		case INA2XX_SHUNT_VOLTAGE:
263			*val = chip->pga_gain_vshunt;
264			*val2 = 1000;
265			return IIO_VAL_FRACTIONAL;
266
267		case INA2XX_BUS_VOLTAGE:
268			*val = chip->range_vbus == 32 ? 1 : 2;
269			return IIO_VAL_INT;
270		}
271		return -EINVAL;
272	}
273
274	return -EINVAL;
275}
276
277/*
278 * Available averaging rates for ina226. The indices correspond with
279 * the bit values expected by the chip (according to the ina226 datasheet,
280 * table 3 AVG bit settings, found at
281 * https://www.ti.com/lit/ds/symlink/ina226.pdf.
282 */
283static const int ina226_avg_tab[] = { 1, 4, 16, 64, 128, 256, 512, 1024 };
284
285static int ina226_set_average(struct ina2xx_chip_info *chip, unsigned int val,
286			      unsigned int *config)
287{
288	int bits;
289
290	if (val > 1024 || val < 1)
291		return -EINVAL;
292
293	bits = find_closest(val, ina226_avg_tab,
294			    ARRAY_SIZE(ina226_avg_tab));
295
296	chip->avg = ina226_avg_tab[bits];
297
298	*config &= ~INA226_AVG_MASK;
299	*config |= INA226_SHIFT_AVG(bits) & INA226_AVG_MASK;
300
301	return 0;
302}
303
304/* Conversion times in uS */
305static const int ina226_conv_time_tab[] = { 140, 204, 332, 588, 1100,
306					    2116, 4156, 8244 };
307
308static int ina226_set_int_time_vbus(struct ina2xx_chip_info *chip,
309				    unsigned int val_us, unsigned int *config)
310{
311	int bits;
312
313	if (val_us > 8244 || val_us < 140)
314		return -EINVAL;
315
316	bits = find_closest(val_us, ina226_conv_time_tab,
317			    ARRAY_SIZE(ina226_conv_time_tab));
318
319	chip->int_time_vbus = ina226_conv_time_tab[bits];
320
321	*config &= ~INA226_ITB_MASK;
322	*config |= INA226_SHIFT_ITB(bits) & INA226_ITB_MASK;
323
324	return 0;
325}
326
327static int ina226_set_int_time_vshunt(struct ina2xx_chip_info *chip,
328				      unsigned int val_us, unsigned int *config)
329{
330	int bits;
331
332	if (val_us > 8244 || val_us < 140)
333		return -EINVAL;
334
335	bits = find_closest(val_us, ina226_conv_time_tab,
336			    ARRAY_SIZE(ina226_conv_time_tab));
337
338	chip->int_time_vshunt = ina226_conv_time_tab[bits];
339
340	*config &= ~INA226_ITS_MASK;
341	*config |= INA226_SHIFT_ITS(bits) & INA226_ITS_MASK;
342
343	return 0;
344}
345
346/* Conversion times in uS. */
347static const int ina219_conv_time_tab_subsample[] = { 84, 148, 276, 532 };
348static const int ina219_conv_time_tab_average[] = { 532, 1060, 2130, 4260,
349						    8510, 17020, 34050, 68100};
350
351static int ina219_lookup_int_time(unsigned int *val_us, int *bits)
352{
353	if (*val_us > 68100 || *val_us < 84)
354		return -EINVAL;
355
356	if (*val_us <= 532) {
357		*bits = find_closest(*val_us, ina219_conv_time_tab_subsample,
358				    ARRAY_SIZE(ina219_conv_time_tab_subsample));
359		*val_us = ina219_conv_time_tab_subsample[*bits];
360	} else {
361		*bits = find_closest(*val_us, ina219_conv_time_tab_average,
362				    ARRAY_SIZE(ina219_conv_time_tab_average));
363		*val_us = ina219_conv_time_tab_average[*bits];
364		*bits |= 0x8;
365	}
366
367	return 0;
368}
369
370static int ina219_set_int_time_vbus(struct ina2xx_chip_info *chip,
371				    unsigned int val_us, unsigned int *config)
372{
373	int bits, ret;
374	unsigned int val_us_best = val_us;
375
376	ret = ina219_lookup_int_time(&val_us_best, &bits);
377	if (ret)
378		return ret;
379
380	chip->int_time_vbus = val_us_best;
381
382	*config &= ~INA219_ITB_MASK;
383	*config |= INA219_SHIFT_ITB(bits) & INA219_ITB_MASK;
384
385	return 0;
386}
387
388static int ina219_set_int_time_vshunt(struct ina2xx_chip_info *chip,
389				      unsigned int val_us, unsigned int *config)
390{
391	int bits, ret;
392	unsigned int val_us_best = val_us;
393
394	ret = ina219_lookup_int_time(&val_us_best, &bits);
395	if (ret)
396		return ret;
397
398	chip->int_time_vshunt = val_us_best;
399
400	*config &= ~INA219_ITS_MASK;
401	*config |= INA219_SHIFT_ITS(bits) & INA219_ITS_MASK;
402
403	return 0;
404}
405
406static const int ina219_vbus_range_tab[] = { 1, 2 };
407static int ina219_set_vbus_range_denom(struct ina2xx_chip_info *chip,
408				       unsigned int range,
409				       unsigned int *config)
410{
411	if (range == 1)
412		chip->range_vbus = 32;
413	else if (range == 2)
414		chip->range_vbus = 16;
415	else
416		return -EINVAL;
417
418	*config &= ~INA219_BRNG_MASK;
419	*config |= INA219_SHIFT_BRNG(range == 1 ? 1 : 0) & INA219_BRNG_MASK;
420
421	return 0;
422}
423
424static const int ina219_vshunt_gain_tab[] = { 125, 250, 500, 1000 };
425static const int ina219_vshunt_gain_frac[] = {
426	125, 1000, 250, 1000, 500, 1000, 1000, 1000 };
427
428static int ina219_set_vshunt_pga_gain(struct ina2xx_chip_info *chip,
429				      unsigned int gain,
430				      unsigned int *config)
431{
432	int bits;
433
434	if (gain < 125 || gain > 1000)
435		return -EINVAL;
436
437	bits = find_closest(gain, ina219_vshunt_gain_tab,
438			    ARRAY_SIZE(ina219_vshunt_gain_tab));
439
440	chip->pga_gain_vshunt = ina219_vshunt_gain_tab[bits];
441	bits = 3 - bits;
442
443	*config &= ~INA219_PGA_MASK;
444	*config |= INA219_SHIFT_PGA(bits) & INA219_PGA_MASK;
445
446	return 0;
447}
448
449static int ina2xx_read_avail(struct iio_dev *indio_dev,
450			     struct iio_chan_spec const *chan,
451			     const int **vals, int *type, int *length,
452			     long mask)
453{
454	switch (mask) {
455	case IIO_CHAN_INFO_HARDWAREGAIN:
456		switch (chan->address) {
457		case INA2XX_SHUNT_VOLTAGE:
458			*type = IIO_VAL_FRACTIONAL;
459			*length = sizeof(ina219_vshunt_gain_frac) / sizeof(int);
460			*vals = ina219_vshunt_gain_frac;
461			return IIO_AVAIL_LIST;
462
463		case INA2XX_BUS_VOLTAGE:
464			*type = IIO_VAL_INT;
465			*length = sizeof(ina219_vbus_range_tab) / sizeof(int);
466			*vals = ina219_vbus_range_tab;
467			return IIO_AVAIL_LIST;
468		}
469	}
470
471	return -EINVAL;
472}
473
474static int ina2xx_write_raw(struct iio_dev *indio_dev,
475			    struct iio_chan_spec const *chan,
476			    int val, int val2, long mask)
477{
478	struct ina2xx_chip_info *chip = iio_priv(indio_dev);
479	unsigned int config, tmp;
480	int ret;
481
482	if (iio_buffer_enabled(indio_dev))
483		return -EBUSY;
484
485	mutex_lock(&chip->state_lock);
486
487	ret = regmap_read(chip->regmap, INA2XX_CONFIG, &config);
488	if (ret)
489		goto err;
490
491	tmp = config;
492
493	switch (mask) {
494	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
495		ret = ina226_set_average(chip, val, &tmp);
496		break;
497
498	case IIO_CHAN_INFO_INT_TIME:
499		if (chip->config->chip_id == ina226) {
500			if (chan->address == INA2XX_SHUNT_VOLTAGE)
501				ret = ina226_set_int_time_vshunt(chip, val2,
502								 &tmp);
503			else
504				ret = ina226_set_int_time_vbus(chip, val2,
505							       &tmp);
506		} else {
507			if (chan->address == INA2XX_SHUNT_VOLTAGE)
508				ret = ina219_set_int_time_vshunt(chip, val2,
509								 &tmp);
510			else
511				ret = ina219_set_int_time_vbus(chip, val2,
512							       &tmp);
513		}
514		break;
515
516	case IIO_CHAN_INFO_HARDWAREGAIN:
517		if (chan->address == INA2XX_SHUNT_VOLTAGE)
518			ret = ina219_set_vshunt_pga_gain(chip, val * 1000 +
519							 val2 / 1000, &tmp);
520		else
521			ret = ina219_set_vbus_range_denom(chip, val, &tmp);
522		break;
523
524	default:
525		ret = -EINVAL;
526	}
527
528	if (!ret && (tmp != config))
529		ret = regmap_write(chip->regmap, INA2XX_CONFIG, tmp);
530err:
531	mutex_unlock(&chip->state_lock);
532
533	return ret;
534}
535
536static ssize_t ina2xx_allow_async_readout_show(struct device *dev,
537					   struct device_attribute *attr,
538					   char *buf)
539{
540	struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
541
542	return sprintf(buf, "%d\n", chip->allow_async_readout);
543}
544
545static ssize_t ina2xx_allow_async_readout_store(struct device *dev,
546				struct device_attribute *attr,
547				const char *buf, size_t len)
548{
549	struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
550	bool val;
551	int ret;
552
553	ret = strtobool((const char *) buf, &val);
554	if (ret)
555		return ret;
556
557	chip->allow_async_readout = val;
558
559	return len;
560}
561
562/*
563 * Calibration register is set to the best value, which eliminates
564 * truncation errors on calculating current register in hardware.
565 * According to datasheet (INA 226: eq. 3, INA219: eq. 4) the best values
566 * are 2048 for ina226 and 4096 for ina219. They are hardcoded as
567 * calibration_value.
568 */
569static int ina2xx_set_calibration(struct ina2xx_chip_info *chip)
570{
571	return regmap_write(chip->regmap, INA2XX_CALIBRATION,
572			    chip->config->calibration_value);
573}
574
575static int set_shunt_resistor(struct ina2xx_chip_info *chip, unsigned int val)
576{
577	if (val == 0 || val > INT_MAX)
578		return -EINVAL;
579
580	chip->shunt_resistor_uohm = val;
581
582	return 0;
583}
584
585static ssize_t ina2xx_shunt_resistor_show(struct device *dev,
586					  struct device_attribute *attr,
587					  char *buf)
588{
589	struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
590	int vals[2] = { chip->shunt_resistor_uohm, 1000000 };
591
592	return iio_format_value(buf, IIO_VAL_FRACTIONAL, 1, vals);
593}
594
595static ssize_t ina2xx_shunt_resistor_store(struct device *dev,
596					   struct device_attribute *attr,
597					   const char *buf, size_t len)
598{
599	struct ina2xx_chip_info *chip = iio_priv(dev_to_iio_dev(dev));
600	int val, val_fract, ret;
601
602	ret = iio_str_to_fixpoint(buf, 100000, &val, &val_fract);
603	if (ret)
604		return ret;
605
606	ret = set_shunt_resistor(chip, val * 1000000 + val_fract);
607	if (ret)
608		return ret;
609
610	return len;
611}
612
613#define INA219_CHAN(_type, _index, _address) { \
614	.type = (_type), \
615	.address = (_address), \
616	.indexed = 1, \
617	.channel = (_index), \
618	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
619			      BIT(IIO_CHAN_INFO_SCALE), \
620	.info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ), \
621	.scan_index = (_index), \
622	.scan_type = { \
623		.sign = 'u', \
624		.realbits = 16, \
625		.storagebits = 16, \
626		.endianness = IIO_CPU, \
627	} \
628}
629
630#define INA226_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				   BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
639	.scan_index = (_index), \
640	.scan_type = { \
641		.sign = 'u', \
642		.realbits = 16, \
643		.storagebits = 16, \
644		.endianness = IIO_CPU, \
645	} \
646}
647
648/*
649 * Sampling Freq is a consequence of the integration times of
650 * the Voltage channels.
651 */
652#define INA219_CHAN_VOLTAGE(_index, _address, _shift) { \
653	.type = IIO_VOLTAGE, \
654	.address = (_address), \
655	.indexed = 1, \
656	.channel = (_index), \
657	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
658			      BIT(IIO_CHAN_INFO_SCALE) | \
659			      BIT(IIO_CHAN_INFO_INT_TIME) | \
660			      BIT(IIO_CHAN_INFO_HARDWAREGAIN), \
661	.info_mask_separate_available = \
662			      BIT(IIO_CHAN_INFO_HARDWAREGAIN), \
663	.info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ), \
664	.scan_index = (_index), \
665	.scan_type = { \
666		.sign = 'u', \
667		.shift = _shift, \
668		.realbits = 16 - _shift, \
669		.storagebits = 16, \
670		.endianness = IIO_LE, \
671	} \
672}
673
674#define INA226_CHAN_VOLTAGE(_index, _address) { \
675	.type = IIO_VOLTAGE, \
676	.address = (_address), \
677	.indexed = 1, \
678	.channel = (_index), \
679	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
680			      BIT(IIO_CHAN_INFO_SCALE) | \
681			      BIT(IIO_CHAN_INFO_INT_TIME), \
682	.info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
683				   BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
684	.scan_index = (_index), \
685	.scan_type = { \
686		.sign = 'u', \
687		.realbits = 16, \
688		.storagebits = 16, \
689		.endianness = IIO_LE, \
690	} \
691}
692
693
694static const struct iio_chan_spec ina226_channels[] = {
695	INA226_CHAN_VOLTAGE(0, INA2XX_SHUNT_VOLTAGE),
696	INA226_CHAN_VOLTAGE(1, INA2XX_BUS_VOLTAGE),
697	INA226_CHAN(IIO_POWER, 2, INA2XX_POWER),
698	INA226_CHAN(IIO_CURRENT, 3, INA2XX_CURRENT),
699	IIO_CHAN_SOFT_TIMESTAMP(4),
700};
701
702static const struct iio_chan_spec ina219_channels[] = {
703	INA219_CHAN_VOLTAGE(0, INA2XX_SHUNT_VOLTAGE, 0),
704	INA219_CHAN_VOLTAGE(1, INA2XX_BUS_VOLTAGE, INA219_BUS_VOLTAGE_SHIFT),
705	INA219_CHAN(IIO_POWER, 2, INA2XX_POWER),
706	INA219_CHAN(IIO_CURRENT, 3, INA2XX_CURRENT),
707	IIO_CHAN_SOFT_TIMESTAMP(4),
708};
709
710static int ina2xx_conversion_ready(struct iio_dev *indio_dev)
711{
712	struct ina2xx_chip_info *chip = iio_priv(indio_dev);
713	int ret;
714	unsigned int alert;
715
716	/*
717	 * Because the timer thread and the chip conversion clock
718	 * are asynchronous, the period difference will eventually
719	 * result in reading V[k-1] again, or skip V[k] at time Tk.
720	 * In order to resync the timer with the conversion process
721	 * we check the ConVersionReadyFlag.
722	 * On hardware that supports using the ALERT pin to toggle a
723	 * GPIO a triggered buffer could be used instead.
724	 * For now, we do an extra read of the MASK_ENABLE register (INA226)
725	 * resp. the BUS_VOLTAGE register (INA219).
726	 */
727	if (chip->config->chip_id == ina226) {
728		ret = regmap_read(chip->regmap,
729				  INA226_MASK_ENABLE, &alert);
730		alert &= INA226_CVRF;
731	} else {
732		ret = regmap_read(chip->regmap,
733				  INA2XX_BUS_VOLTAGE, &alert);
734		alert &= INA219_CNVR;
735	}
736
737	if (ret < 0)
738		return ret;
739
740	return !!alert;
741}
742
743static int ina2xx_work_buffer(struct iio_dev *indio_dev)
744{
745	struct ina2xx_chip_info *chip = iio_priv(indio_dev);
746	int bit, ret, i = 0;
747	s64 time;
748
749	time = iio_get_time_ns(indio_dev);
750
751	/*
752	 * Single register reads: bulk_read will not work with ina226/219
753	 * as there is no auto-increment of the register pointer.
754	 */
755	for_each_set_bit(bit, indio_dev->active_scan_mask,
756			 indio_dev->masklength) {
757		unsigned int val;
758
759		ret = regmap_read(chip->regmap,
760				  INA2XX_SHUNT_VOLTAGE + bit, &val);
761		if (ret < 0)
762			return ret;
763
764		chip->scan.chan[i++] = val;
765	}
766
767	iio_push_to_buffers_with_timestamp(indio_dev, &chip->scan, time);
768
769	return 0;
770};
771
772static int ina2xx_capture_thread(void *data)
773{
774	struct iio_dev *indio_dev = data;
775	struct ina2xx_chip_info *chip = iio_priv(indio_dev);
776	int sampling_us = SAMPLING_PERIOD(chip);
777	int ret;
778	struct timespec64 next, now, delta;
779	s64 delay_us;
780
781	/*
782	 * Poll a bit faster than the chip internal Fs, in case
783	 * we wish to sync with the conversion ready flag.
784	 */
785	if (!chip->allow_async_readout)
786		sampling_us -= 200;
787
788	ktime_get_ts64(&next);
789
790	do {
791		while (!chip->allow_async_readout) {
792			ret = ina2xx_conversion_ready(indio_dev);
793			if (ret < 0)
794				return ret;
795
796			/*
797			 * If the conversion was not yet finished,
798			 * reset the reference timestamp.
799			 */
800			if (ret == 0)
801				ktime_get_ts64(&next);
802			else
803				break;
804		}
805
806		ret = ina2xx_work_buffer(indio_dev);
807		if (ret < 0)
808			return ret;
809
810		ktime_get_ts64(&now);
811
812		/*
813		 * Advance the timestamp for the next poll by one sampling
814		 * interval, and sleep for the remainder (next - now)
815		 * In case "next" has already passed, the interval is added
816		 * multiple times, i.e. samples are dropped.
817		 */
818		do {
819			timespec64_add_ns(&next, 1000 * sampling_us);
820			delta = timespec64_sub(next, now);
821			delay_us = div_s64(timespec64_to_ns(&delta), 1000);
822		} while (delay_us <= 0);
823
824		usleep_range(delay_us, (delay_us * 3) >> 1);
825
826	} while (!kthread_should_stop());
827
828	return 0;
829}
830
831static int ina2xx_buffer_enable(struct iio_dev *indio_dev)
832{
833	struct ina2xx_chip_info *chip = iio_priv(indio_dev);
834	unsigned int sampling_us = SAMPLING_PERIOD(chip);
835	struct task_struct *task;
836
837	dev_dbg(&indio_dev->dev, "Enabling buffer w/ scan_mask %02x, freq = %d, avg =%u\n",
838		(unsigned int)(*indio_dev->active_scan_mask),
839		1000000 / sampling_us, chip->avg);
840
841	dev_dbg(&indio_dev->dev, "Expected work period: %u us\n", sampling_us);
842	dev_dbg(&indio_dev->dev, "Async readout mode: %d\n",
843		chip->allow_async_readout);
844
845	task = kthread_create(ina2xx_capture_thread, (void *)indio_dev,
846			      "%s:%d-%uus", indio_dev->name, indio_dev->id,
847			      sampling_us);
848	if (IS_ERR(task))
849		return PTR_ERR(task);
850
851	get_task_struct(task);
852	wake_up_process(task);
853	chip->task = task;
854
855	return 0;
856}
857
858static int ina2xx_buffer_disable(struct iio_dev *indio_dev)
859{
860	struct ina2xx_chip_info *chip = iio_priv(indio_dev);
861
862	if (chip->task) {
863		kthread_stop(chip->task);
864		put_task_struct(chip->task);
865		chip->task = NULL;
866	}
867
868	return 0;
869}
870
871static const struct iio_buffer_setup_ops ina2xx_setup_ops = {
872	.postenable = &ina2xx_buffer_enable,
873	.predisable = &ina2xx_buffer_disable,
874};
875
876static int ina2xx_debug_reg(struct iio_dev *indio_dev,
877			    unsigned reg, unsigned writeval, unsigned *readval)
878{
879	struct ina2xx_chip_info *chip = iio_priv(indio_dev);
880
881	if (!readval)
882		return regmap_write(chip->regmap, reg, writeval);
883
884	return regmap_read(chip->regmap, reg, readval);
885}
886
887/* Possible integration times for vshunt and vbus */
888static IIO_CONST_ATTR_NAMED(ina219_integration_time_available,
889			    integration_time_available,
890			    "0.000084 0.000148 0.000276 0.000532 0.001060 0.002130 0.004260 0.008510 0.017020 0.034050 0.068100");
891
892static IIO_CONST_ATTR_NAMED(ina226_integration_time_available,
893			    integration_time_available,
894			    "0.000140 0.000204 0.000332 0.000588 0.001100 0.002116 0.004156 0.008244");
895
896static IIO_DEVICE_ATTR(in_allow_async_readout, S_IRUGO | S_IWUSR,
897		       ina2xx_allow_async_readout_show,
898		       ina2xx_allow_async_readout_store, 0);
899
900static IIO_DEVICE_ATTR(in_shunt_resistor, S_IRUGO | S_IWUSR,
901		       ina2xx_shunt_resistor_show,
902		       ina2xx_shunt_resistor_store, 0);
903
904static struct attribute *ina219_attributes[] = {
905	&iio_dev_attr_in_allow_async_readout.dev_attr.attr,
906	&iio_const_attr_ina219_integration_time_available.dev_attr.attr,
907	&iio_dev_attr_in_shunt_resistor.dev_attr.attr,
908	NULL,
909};
910
911static struct attribute *ina226_attributes[] = {
912	&iio_dev_attr_in_allow_async_readout.dev_attr.attr,
913	&iio_const_attr_ina226_integration_time_available.dev_attr.attr,
914	&iio_dev_attr_in_shunt_resistor.dev_attr.attr,
915	NULL,
916};
917
918static const struct attribute_group ina219_attribute_group = {
919	.attrs = ina219_attributes,
920};
921
922static const struct attribute_group ina226_attribute_group = {
923	.attrs = ina226_attributes,
924};
925
926static const struct iio_info ina219_info = {
927	.attrs = &ina219_attribute_group,
928	.read_raw = ina2xx_read_raw,
929	.read_avail = ina2xx_read_avail,
930	.write_raw = ina2xx_write_raw,
931	.debugfs_reg_access = ina2xx_debug_reg,
932};
933
934static const struct iio_info ina226_info = {
935	.attrs = &ina226_attribute_group,
936	.read_raw = ina2xx_read_raw,
937	.write_raw = ina2xx_write_raw,
938	.debugfs_reg_access = ina2xx_debug_reg,
939};
940
941/* Initialize the configuration and calibration registers. */
942static int ina2xx_init(struct ina2xx_chip_info *chip, unsigned int config)
943{
944	int ret = regmap_write(chip->regmap, INA2XX_CONFIG, config);
945	if (ret)
946		return ret;
947
948	return ina2xx_set_calibration(chip);
949}
950
951static int ina2xx_probe(struct i2c_client *client,
952			const struct i2c_device_id *id)
953{
954	struct ina2xx_chip_info *chip;
955	struct iio_dev *indio_dev;
956	struct iio_buffer *buffer;
957	unsigned int val;
958	enum ina2xx_ids type;
959	int ret;
960
961	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*chip));
962	if (!indio_dev)
963		return -ENOMEM;
964
965	chip = iio_priv(indio_dev);
966
967	/* This is only used for device removal purposes. */
968	i2c_set_clientdata(client, indio_dev);
969
970	chip->regmap = devm_regmap_init_i2c(client, &ina2xx_regmap_config);
971	if (IS_ERR(chip->regmap)) {
972		dev_err(&client->dev, "failed to allocate register map\n");
973		return PTR_ERR(chip->regmap);
974	}
975
976	if (client->dev.of_node)
977		type = (enum ina2xx_ids)of_device_get_match_data(&client->dev);
978	else
979		type = id->driver_data;
980	chip->config = &ina2xx_config[type];
981
982	mutex_init(&chip->state_lock);
983
984	if (of_property_read_u32(client->dev.of_node,
985				 "shunt-resistor", &val) < 0) {
986		struct ina2xx_platform_data *pdata =
987		    dev_get_platdata(&client->dev);
988
989		if (pdata)
990			val = pdata->shunt_uohms;
991		else
992			val = INA2XX_RSHUNT_DEFAULT;
993	}
994
995	ret = set_shunt_resistor(chip, val);
996	if (ret)
997		return ret;
998
999	/* Patch the current config register with default. */
1000	val = chip->config->config_default;
1001
1002	if (id->driver_data == ina226) {
1003		ina226_set_average(chip, INA226_DEFAULT_AVG, &val);
1004		ina226_set_int_time_vbus(chip, INA226_DEFAULT_IT, &val);
1005		ina226_set_int_time_vshunt(chip, INA226_DEFAULT_IT, &val);
1006	} else {
1007		chip->avg = 1;
1008		ina219_set_int_time_vbus(chip, INA219_DEFAULT_IT, &val);
1009		ina219_set_int_time_vshunt(chip, INA219_DEFAULT_IT, &val);
1010		ina219_set_vbus_range_denom(chip, INA219_DEFAULT_BRNG, &val);
1011		ina219_set_vshunt_pga_gain(chip, INA219_DEFAULT_PGA, &val);
1012	}
1013
1014	ret = ina2xx_init(chip, val);
1015	if (ret) {
1016		dev_err(&client->dev, "error configuring the device\n");
1017		return ret;
1018	}
1019
1020	indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
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
1042static 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
1054static const struct i2c_device_id ina2xx_id[] = {
1055	{"ina219", ina219},
1056	{"ina220", ina219},
1057	{"ina226", ina226},
1058	{"ina230", ina226},
1059	{"ina231", ina226},
1060	{}
1061};
1062MODULE_DEVICE_TABLE(i2c, ina2xx_id);
1063
1064static 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};
1087MODULE_DEVICE_TABLE(of, ina2xx_of_match);
1088
1089static 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};
1098module_i2c_driver(ina2xx_driver);
1099
1100MODULE_AUTHOR("Marc Titinger <marc.titinger@baylibre.com>");
1101MODULE_DESCRIPTION("Texas Instruments INA2XX ADC driver");
1102MODULE_LICENSE("GPL v2");
1103