xref: /linux/drivers/hwmon/ina2xx.c (revision 53597deca0e38c30e6cd4ba2114fa42d2bcd85bb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Driver for Texas Instruments INA219, INA226 and register-layout compatible
4  * current/power monitor chips with I2C Interface
5  *
6  * Copyright (C) 2012 Lothar Felten <lothar.felten@gmail.com>
7  * Thanks to Jan Volkering
8  */
9 
10 #include <linux/bitfield.h>
11 #include <linux/bits.h>
12 #include <linux/delay.h>
13 #include <linux/device.h>
14 #include <linux/err.h>
15 #include <linux/hwmon.h>
16 #include <linux/i2c.h>
17 #include <linux/init.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
20 #include <linux/property.h>
21 #include <linux/regmap.h>
22 #include <linux/slab.h>
23 #include <linux/sysfs.h>
24 #include <linux/util_macros.h>
25 
26 /* common register definitions */
27 #define INA2XX_CONFIG			0x00
28 #define INA2XX_SHUNT_VOLTAGE		0x01 /* readonly */
29 #define INA2XX_BUS_VOLTAGE		0x02 /* readonly */
30 #define INA2XX_POWER			0x03 /* readonly */
31 #define INA2XX_CURRENT			0x04 /* readonly */
32 #define INA2XX_CALIBRATION		0x05
33 
34 /* INA226 register definitions */
35 #define INA226_MASK_ENABLE		0x06
36 #define INA226_ALERT_LIMIT		0x07
37 
38 /* SY24655 register definitions */
39 #define SY24655_EIN				0x0A
40 #define SY24655_ACCUM_CONFIG	0x0D
41 #define INA2XX_MAX_REGISTERS		0x0D
42 
43 /* settings - depend on use case */
44 #define INA219_CONFIG_DEFAULT		0x399F	/* PGA=8 */
45 #define INA226_CONFIG_DEFAULT		0x4527	/* averages=16 */
46 #define INA260_CONFIG_DEFAULT		0x6527	/* averages=16 */
47 #define SY24655_CONFIG_DEFAULT		0x4527	/* averages=16 */
48 
49 /* (only for sy24655) */
50 #define SY24655_ACCUM_CONFIG_DEFAULT	0x044C	/* continuous mode, clear after read*/
51 
52 /* worst case is 68.10 ms (~14.6Hz, ina219) */
53 #define INA2XX_CONVERSION_RATE		15
54 #define INA2XX_MAX_DELAY		69 /* worst case delay in ms */
55 
56 #define INA2XX_RSHUNT_DEFAULT		10000
57 #define INA260_RSHUNT			2000
58 
59 /* bit mask for reading the averaging setting in the configuration register */
60 #define INA226_AVG_RD_MASK		GENMASK(11, 9)
61 
62 #define INA226_READ_AVG(reg)		FIELD_GET(INA226_AVG_RD_MASK, reg)
63 
64 #define INA226_ALERT_LATCH_ENABLE	BIT(0)
65 #define INA226_ALERT_POLARITY		BIT(1)
66 
67 /* bit number of alert functions in Mask/Enable Register */
68 #define INA226_SHUNT_OVER_VOLTAGE_MASK	BIT(15)
69 #define INA226_SHUNT_UNDER_VOLTAGE_MASK	BIT(14)
70 #define INA226_BUS_OVER_VOLTAGE_MASK	BIT(13)
71 #define INA226_BUS_UNDER_VOLTAGE_MASK	BIT(12)
72 #define INA226_POWER_OVER_LIMIT_MASK	BIT(11)
73 
74 /* bit mask for alert config bits of Mask/Enable Register */
75 #define INA226_ALERT_CONFIG_MASK	GENMASK(15, 10)
76 #define INA226_ALERT_FUNCTION_FLAG	BIT(4)
77 
78 /*
79  * Both bus voltage and shunt voltage conversion times for ina226 are set
80  * to 0b0100 on POR, which translates to 2200 microseconds in total.
81  */
82 #define INA226_TOTAL_CONV_TIME_DEFAULT	2200
83 
84 static bool ina2xx_writeable_reg(struct device *dev, unsigned int reg)
85 {
86 	switch (reg) {
87 	case INA2XX_CONFIG:
88 	case INA2XX_CALIBRATION:
89 	case INA226_MASK_ENABLE:
90 	case INA226_ALERT_LIMIT:
91 	case SY24655_ACCUM_CONFIG:
92 		return true;
93 	default:
94 		return false;
95 	}
96 }
97 
98 static bool ina2xx_volatile_reg(struct device *dev, unsigned int reg)
99 {
100 	switch (reg) {
101 	case INA2XX_SHUNT_VOLTAGE:
102 	case INA2XX_BUS_VOLTAGE:
103 	case INA2XX_POWER:
104 	case INA2XX_CURRENT:
105 		return true;
106 	default:
107 		return false;
108 	}
109 }
110 
111 static const struct regmap_config ina2xx_regmap_config = {
112 	.reg_bits = 8,
113 	.val_bits = 16,
114 	.use_single_write = true,
115 	.use_single_read = true,
116 	.max_register = INA2XX_MAX_REGISTERS,
117 	.cache_type = REGCACHE_MAPLE,
118 	.volatile_reg = ina2xx_volatile_reg,
119 	.writeable_reg = ina2xx_writeable_reg,
120 };
121 
122 enum ina2xx_ids {
123 	ina219,
124 	ina226,
125 	ina234,
126 	ina260,
127 	sy24655
128 };
129 
130 struct ina2xx_config {
131 	u16 config_default;
132 	bool has_alerts;	/* chip supports alerts and limits */
133 	bool has_ishunt;	/* chip has internal shunt resistor */
134 	bool has_power_average;	/* chip supports average power */
135 	bool has_update_interval;
136 	int calibration_value;
137 	int shunt_div;
138 	int shunt_voltage_shift;
139 	int bus_voltage_shift;
140 	int bus_voltage_lsb;	/* uV */
141 	int power_lsb_factor;
142 	int current_shift;
143 };
144 
145 struct ina2xx_data {
146 	const struct ina2xx_config *config;
147 	enum ina2xx_ids chip;
148 
149 	long rshunt;
150 	long current_lsb_uA;
151 	long power_lsb_uW;
152 	struct regmap *regmap;
153 	struct i2c_client *client;
154 };
155 
156 static const struct ina2xx_config ina2xx_config[] = {
157 	[ina219] = {
158 		.config_default = INA219_CONFIG_DEFAULT,
159 		.calibration_value = 4096,
160 		.shunt_div = 100,
161 		.shunt_voltage_shift = 0,
162 		.bus_voltage_shift = 3,
163 		.bus_voltage_lsb = 4000,
164 		.power_lsb_factor = 20,
165 		.has_alerts = false,
166 		.has_ishunt = false,
167 		.has_power_average = false,
168 		.current_shift = 0,
169 		.has_update_interval = false,
170 	},
171 	[ina226] = {
172 		.config_default = INA226_CONFIG_DEFAULT,
173 		.calibration_value = 2048,
174 		.shunt_div = 400,
175 		.shunt_voltage_shift = 0,
176 		.bus_voltage_shift = 0,
177 		.bus_voltage_lsb = 1250,
178 		.power_lsb_factor = 25,
179 		.has_alerts = true,
180 		.has_ishunt = false,
181 		.has_power_average = false,
182 		.current_shift = 0,
183 		.has_update_interval = true,
184 	},
185 	[ina234] = {
186 		.config_default = INA226_CONFIG_DEFAULT,
187 		.calibration_value = 2048,
188 		.shunt_div = 25, /* 2.5 µV/LSB raw ADC reading from INA2XX_SHUNT_VOLTAGE */
189 		.shunt_voltage_shift = 4,
190 		.bus_voltage_shift = 4,
191 		.bus_voltage_lsb = 25600,
192 		.power_lsb_factor = 32,
193 		.has_alerts = true,
194 		.has_ishunt = false,
195 		.has_power_average = false,
196 		.current_shift = 4,
197 		.has_update_interval = true,
198 	},
199 	[ina260] = {
200 		.config_default = INA260_CONFIG_DEFAULT,
201 		.shunt_div = 400,
202 		.shunt_voltage_shift = 0,
203 		.bus_voltage_shift = 0,
204 		.bus_voltage_lsb = 1250,
205 		.power_lsb_factor = 8,
206 		.has_alerts = true,
207 		.has_ishunt = true,
208 		.has_power_average = false,
209 		.current_shift = 0,
210 		.has_update_interval = true,
211 	},
212 	[sy24655] = {
213 		.config_default = SY24655_CONFIG_DEFAULT,
214 		.calibration_value = 4096,
215 		.shunt_div = 400,
216 		.shunt_voltage_shift = 0,
217 		.bus_voltage_shift = 0,
218 		.bus_voltage_lsb = 1250,
219 		.power_lsb_factor = 25,
220 		.has_alerts = true,
221 		.has_ishunt = false,
222 		.has_power_average = true,
223 		.current_shift = 0,
224 		.has_update_interval = false,
225 	},
226 };
227 
228 /*
229  * Available averaging rates for ina226. The indices correspond with
230  * the bit values expected by the chip (according to the ina226 datasheet,
231  * table 3 AVG bit settings, found at
232  * https://www.ti.com/lit/ds/symlink/ina226.pdf.
233  */
234 static const int ina226_avg_tab[] = { 1, 4, 16, 64, 128, 256, 512, 1024 };
235 
236 static int ina226_reg_to_interval(u16 config)
237 {
238 	int avg = ina226_avg_tab[INA226_READ_AVG(config)];
239 
240 	/*
241 	 * Multiply the total conversion time by the number of averages.
242 	 * Return the result in milliseconds.
243 	 */
244 	return DIV_ROUND_CLOSEST(avg * INA226_TOTAL_CONV_TIME_DEFAULT, 1000);
245 }
246 
247 /*
248  * Return the new, shifted AVG field value of CONFIG register,
249  * to use with regmap_update_bits
250  */
251 static u16 ina226_interval_to_reg(long interval)
252 {
253 	int avg, avg_bits;
254 
255 	/*
256 	 * The maximum supported interval is 1,024 * (2 * 8.244ms) ~= 16.8s.
257 	 * Clamp to 32 seconds before calculations to avoid overflows.
258 	 */
259 	interval = clamp_val(interval, 0, 32000);
260 
261 	avg = DIV_ROUND_CLOSEST(interval * 1000,
262 				INA226_TOTAL_CONV_TIME_DEFAULT);
263 	avg_bits = find_closest(avg, ina226_avg_tab,
264 				ARRAY_SIZE(ina226_avg_tab));
265 
266 	return FIELD_PREP(INA226_AVG_RD_MASK, avg_bits);
267 }
268 
269 static int ina2xx_get_value(struct ina2xx_data *data, u8 reg,
270 			    unsigned int regval)
271 {
272 	int val;
273 
274 	switch (reg) {
275 	case INA2XX_SHUNT_VOLTAGE:
276 		/* signed register */
277 		val = (s16)regval >> data->config->shunt_voltage_shift;
278 		val = DIV_ROUND_CLOSEST(val, data->config->shunt_div);
279 		break;
280 	case INA2XX_BUS_VOLTAGE:
281 		val = (regval >> data->config->bus_voltage_shift) *
282 		  data->config->bus_voltage_lsb;
283 		val = DIV_ROUND_CLOSEST(val, 1000);
284 		break;
285 	case INA2XX_POWER:
286 		val = regval * data->power_lsb_uW;
287 		break;
288 	case INA2XX_CURRENT:
289 		/* signed register, result in mA */
290 		val = ((s16)regval >> data->config->current_shift) *
291 		  data->current_lsb_uA;
292 		val = DIV_ROUND_CLOSEST(val, 1000);
293 		break;
294 	case INA2XX_CALIBRATION:
295 		val = regval;
296 		break;
297 	default:
298 		/* programmer goofed */
299 		WARN_ON_ONCE(1);
300 		val = 0;
301 		break;
302 	}
303 
304 	return val;
305 }
306 
307 /*
308  * Read and convert register value from chip. If the register value is 0,
309  * check if the chip has been power cycled or reset. If so, re-initialize it.
310  */
311 static int ina2xx_read_init(struct device *dev, int reg, long *val)
312 {
313 	struct ina2xx_data *data = dev_get_drvdata(dev);
314 	struct regmap *regmap = data->regmap;
315 	unsigned int regval;
316 	int ret, retry;
317 
318 	if (data->config->has_ishunt) {
319 		/* No calibration needed */
320 		ret = regmap_read(regmap, reg, &regval);
321 		if (ret < 0)
322 			return ret;
323 		*val = ina2xx_get_value(data, reg, regval);
324 		return 0;
325 	}
326 
327 	for (retry = 5; retry; retry--) {
328 		ret = regmap_read(regmap, reg, &regval);
329 		if (ret < 0)
330 			return ret;
331 
332 		/*
333 		 * If the current value in the calibration register is 0, the
334 		 * power and current registers will also remain at 0. In case
335 		 * the chip has been reset let's check the calibration
336 		 * register and reinitialize if needed.
337 		 * We do that extra read of the calibration register if there
338 		 * is some hint of a chip reset.
339 		 */
340 		if (regval == 0) {
341 			unsigned int cal;
342 
343 			ret = regmap_read_bypassed(regmap, INA2XX_CALIBRATION, &cal);
344 			if (ret < 0)
345 				return ret;
346 
347 			if (cal == 0) {
348 				dev_warn(dev, "chip not calibrated, reinitializing\n");
349 
350 				regcache_mark_dirty(regmap);
351 				regcache_sync(regmap);
352 
353 				/*
354 				 * Let's make sure the power and current
355 				 * registers have been updated before trying
356 				 * again.
357 				 */
358 				msleep(INA2XX_MAX_DELAY);
359 				continue;
360 			}
361 		}
362 		*val = ina2xx_get_value(data, reg, regval);
363 		return 0;
364 	}
365 
366 	/*
367 	 * If we're here then although all write operations succeeded, the
368 	 * chip still returns 0 in the calibration register. Nothing more we
369 	 * can do here.
370 	 */
371 	dev_err(dev, "unable to reinitialize the chip\n");
372 	return -ENODEV;
373 }
374 
375 /*
376  * Turns alert limit values into register values.
377  * Opposite of the formula in ina2xx_get_value().
378  */
379 static u16 ina226_alert_to_reg(struct ina2xx_data *data, int reg, long val)
380 {
381 	switch (reg) {
382 	case INA2XX_SHUNT_VOLTAGE:
383 		val = clamp_val(val, 0, SHRT_MAX * data->config->shunt_div);
384 		val *= data->config->shunt_div;
385 		val <<= data->config->shunt_voltage_shift;
386 		return clamp_val(val, 0, SHRT_MAX);
387 	case INA2XX_BUS_VOLTAGE:
388 		val = clamp_val(val, 0, 200000);
389 		val = (val * 1000) << data->config->bus_voltage_shift;
390 		val = DIV_ROUND_CLOSEST(val, data->config->bus_voltage_lsb);
391 		return clamp_val(val, 0, USHRT_MAX);
392 	case INA2XX_POWER:
393 		val = clamp_val(val, 0, UINT_MAX - data->power_lsb_uW);
394 		val = DIV_ROUND_CLOSEST(val, data->power_lsb_uW);
395 		return clamp_val(val, 0, USHRT_MAX);
396 	case INA2XX_CURRENT:
397 		val = clamp_val(val, INT_MIN / 1000, INT_MAX / 1000);
398 		/* signed register, result in mA */
399 		val = DIV_ROUND_CLOSEST(val * 1000, data->current_lsb_uA);
400 		val <<= data->config->current_shift;
401 		return clamp_val(val, SHRT_MIN, SHRT_MAX);
402 	default:
403 		/* programmer goofed */
404 		WARN_ON_ONCE(1);
405 		return 0;
406 	}
407 }
408 
409 static int ina226_alert_limit_read(struct ina2xx_data *data, u32 mask, int reg, long *val)
410 {
411 	struct regmap *regmap = data->regmap;
412 	int regval;
413 	int ret;
414 
415 	ret = regmap_read(regmap, INA226_MASK_ENABLE, &regval);
416 	if (ret)
417 		return ret;
418 
419 	if (regval & mask) {
420 		ret = regmap_read(regmap, INA226_ALERT_LIMIT, &regval);
421 		if (ret)
422 			return ret;
423 		*val = ina2xx_get_value(data, reg, regval);
424 	} else {
425 		*val = 0;
426 	}
427 	return 0;
428 }
429 
430 static int ina226_alert_limit_write(struct ina2xx_data *data, u32 mask, int reg, long val)
431 {
432 	struct regmap *regmap = data->regmap;
433 	int ret;
434 
435 	if (val < 0)
436 		return -EINVAL;
437 
438 	/*
439 	 * Clear all alerts first to avoid accidentally triggering ALERT pin
440 	 * due to register write sequence. Then, only enable the alert
441 	 * if the value is non-zero.
442 	 */
443 	ret = regmap_update_bits(regmap, INA226_MASK_ENABLE,
444 				 INA226_ALERT_CONFIG_MASK, 0);
445 	if (ret < 0)
446 		return ret;
447 
448 	ret = regmap_write(regmap, INA226_ALERT_LIMIT,
449 			   ina226_alert_to_reg(data, reg, val));
450 	if (ret < 0)
451 		return ret;
452 
453 	if (val)
454 		return regmap_update_bits(regmap, INA226_MASK_ENABLE,
455 					  INA226_ALERT_CONFIG_MASK, mask);
456 	return 0;
457 }
458 
459 static int ina2xx_chip_read(struct device *dev, u32 attr, long *val)
460 {
461 	struct ina2xx_data *data = dev_get_drvdata(dev);
462 	u32 regval;
463 	int ret;
464 
465 	switch (attr) {
466 	case hwmon_chip_update_interval:
467 		ret = regmap_read(data->regmap, INA2XX_CONFIG, &regval);
468 		if (ret)
469 			return ret;
470 
471 		*val = ina226_reg_to_interval(regval);
472 		break;
473 	default:
474 		return -EOPNOTSUPP;
475 	}
476 	return 0;
477 }
478 
479 static int ina226_alert_read(struct regmap *regmap, u32 mask, long *val)
480 {
481 	unsigned int regval;
482 	int ret;
483 
484 	ret = regmap_read_bypassed(regmap, INA226_MASK_ENABLE, &regval);
485 	if (ret)
486 		return ret;
487 
488 	*val = (regval & mask) && (regval & INA226_ALERT_FUNCTION_FLAG);
489 
490 	return 0;
491 }
492 
493 static int ina2xx_in_read(struct device *dev, u32 attr, int channel, long *val)
494 {
495 	int voltage_reg = channel ? INA2XX_BUS_VOLTAGE : INA2XX_SHUNT_VOLTAGE;
496 	u32 under_voltage_mask = channel ? INA226_BUS_UNDER_VOLTAGE_MASK
497 					 : INA226_SHUNT_UNDER_VOLTAGE_MASK;
498 	u32 over_voltage_mask = channel ? INA226_BUS_OVER_VOLTAGE_MASK
499 					: INA226_SHUNT_OVER_VOLTAGE_MASK;
500 	struct ina2xx_data *data = dev_get_drvdata(dev);
501 	struct regmap *regmap = data->regmap;
502 	unsigned int regval;
503 	int ret;
504 
505 	switch (attr) {
506 	case hwmon_in_input:
507 		ret = regmap_read(regmap, voltage_reg, &regval);
508 		if (ret)
509 			return ret;
510 		*val = ina2xx_get_value(data, voltage_reg, regval);
511 		break;
512 	case hwmon_in_lcrit:
513 		return ina226_alert_limit_read(data, under_voltage_mask,
514 					       voltage_reg, val);
515 	case hwmon_in_crit:
516 		return ina226_alert_limit_read(data, over_voltage_mask,
517 					       voltage_reg, val);
518 	case hwmon_in_lcrit_alarm:
519 		return ina226_alert_read(regmap, under_voltage_mask, val);
520 	case hwmon_in_crit_alarm:
521 		return ina226_alert_read(regmap, over_voltage_mask, val);
522 	default:
523 		return -EOPNOTSUPP;
524 	}
525 	return 0;
526 }
527 
528 /*
529  * Configuring the READ_EIN (bit 10) of the ACCUM_CONFIG register to 1
530  * can clear accumulator and sample_count after reading the EIN register.
531  * This way, the average power between the last read and the current
532  * read can be obtained. By combining with accurate time data from
533  * outside, the energy consumption during that period can be calculated.
534  */
535 static int sy24655_average_power_read(struct ina2xx_data *data, u8 reg, long *val)
536 {
537 	u8 template[6];
538 	int ret;
539 	long accumulator_24, sample_count;
540 
541 	/* 48-bit register read */
542 	ret = i2c_smbus_read_i2c_block_data(data->client, reg, 6, template);
543 	if (ret < 0)
544 		return ret;
545 	if (ret != 6)
546 		return -EIO;
547 	accumulator_24 = ((template[3] << 16) |
548 				(template[4] << 8) |
549 				template[5]);
550 	sample_count = ((template[0] << 16) |
551 				(template[1] << 8) |
552 				template[2]);
553 	if (sample_count <= 0) {
554 		*val = 0;
555 		return 0;
556 	}
557 
558 	*val = DIV_ROUND_CLOSEST(accumulator_24, sample_count) * data->power_lsb_uW;
559 
560 	return 0;
561 }
562 
563 static int ina2xx_power_read(struct device *dev, u32 attr, long *val)
564 {
565 	struct ina2xx_data *data = dev_get_drvdata(dev);
566 
567 	switch (attr) {
568 	case hwmon_power_input:
569 		return ina2xx_read_init(dev, INA2XX_POWER, val);
570 	case hwmon_power_average:
571 		return sy24655_average_power_read(data, SY24655_EIN, val);
572 	case hwmon_power_crit:
573 		return ina226_alert_limit_read(data, INA226_POWER_OVER_LIMIT_MASK,
574 					       INA2XX_POWER, val);
575 	case hwmon_power_crit_alarm:
576 		return ina226_alert_read(data->regmap, INA226_POWER_OVER_LIMIT_MASK, val);
577 	default:
578 		return -EOPNOTSUPP;
579 	}
580 }
581 
582 static int ina2xx_curr_read(struct device *dev, u32 attr, long *val)
583 {
584 	struct ina2xx_data *data = dev_get_drvdata(dev);
585 	struct regmap *regmap = data->regmap;
586 	unsigned int regval;
587 	int ret;
588 
589 	/*
590 	 * While the chips supported by this driver do not directly support
591 	 * current limits, they do support setting shunt voltage limits.
592 	 * The shunt voltage divided by the shunt resistor value is the current.
593 	 * On top of that, calibration values are set such that in the shunt
594 	 * voltage register and the current register report the same values.
595 	 * That means we can report and configure current limits based on shunt
596 	 * voltage limits.
597 	 */
598 	switch (attr) {
599 	case hwmon_curr_input:
600 		/*
601 		 * Since the shunt voltage and the current register report the
602 		 * same values when the chip is calibrated, we can calculate
603 		 * the current directly from the shunt voltage without relying
604 		 * on chip calibration.
605 		 */
606 		ret = regmap_read(regmap, INA2XX_SHUNT_VOLTAGE, &regval);
607 		if (ret)
608 			return ret;
609 		*val = ina2xx_get_value(data, INA2XX_CURRENT, regval);
610 		return 0;
611 	case hwmon_curr_lcrit:
612 		return ina226_alert_limit_read(data, INA226_SHUNT_UNDER_VOLTAGE_MASK,
613 					       INA2XX_CURRENT, val);
614 	case hwmon_curr_crit:
615 		return ina226_alert_limit_read(data, INA226_SHUNT_OVER_VOLTAGE_MASK,
616 					       INA2XX_CURRENT, val);
617 	case hwmon_curr_lcrit_alarm:
618 		return ina226_alert_read(regmap, INA226_SHUNT_UNDER_VOLTAGE_MASK, val);
619 	case hwmon_curr_crit_alarm:
620 		return ina226_alert_read(regmap, INA226_SHUNT_OVER_VOLTAGE_MASK, val);
621 	default:
622 		return -EOPNOTSUPP;
623 	}
624 }
625 
626 static int ina2xx_read(struct device *dev, enum hwmon_sensor_types type,
627 		       u32 attr, int channel, long *val)
628 {
629 	switch (type) {
630 	case hwmon_chip:
631 		return ina2xx_chip_read(dev, attr, val);
632 	case hwmon_in:
633 		return ina2xx_in_read(dev, attr, channel, val);
634 	case hwmon_power:
635 		return ina2xx_power_read(dev, attr, val);
636 	case hwmon_curr:
637 		return ina2xx_curr_read(dev, attr, val);
638 	default:
639 		return -EOPNOTSUPP;
640 	}
641 }
642 
643 static int ina2xx_chip_write(struct device *dev, u32 attr, long val)
644 {
645 	struct ina2xx_data *data = dev_get_drvdata(dev);
646 
647 	switch (attr) {
648 	case hwmon_chip_update_interval:
649 		return regmap_update_bits(data->regmap, INA2XX_CONFIG,
650 					  INA226_AVG_RD_MASK,
651 					  ina226_interval_to_reg(val));
652 	default:
653 		return -EOPNOTSUPP;
654 	}
655 }
656 
657 static int ina2xx_in_write(struct device *dev, u32 attr, int channel, long val)
658 {
659 	struct ina2xx_data *data = dev_get_drvdata(dev);
660 
661 	switch (attr) {
662 	case hwmon_in_lcrit:
663 		return ina226_alert_limit_write(data,
664 			channel ? INA226_BUS_UNDER_VOLTAGE_MASK : INA226_SHUNT_UNDER_VOLTAGE_MASK,
665 			channel ? INA2XX_BUS_VOLTAGE : INA2XX_SHUNT_VOLTAGE,
666 			val);
667 	case hwmon_in_crit:
668 		return ina226_alert_limit_write(data,
669 			channel ? INA226_BUS_OVER_VOLTAGE_MASK : INA226_SHUNT_OVER_VOLTAGE_MASK,
670 			channel ? INA2XX_BUS_VOLTAGE : INA2XX_SHUNT_VOLTAGE,
671 			val);
672 	default:
673 		return -EOPNOTSUPP;
674 	}
675 	return 0;
676 }
677 
678 static int ina2xx_power_write(struct device *dev, u32 attr, long val)
679 {
680 	struct ina2xx_data *data = dev_get_drvdata(dev);
681 
682 	switch (attr) {
683 	case hwmon_power_crit:
684 		return ina226_alert_limit_write(data, INA226_POWER_OVER_LIMIT_MASK,
685 						INA2XX_POWER, val);
686 	default:
687 		return -EOPNOTSUPP;
688 	}
689 	return 0;
690 }
691 
692 static int ina2xx_curr_write(struct device *dev, u32 attr, long val)
693 {
694 	struct ina2xx_data *data = dev_get_drvdata(dev);
695 
696 	switch (attr) {
697 	case hwmon_curr_lcrit:
698 		return ina226_alert_limit_write(data, INA226_SHUNT_UNDER_VOLTAGE_MASK,
699 						INA2XX_CURRENT, val);
700 	case hwmon_curr_crit:
701 		return ina226_alert_limit_write(data, INA226_SHUNT_OVER_VOLTAGE_MASK,
702 						INA2XX_CURRENT, val);
703 	default:
704 		return -EOPNOTSUPP;
705 	}
706 	return 0;
707 }
708 
709 static int ina2xx_write(struct device *dev, enum hwmon_sensor_types type,
710 			u32 attr, int channel, long val)
711 {
712 	switch (type) {
713 	case hwmon_chip:
714 		return ina2xx_chip_write(dev, attr, val);
715 	case hwmon_in:
716 		return ina2xx_in_write(dev, attr, channel, val);
717 	case hwmon_power:
718 		return ina2xx_power_write(dev, attr, val);
719 	case hwmon_curr:
720 		return ina2xx_curr_write(dev, attr, val);
721 	default:
722 		return -EOPNOTSUPP;
723 	}
724 }
725 
726 static umode_t ina2xx_is_visible(const void *_data, enum hwmon_sensor_types type,
727 				 u32 attr, int channel)
728 {
729 	const struct ina2xx_data *data = _data;
730 	bool has_alerts = data->config->has_alerts;
731 	bool has_power_average = data->config->has_power_average;
732 	bool has_update_interval = data->config->has_update_interval;
733 
734 	switch (type) {
735 	case hwmon_in:
736 		switch (attr) {
737 		case hwmon_in_input:
738 			return 0444;
739 		case hwmon_in_lcrit:
740 		case hwmon_in_crit:
741 			if (has_alerts)
742 				return 0644;
743 			break;
744 		case hwmon_in_lcrit_alarm:
745 		case hwmon_in_crit_alarm:
746 			if (has_alerts)
747 				return 0444;
748 			break;
749 		default:
750 			break;
751 		}
752 		break;
753 	case hwmon_curr:
754 		switch (attr) {
755 		case hwmon_curr_input:
756 			return 0444;
757 		case hwmon_curr_lcrit:
758 		case hwmon_curr_crit:
759 			if (has_alerts)
760 				return 0644;
761 			break;
762 		case hwmon_curr_lcrit_alarm:
763 		case hwmon_curr_crit_alarm:
764 			if (has_alerts)
765 				return 0444;
766 			break;
767 		default:
768 			break;
769 		}
770 		break;
771 	case hwmon_power:
772 		switch (attr) {
773 		case hwmon_power_input:
774 			return 0444;
775 		case hwmon_power_crit:
776 			if (has_alerts)
777 				return 0644;
778 			break;
779 		case hwmon_power_crit_alarm:
780 			if (has_alerts)
781 				return 0444;
782 			break;
783 		case hwmon_power_average:
784 			if (has_power_average)
785 				return 0444;
786 			break;
787 		default:
788 			break;
789 		}
790 		break;
791 	case hwmon_chip:
792 		switch (attr) {
793 		case hwmon_chip_update_interval:
794 			if (has_update_interval)
795 				return 0644;
796 			break;
797 		default:
798 			break;
799 		}
800 		break;
801 	default:
802 		break;
803 	}
804 	return 0;
805 }
806 
807 static const struct hwmon_channel_info * const ina2xx_info[] = {
808 	HWMON_CHANNEL_INFO(chip,
809 			   HWMON_C_UPDATE_INTERVAL),
810 	HWMON_CHANNEL_INFO(in,
811 			   HWMON_I_INPUT | HWMON_I_CRIT | HWMON_I_CRIT_ALARM |
812 			   HWMON_I_LCRIT | HWMON_I_LCRIT_ALARM,
813 			   HWMON_I_INPUT | HWMON_I_CRIT | HWMON_I_CRIT_ALARM |
814 			   HWMON_I_LCRIT | HWMON_I_LCRIT_ALARM
815 			   ),
816 	HWMON_CHANNEL_INFO(curr, HWMON_C_INPUT | HWMON_C_CRIT | HWMON_C_CRIT_ALARM |
817 			   HWMON_C_LCRIT | HWMON_C_LCRIT_ALARM),
818 	HWMON_CHANNEL_INFO(power,
819 			   HWMON_P_INPUT | HWMON_P_CRIT | HWMON_P_CRIT_ALARM |
820 			   HWMON_P_AVERAGE),
821 	NULL
822 };
823 
824 static const struct hwmon_ops ina2xx_hwmon_ops = {
825 	.is_visible = ina2xx_is_visible,
826 	.read = ina2xx_read,
827 	.write = ina2xx_write,
828 };
829 
830 static const struct hwmon_chip_info ina2xx_chip_info = {
831 	.ops = &ina2xx_hwmon_ops,
832 	.info = ina2xx_info,
833 };
834 
835 /* shunt resistance */
836 
837 /*
838  * In order to keep calibration register value fixed, the product
839  * of current_lsb and shunt_resistor should also be fixed and equal
840  * to shunt_voltage_lsb = 1 / shunt_div multiplied by 10^9 in order
841  * to keep the scale.
842  */
843 static int ina2xx_set_shunt(struct ina2xx_data *data, unsigned long val)
844 {
845 	unsigned int dividend = DIV_ROUND_CLOSEST(1000000000,
846 						  data->config->shunt_div);
847 	if (!val || val > dividend)
848 		return -EINVAL;
849 
850 	data->rshunt = val;
851 	data->current_lsb_uA = DIV_ROUND_CLOSEST(dividend, val);
852 	data->power_lsb_uW = data->config->power_lsb_factor *
853 			     data->current_lsb_uA;
854 
855 	return 0;
856 }
857 
858 static ssize_t shunt_resistor_show(struct device *dev,
859 				   struct device_attribute *da, char *buf)
860 {
861 	struct ina2xx_data *data = dev_get_drvdata(dev);
862 
863 	return sysfs_emit(buf, "%li\n", data->rshunt);
864 }
865 
866 static ssize_t shunt_resistor_store(struct device *dev,
867 				    struct device_attribute *da,
868 				    const char *buf, size_t count)
869 {
870 	struct ina2xx_data *data = dev_get_drvdata(dev);
871 	unsigned long val;
872 	int status;
873 
874 	status = kstrtoul(buf, 10, &val);
875 	if (status < 0)
876 		return status;
877 
878 	hwmon_lock(dev);
879 	status = ina2xx_set_shunt(data, val);
880 	hwmon_unlock(dev);
881 	if (status < 0)
882 		return status;
883 	return count;
884 }
885 
886 static DEVICE_ATTR_RW(shunt_resistor);
887 
888 /* pointers to created device attributes */
889 static struct attribute *ina2xx_attrs[] = {
890 	&dev_attr_shunt_resistor.attr,
891 	NULL,
892 };
893 ATTRIBUTE_GROUPS(ina2xx);
894 
895 /*
896  * Initialize chip
897  */
898 static int ina2xx_init(struct device *dev, struct ina2xx_data *data)
899 {
900 	struct regmap *regmap = data->regmap;
901 	u32 shunt;
902 	int ret;
903 
904 	if (data->config->has_ishunt)
905 		shunt = INA260_RSHUNT;
906 	else if (device_property_read_u32(dev, "shunt-resistor", &shunt) < 0)
907 		shunt = INA2XX_RSHUNT_DEFAULT;
908 
909 	ret = ina2xx_set_shunt(data, shunt);
910 	if (ret < 0)
911 		return ret;
912 
913 	ret = regmap_write(regmap, INA2XX_CONFIG, data->config->config_default);
914 	if (ret < 0)
915 		return ret;
916 
917 	if (data->config->has_alerts) {
918 		bool active_high = device_property_read_bool(dev, "ti,alert-polarity-active-high");
919 
920 		regmap_update_bits(regmap, INA226_MASK_ENABLE,
921 				   INA226_ALERT_LATCH_ENABLE | INA226_ALERT_POLARITY,
922 				   INA226_ALERT_LATCH_ENABLE |
923 						FIELD_PREP(INA226_ALERT_POLARITY, active_high));
924 	}
925 	if (data->config->has_power_average) {
926 		if (data->chip == sy24655) {
927 			/*
928 			 * Initialize the power accumulation method to continuous
929 			 * mode and clear the EIN register after each read of the
930 			 * EIN register
931 			 */
932 			ret = regmap_write(regmap, SY24655_ACCUM_CONFIG,
933 					   SY24655_ACCUM_CONFIG_DEFAULT);
934 			if (ret < 0)
935 				return ret;
936 		}
937 	}
938 
939 	if (data->config->has_ishunt)
940 		return 0;
941 
942 	/*
943 	 * Calibration register is set to the best value, which eliminates
944 	 * truncation errors on calculating current register in hardware.
945 	 * According to datasheet (eq. 3) the best values are 2048 for
946 	 * ina226 and 4096 for ina219. They are hardcoded as calibration_value.
947 	 */
948 	return regmap_write(regmap, INA2XX_CALIBRATION,
949 			    data->config->calibration_value);
950 }
951 
952 static int ina2xx_probe(struct i2c_client *client)
953 {
954 	struct device *dev = &client->dev;
955 	struct ina2xx_data *data;
956 	struct device *hwmon_dev;
957 	enum ina2xx_ids chip;
958 	int ret;
959 
960 	chip = (uintptr_t)i2c_get_match_data(client);
961 
962 	data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);
963 	if (!data)
964 		return -ENOMEM;
965 
966 	/* set the device type */
967 	data->client = client;
968 	data->config = &ina2xx_config[chip];
969 	data->chip = chip;
970 
971 	data->regmap = devm_regmap_init_i2c(client, &ina2xx_regmap_config);
972 	if (IS_ERR(data->regmap)) {
973 		dev_err(dev, "failed to allocate register map\n");
974 		return PTR_ERR(data->regmap);
975 	}
976 
977 	/*
978 	 * Regulator core returns -ENODEV if the 'vs' is not available.
979 	 * Hence the check for -ENODEV return code is necessary.
980 	 */
981 	ret = devm_regulator_get_enable_optional(dev, "vs");
982 	if (ret < 0 && ret != -ENODEV)
983 		return dev_err_probe(dev, ret, "failed to enable vs regulator\n");
984 
985 	ret = ina2xx_init(dev, data);
986 	if (ret < 0)
987 		return dev_err_probe(dev, ret, "failed to configure device\n");
988 
989 	hwmon_dev = devm_hwmon_device_register_with_info(dev, client->name,
990 							 data, &ina2xx_chip_info,
991 							 data->config->has_ishunt ?
992 								NULL : ina2xx_groups);
993 	if (IS_ERR(hwmon_dev))
994 		return PTR_ERR(hwmon_dev);
995 
996 	dev_info(dev, "power monitor %s (Rshunt = %li uOhm)\n",
997 		 client->name, data->rshunt);
998 
999 	return 0;
1000 }
1001 
1002 static const struct i2c_device_id ina2xx_id[] = {
1003 	{ "ina219", ina219 },
1004 	{ "ina220", ina219 },
1005 	{ "ina226", ina226 },
1006 	{ "ina230", ina226 },
1007 	{ "ina231", ina226 },
1008 	{ "ina234", ina234 },
1009 	{ "ina260", ina260 },
1010 	{ "sy24655", sy24655 },
1011 	{ }
1012 };
1013 MODULE_DEVICE_TABLE(i2c, ina2xx_id);
1014 
1015 static const struct of_device_id __maybe_unused ina2xx_of_match[] = {
1016 	{
1017 		.compatible = "silergy,sy24655",
1018 		.data = (void *)sy24655
1019 	},
1020 	{
1021 		.compatible = "ti,ina219",
1022 		.data = (void *)ina219
1023 	},
1024 	{
1025 		.compatible = "ti,ina220",
1026 		.data = (void *)ina219
1027 	},
1028 	{
1029 		.compatible = "ti,ina226",
1030 		.data = (void *)ina226
1031 	},
1032 	{
1033 		.compatible = "ti,ina230",
1034 		.data = (void *)ina226
1035 	},
1036 	{
1037 		.compatible = "ti,ina231",
1038 		.data = (void *)ina226
1039 	},
1040 	{
1041 		.compatible = "ti,ina234",
1042 		.data = (void *)ina234
1043 	},
1044 	{
1045 		.compatible = "ti,ina260",
1046 		.data = (void *)ina260
1047 	},
1048 	{ }
1049 };
1050 MODULE_DEVICE_TABLE(of, ina2xx_of_match);
1051 
1052 static struct i2c_driver ina2xx_driver = {
1053 	.driver = {
1054 		.name	= "ina2xx",
1055 		.of_match_table = of_match_ptr(ina2xx_of_match),
1056 	},
1057 	.probe		= ina2xx_probe,
1058 	.id_table	= ina2xx_id,
1059 };
1060 
1061 module_i2c_driver(ina2xx_driver);
1062 
1063 MODULE_AUTHOR("Lothar Felten <l-felten@ti.com>");
1064 MODULE_DESCRIPTION("ina2xx driver");
1065 MODULE_LICENSE("GPL");
1066