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