xref: /openbmc/linux/drivers/hwmon/ina3221.c (revision ae213c44)
1 /*
2  * INA3221 Triple Current/Voltage Monitor
3  *
4  * Copyright (C) 2016 Texas Instruments Incorporated - http://www.ti.com/
5  *	Andrew F. Davis <afd@ti.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  */
16 
17 #include <linux/hwmon.h>
18 #include <linux/hwmon-sysfs.h>
19 #include <linux/i2c.h>
20 #include <linux/module.h>
21 #include <linux/mutex.h>
22 #include <linux/of.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/regmap.h>
25 #include <linux/util_macros.h>
26 
27 #define INA3221_DRIVER_NAME		"ina3221"
28 
29 #define INA3221_CONFIG			0x00
30 #define INA3221_SHUNT1			0x01
31 #define INA3221_BUS1			0x02
32 #define INA3221_SHUNT2			0x03
33 #define INA3221_BUS2			0x04
34 #define INA3221_SHUNT3			0x05
35 #define INA3221_BUS3			0x06
36 #define INA3221_CRIT1			0x07
37 #define INA3221_WARN1			0x08
38 #define INA3221_CRIT2			0x09
39 #define INA3221_WARN2			0x0a
40 #define INA3221_CRIT3			0x0b
41 #define INA3221_WARN3			0x0c
42 #define INA3221_MASK_ENABLE		0x0f
43 
44 #define INA3221_CONFIG_MODE_MASK	GENMASK(2, 0)
45 #define INA3221_CONFIG_MODE_POWERDOWN	0
46 #define INA3221_CONFIG_MODE_SHUNT	BIT(0)
47 #define INA3221_CONFIG_MODE_BUS		BIT(1)
48 #define INA3221_CONFIG_MODE_CONTINUOUS	BIT(2)
49 #define INA3221_CONFIG_VSH_CT_SHIFT	3
50 #define INA3221_CONFIG_VSH_CT_MASK	GENMASK(5, 3)
51 #define INA3221_CONFIG_VSH_CT(x)	(((x) & GENMASK(5, 3)) >> 3)
52 #define INA3221_CONFIG_VBUS_CT_SHIFT	6
53 #define INA3221_CONFIG_VBUS_CT_MASK	GENMASK(8, 6)
54 #define INA3221_CONFIG_VBUS_CT(x)	(((x) & GENMASK(8, 6)) >> 6)
55 #define INA3221_CONFIG_AVG_SHIFT	9
56 #define INA3221_CONFIG_AVG_MASK		GENMASK(11, 9)
57 #define INA3221_CONFIG_AVG(x)		(((x) & GENMASK(11, 9)) >> 9)
58 #define INA3221_CONFIG_CHs_EN_MASK	GENMASK(14, 12)
59 #define INA3221_CONFIG_CHx_EN(x)	BIT(14 - (x))
60 
61 #define INA3221_CONFIG_DEFAULT		0x7127
62 #define INA3221_RSHUNT_DEFAULT		10000
63 
64 enum ina3221_fields {
65 	/* Configuration */
66 	F_RST,
67 
68 	/* Status Flags */
69 	F_CVRF,
70 
71 	/* Alert Flags */
72 	F_WF3, F_WF2, F_WF1,
73 	F_CF3, F_CF2, F_CF1,
74 
75 	/* sentinel */
76 	F_MAX_FIELDS
77 };
78 
79 static const struct reg_field ina3221_reg_fields[] = {
80 	[F_RST] = REG_FIELD(INA3221_CONFIG, 15, 15),
81 
82 	[F_CVRF] = REG_FIELD(INA3221_MASK_ENABLE, 0, 0),
83 	[F_WF3] = REG_FIELD(INA3221_MASK_ENABLE, 3, 3),
84 	[F_WF2] = REG_FIELD(INA3221_MASK_ENABLE, 4, 4),
85 	[F_WF1] = REG_FIELD(INA3221_MASK_ENABLE, 5, 5),
86 	[F_CF3] = REG_FIELD(INA3221_MASK_ENABLE, 7, 7),
87 	[F_CF2] = REG_FIELD(INA3221_MASK_ENABLE, 8, 8),
88 	[F_CF1] = REG_FIELD(INA3221_MASK_ENABLE, 9, 9),
89 };
90 
91 enum ina3221_channels {
92 	INA3221_CHANNEL1,
93 	INA3221_CHANNEL2,
94 	INA3221_CHANNEL3,
95 	INA3221_NUM_CHANNELS
96 };
97 
98 /**
99  * struct ina3221_input - channel input source specific information
100  * @label: label of channel input source
101  * @shunt_resistor: shunt resistor value of channel input source
102  * @disconnected: connection status of channel input source
103  */
104 struct ina3221_input {
105 	const char *label;
106 	int shunt_resistor;
107 	bool disconnected;
108 };
109 
110 /**
111  * struct ina3221_data - device specific information
112  * @pm_dev: Device pointer for pm runtime
113  * @regmap: Register map of the device
114  * @fields: Register fields of the device
115  * @inputs: Array of channel input source specific structures
116  * @lock: mutex lock to serialize sysfs attribute accesses
117  * @reg_config: Register value of INA3221_CONFIG
118  * @single_shot: running in single-shot operating mode
119  */
120 struct ina3221_data {
121 	struct device *pm_dev;
122 	struct regmap *regmap;
123 	struct regmap_field *fields[F_MAX_FIELDS];
124 	struct ina3221_input inputs[INA3221_NUM_CHANNELS];
125 	struct mutex lock;
126 	u32 reg_config;
127 
128 	bool single_shot;
129 };
130 
131 static inline bool ina3221_is_enabled(struct ina3221_data *ina, int channel)
132 {
133 	return pm_runtime_active(ina->pm_dev) &&
134 	       (ina->reg_config & INA3221_CONFIG_CHx_EN(channel));
135 }
136 
137 /* Lookup table for Bus and Shunt conversion times in usec */
138 static const u16 ina3221_conv_time[] = {
139 	140, 204, 332, 588, 1100, 2116, 4156, 8244,
140 };
141 
142 /* Lookup table for number of samples using in averaging mode */
143 static const int ina3221_avg_samples[] = {
144 	1, 4, 16, 64, 128, 256, 512, 1024,
145 };
146 
147 /* Converting update_interval in msec to conversion time in usec */
148 static inline u32 ina3221_interval_ms_to_conv_time(u16 config, int interval)
149 {
150 	u32 channels = hweight16(config & INA3221_CONFIG_CHs_EN_MASK);
151 	u32 samples_idx = INA3221_CONFIG_AVG(config);
152 	u32 samples = ina3221_avg_samples[samples_idx];
153 
154 	/* Bisect the result to Bus and Shunt conversion times */
155 	return DIV_ROUND_CLOSEST(interval * 1000 / 2, channels * samples);
156 }
157 
158 /* Converting CONFIG register value to update_interval in usec */
159 static inline u32 ina3221_reg_to_interval_us(u16 config)
160 {
161 	u32 channels = hweight16(config & INA3221_CONFIG_CHs_EN_MASK);
162 	u32 vbus_ct_idx = INA3221_CONFIG_VBUS_CT(config);
163 	u32 vsh_ct_idx = INA3221_CONFIG_VSH_CT(config);
164 	u32 samples_idx = INA3221_CONFIG_AVG(config);
165 	u32 samples = ina3221_avg_samples[samples_idx];
166 	u32 vbus_ct = ina3221_conv_time[vbus_ct_idx];
167 	u32 vsh_ct = ina3221_conv_time[vsh_ct_idx];
168 
169 	/* Calculate total conversion time */
170 	return channels * (vbus_ct + vsh_ct) * samples;
171 }
172 
173 static inline int ina3221_wait_for_data(struct ina3221_data *ina)
174 {
175 	u32 wait, cvrf;
176 
177 	wait = ina3221_reg_to_interval_us(ina->reg_config);
178 
179 	/* Polling the CVRF bit to make sure read data is ready */
180 	return regmap_field_read_poll_timeout(ina->fields[F_CVRF],
181 					      cvrf, cvrf, wait, 100000);
182 }
183 
184 static int ina3221_read_value(struct ina3221_data *ina, unsigned int reg,
185 			      int *val)
186 {
187 	unsigned int regval;
188 	int ret;
189 
190 	ret = regmap_read(ina->regmap, reg, &regval);
191 	if (ret)
192 		return ret;
193 
194 	*val = sign_extend32(regval >> 3, 12);
195 
196 	return 0;
197 }
198 
199 static const u8 ina3221_in_reg[] = {
200 	INA3221_BUS1,
201 	INA3221_BUS2,
202 	INA3221_BUS3,
203 	INA3221_SHUNT1,
204 	INA3221_SHUNT2,
205 	INA3221_SHUNT3,
206 };
207 
208 static int ina3221_read_chip(struct device *dev, u32 attr, long *val)
209 {
210 	struct ina3221_data *ina = dev_get_drvdata(dev);
211 	int regval;
212 
213 	switch (attr) {
214 	case hwmon_chip_samples:
215 		regval = INA3221_CONFIG_AVG(ina->reg_config);
216 		*val = ina3221_avg_samples[regval];
217 		return 0;
218 	case hwmon_chip_update_interval:
219 		/* Return in msec */
220 		*val = ina3221_reg_to_interval_us(ina->reg_config);
221 		*val = DIV_ROUND_CLOSEST(*val, 1000);
222 		return 0;
223 	default:
224 		return -EOPNOTSUPP;
225 	}
226 }
227 
228 static int ina3221_read_in(struct device *dev, u32 attr, int channel, long *val)
229 {
230 	const bool is_shunt = channel > INA3221_CHANNEL3;
231 	struct ina3221_data *ina = dev_get_drvdata(dev);
232 	u8 reg = ina3221_in_reg[channel];
233 	int regval, ret;
234 
235 	/* Translate shunt channel index to sensor channel index */
236 	channel %= INA3221_NUM_CHANNELS;
237 
238 	switch (attr) {
239 	case hwmon_in_input:
240 		if (!ina3221_is_enabled(ina, channel))
241 			return -ENODATA;
242 
243 		/* Write CONFIG register to trigger a single-shot measurement */
244 		if (ina->single_shot)
245 			regmap_write(ina->regmap, INA3221_CONFIG,
246 				     ina->reg_config);
247 
248 		ret = ina3221_wait_for_data(ina);
249 		if (ret)
250 			return ret;
251 
252 		ret = ina3221_read_value(ina, reg, &regval);
253 		if (ret)
254 			return ret;
255 
256 		/*
257 		 * Scale of shunt voltage (uV): LSB is 40uV
258 		 * Scale of bus voltage (mV): LSB is 8mV
259 		 */
260 		*val = regval * (is_shunt ? 40 : 8);
261 		return 0;
262 	case hwmon_in_enable:
263 		*val = ina3221_is_enabled(ina, channel);
264 		return 0;
265 	default:
266 		return -EOPNOTSUPP;
267 	}
268 }
269 
270 static const u8 ina3221_curr_reg[][INA3221_NUM_CHANNELS] = {
271 	[hwmon_curr_input] = { INA3221_SHUNT1, INA3221_SHUNT2, INA3221_SHUNT3 },
272 	[hwmon_curr_max] = { INA3221_WARN1, INA3221_WARN2, INA3221_WARN3 },
273 	[hwmon_curr_crit] = { INA3221_CRIT1, INA3221_CRIT2, INA3221_CRIT3 },
274 	[hwmon_curr_max_alarm] = { F_WF1, F_WF2, F_WF3 },
275 	[hwmon_curr_crit_alarm] = { F_CF1, F_CF2, F_CF3 },
276 };
277 
278 static int ina3221_read_curr(struct device *dev, u32 attr,
279 			     int channel, long *val)
280 {
281 	struct ina3221_data *ina = dev_get_drvdata(dev);
282 	struct ina3221_input *input = &ina->inputs[channel];
283 	int resistance_uo = input->shunt_resistor;
284 	u8 reg = ina3221_curr_reg[attr][channel];
285 	int regval, voltage_nv, ret;
286 
287 	switch (attr) {
288 	case hwmon_curr_input:
289 		if (!ina3221_is_enabled(ina, channel))
290 			return -ENODATA;
291 
292 		/* Write CONFIG register to trigger a single-shot measurement */
293 		if (ina->single_shot)
294 			regmap_write(ina->regmap, INA3221_CONFIG,
295 				     ina->reg_config);
296 
297 		ret = ina3221_wait_for_data(ina);
298 		if (ret)
299 			return ret;
300 
301 		/* fall through */
302 	case hwmon_curr_crit:
303 	case hwmon_curr_max:
304 		ret = ina3221_read_value(ina, reg, &regval);
305 		if (ret)
306 			return ret;
307 
308 		/* Scale of shunt voltage: LSB is 40uV (40000nV) */
309 		voltage_nv = regval * 40000;
310 		/* Return current in mA */
311 		*val = DIV_ROUND_CLOSEST(voltage_nv, resistance_uo);
312 		return 0;
313 	case hwmon_curr_crit_alarm:
314 	case hwmon_curr_max_alarm:
315 		/* No actual register read if channel is disabled */
316 		if (!ina3221_is_enabled(ina, channel)) {
317 			/* Return 0 for alert flags */
318 			*val = 0;
319 			return 0;
320 		}
321 		ret = regmap_field_read(ina->fields[reg], &regval);
322 		if (ret)
323 			return ret;
324 		*val = regval;
325 		return 0;
326 	default:
327 		return -EOPNOTSUPP;
328 	}
329 }
330 
331 static int ina3221_write_chip(struct device *dev, u32 attr, long val)
332 {
333 	struct ina3221_data *ina = dev_get_drvdata(dev);
334 	int ret, idx;
335 	u32 tmp;
336 
337 	switch (attr) {
338 	case hwmon_chip_samples:
339 		idx = find_closest(val, ina3221_avg_samples,
340 				   ARRAY_SIZE(ina3221_avg_samples));
341 
342 		tmp = (ina->reg_config & ~INA3221_CONFIG_AVG_MASK) |
343 		      (idx << INA3221_CONFIG_AVG_SHIFT);
344 		ret = regmap_write(ina->regmap, INA3221_CONFIG, tmp);
345 		if (ret)
346 			return ret;
347 
348 		/* Update reg_config accordingly */
349 		ina->reg_config = tmp;
350 		return 0;
351 	case hwmon_chip_update_interval:
352 		tmp = ina3221_interval_ms_to_conv_time(ina->reg_config, val);
353 		idx = find_closest(tmp, ina3221_conv_time,
354 				   ARRAY_SIZE(ina3221_conv_time));
355 
356 		/* Update Bus and Shunt voltage conversion times */
357 		tmp = INA3221_CONFIG_VBUS_CT_MASK | INA3221_CONFIG_VSH_CT_MASK;
358 		tmp = (ina->reg_config & ~tmp) |
359 		      (idx << INA3221_CONFIG_VBUS_CT_SHIFT) |
360 		      (idx << INA3221_CONFIG_VSH_CT_SHIFT);
361 		ret = regmap_write(ina->regmap, INA3221_CONFIG, tmp);
362 		if (ret)
363 			return ret;
364 
365 		/* Update reg_config accordingly */
366 		ina->reg_config = tmp;
367 		return 0;
368 	default:
369 		return -EOPNOTSUPP;
370 	}
371 }
372 
373 static int ina3221_write_curr(struct device *dev, u32 attr,
374 			      int channel, long val)
375 {
376 	struct ina3221_data *ina = dev_get_drvdata(dev);
377 	struct ina3221_input *input = &ina->inputs[channel];
378 	int resistance_uo = input->shunt_resistor;
379 	u8 reg = ina3221_curr_reg[attr][channel];
380 	int regval, current_ma, voltage_uv;
381 
382 	/* clamp current */
383 	current_ma = clamp_val(val,
384 			       INT_MIN / resistance_uo,
385 			       INT_MAX / resistance_uo);
386 
387 	voltage_uv = DIV_ROUND_CLOSEST(current_ma * resistance_uo, 1000);
388 
389 	/* clamp voltage */
390 	voltage_uv = clamp_val(voltage_uv, -163800, 163800);
391 
392 	/* 1 / 40uV(scale) << 3(register shift) = 5 */
393 	regval = DIV_ROUND_CLOSEST(voltage_uv, 5) & 0xfff8;
394 
395 	return regmap_write(ina->regmap, reg, regval);
396 }
397 
398 static int ina3221_write_enable(struct device *dev, int channel, bool enable)
399 {
400 	struct ina3221_data *ina = dev_get_drvdata(dev);
401 	u16 config, mask = INA3221_CONFIG_CHx_EN(channel);
402 	u16 config_old = ina->reg_config & mask;
403 	u32 tmp;
404 	int ret;
405 
406 	config = enable ? mask : 0;
407 
408 	/* Bypass if enable status is not being changed */
409 	if (config_old == config)
410 		return 0;
411 
412 	/* For enabling routine, increase refcount and resume() at first */
413 	if (enable) {
414 		ret = pm_runtime_get_sync(ina->pm_dev);
415 		if (ret < 0) {
416 			dev_err(dev, "Failed to get PM runtime\n");
417 			return ret;
418 		}
419 	}
420 
421 	/* Enable or disable the channel */
422 	tmp = (ina->reg_config & ~mask) | (config & mask);
423 	ret = regmap_write(ina->regmap, INA3221_CONFIG, tmp);
424 	if (ret)
425 		goto fail;
426 
427 	/* Cache the latest config register value */
428 	ina->reg_config = tmp;
429 
430 	/* For disabling routine, decrease refcount or suspend() at last */
431 	if (!enable)
432 		pm_runtime_put_sync(ina->pm_dev);
433 
434 	return 0;
435 
436 fail:
437 	if (enable) {
438 		dev_err(dev, "Failed to enable channel %d: error %d\n",
439 			channel, ret);
440 		pm_runtime_put_sync(ina->pm_dev);
441 	}
442 
443 	return ret;
444 }
445 
446 static int ina3221_read(struct device *dev, enum hwmon_sensor_types type,
447 			u32 attr, int channel, long *val)
448 {
449 	struct ina3221_data *ina = dev_get_drvdata(dev);
450 	int ret;
451 
452 	mutex_lock(&ina->lock);
453 
454 	switch (type) {
455 	case hwmon_chip:
456 		ret = ina3221_read_chip(dev, attr, val);
457 		break;
458 	case hwmon_in:
459 		/* 0-align channel ID */
460 		ret = ina3221_read_in(dev, attr, channel - 1, val);
461 		break;
462 	case hwmon_curr:
463 		ret = ina3221_read_curr(dev, attr, channel, val);
464 		break;
465 	default:
466 		ret = -EOPNOTSUPP;
467 		break;
468 	}
469 
470 	mutex_unlock(&ina->lock);
471 
472 	return ret;
473 }
474 
475 static int ina3221_write(struct device *dev, enum hwmon_sensor_types type,
476 			 u32 attr, int channel, long val)
477 {
478 	struct ina3221_data *ina = dev_get_drvdata(dev);
479 	int ret;
480 
481 	mutex_lock(&ina->lock);
482 
483 	switch (type) {
484 	case hwmon_chip:
485 		ret = ina3221_write_chip(dev, attr, val);
486 		break;
487 	case hwmon_in:
488 		/* 0-align channel ID */
489 		ret = ina3221_write_enable(dev, channel - 1, val);
490 		break;
491 	case hwmon_curr:
492 		ret = ina3221_write_curr(dev, attr, channel, val);
493 		break;
494 	default:
495 		ret = -EOPNOTSUPP;
496 		break;
497 	}
498 
499 	mutex_unlock(&ina->lock);
500 
501 	return ret;
502 }
503 
504 static int ina3221_read_string(struct device *dev, enum hwmon_sensor_types type,
505 			       u32 attr, int channel, const char **str)
506 {
507 	struct ina3221_data *ina = dev_get_drvdata(dev);
508 	int index = channel - 1;
509 
510 	*str = ina->inputs[index].label;
511 
512 	return 0;
513 }
514 
515 static umode_t ina3221_is_visible(const void *drvdata,
516 				  enum hwmon_sensor_types type,
517 				  u32 attr, int channel)
518 {
519 	const struct ina3221_data *ina = drvdata;
520 	const struct ina3221_input *input = NULL;
521 
522 	switch (type) {
523 	case hwmon_chip:
524 		switch (attr) {
525 		case hwmon_chip_samples:
526 		case hwmon_chip_update_interval:
527 			return 0644;
528 		default:
529 			return 0;
530 		}
531 	case hwmon_in:
532 		/* Ignore in0_ */
533 		if (channel == 0)
534 			return 0;
535 
536 		switch (attr) {
537 		case hwmon_in_label:
538 			if (channel - 1 <= INA3221_CHANNEL3)
539 				input = &ina->inputs[channel - 1];
540 			/* Hide label node if label is not provided */
541 			return (input && input->label) ? 0444 : 0;
542 		case hwmon_in_input:
543 			return 0444;
544 		case hwmon_in_enable:
545 			return 0644;
546 		default:
547 			return 0;
548 		}
549 	case hwmon_curr:
550 		switch (attr) {
551 		case hwmon_curr_input:
552 		case hwmon_curr_crit_alarm:
553 		case hwmon_curr_max_alarm:
554 			return 0444;
555 		case hwmon_curr_crit:
556 		case hwmon_curr_max:
557 			return 0644;
558 		default:
559 			return 0;
560 		}
561 	default:
562 		return 0;
563 	}
564 }
565 
566 #define INA3221_HWMON_CURR_CONFIG (HWMON_C_INPUT | \
567 				   HWMON_C_CRIT | HWMON_C_CRIT_ALARM | \
568 				   HWMON_C_MAX | HWMON_C_MAX_ALARM)
569 
570 static const struct hwmon_channel_info *ina3221_info[] = {
571 	HWMON_CHANNEL_INFO(chip,
572 			   HWMON_C_SAMPLES,
573 			   HWMON_C_UPDATE_INTERVAL),
574 	HWMON_CHANNEL_INFO(in,
575 			   /* 0: dummy, skipped in is_visible */
576 			   HWMON_I_INPUT,
577 			   /* 1-3: input voltage Channels */
578 			   HWMON_I_INPUT | HWMON_I_ENABLE | HWMON_I_LABEL,
579 			   HWMON_I_INPUT | HWMON_I_ENABLE | HWMON_I_LABEL,
580 			   HWMON_I_INPUT | HWMON_I_ENABLE | HWMON_I_LABEL,
581 			   /* 4-6: shunt voltage Channels */
582 			   HWMON_I_INPUT,
583 			   HWMON_I_INPUT,
584 			   HWMON_I_INPUT),
585 	HWMON_CHANNEL_INFO(curr,
586 			   INA3221_HWMON_CURR_CONFIG,
587 			   INA3221_HWMON_CURR_CONFIG,
588 			   INA3221_HWMON_CURR_CONFIG),
589 	NULL
590 };
591 
592 static const struct hwmon_ops ina3221_hwmon_ops = {
593 	.is_visible = ina3221_is_visible,
594 	.read_string = ina3221_read_string,
595 	.read = ina3221_read,
596 	.write = ina3221_write,
597 };
598 
599 static const struct hwmon_chip_info ina3221_chip_info = {
600 	.ops = &ina3221_hwmon_ops,
601 	.info = ina3221_info,
602 };
603 
604 /* Extra attribute groups */
605 static ssize_t ina3221_shunt_show(struct device *dev,
606 				  struct device_attribute *attr, char *buf)
607 {
608 	struct sensor_device_attribute *sd_attr = to_sensor_dev_attr(attr);
609 	struct ina3221_data *ina = dev_get_drvdata(dev);
610 	unsigned int channel = sd_attr->index;
611 	struct ina3221_input *input = &ina->inputs[channel];
612 
613 	return snprintf(buf, PAGE_SIZE, "%d\n", input->shunt_resistor);
614 }
615 
616 static ssize_t ina3221_shunt_store(struct device *dev,
617 				   struct device_attribute *attr,
618 				   const char *buf, size_t count)
619 {
620 	struct sensor_device_attribute *sd_attr = to_sensor_dev_attr(attr);
621 	struct ina3221_data *ina = dev_get_drvdata(dev);
622 	unsigned int channel = sd_attr->index;
623 	struct ina3221_input *input = &ina->inputs[channel];
624 	int val;
625 	int ret;
626 
627 	ret = kstrtoint(buf, 0, &val);
628 	if (ret)
629 		return ret;
630 
631 	val = clamp_val(val, 1, INT_MAX);
632 
633 	input->shunt_resistor = val;
634 
635 	return count;
636 }
637 
638 /* shunt resistance */
639 static SENSOR_DEVICE_ATTR_RW(shunt1_resistor, ina3221_shunt, INA3221_CHANNEL1);
640 static SENSOR_DEVICE_ATTR_RW(shunt2_resistor, ina3221_shunt, INA3221_CHANNEL2);
641 static SENSOR_DEVICE_ATTR_RW(shunt3_resistor, ina3221_shunt, INA3221_CHANNEL3);
642 
643 static struct attribute *ina3221_attrs[] = {
644 	&sensor_dev_attr_shunt1_resistor.dev_attr.attr,
645 	&sensor_dev_attr_shunt2_resistor.dev_attr.attr,
646 	&sensor_dev_attr_shunt3_resistor.dev_attr.attr,
647 	NULL,
648 };
649 ATTRIBUTE_GROUPS(ina3221);
650 
651 static const struct regmap_range ina3221_yes_ranges[] = {
652 	regmap_reg_range(INA3221_CONFIG, INA3221_BUS3),
653 	regmap_reg_range(INA3221_MASK_ENABLE, INA3221_MASK_ENABLE),
654 };
655 
656 static const struct regmap_access_table ina3221_volatile_table = {
657 	.yes_ranges = ina3221_yes_ranges,
658 	.n_yes_ranges = ARRAY_SIZE(ina3221_yes_ranges),
659 };
660 
661 static const struct regmap_config ina3221_regmap_config = {
662 	.reg_bits = 8,
663 	.val_bits = 16,
664 
665 	.cache_type = REGCACHE_RBTREE,
666 	.volatile_table = &ina3221_volatile_table,
667 };
668 
669 static int ina3221_probe_child_from_dt(struct device *dev,
670 				       struct device_node *child,
671 				       struct ina3221_data *ina)
672 {
673 	struct ina3221_input *input;
674 	u32 val;
675 	int ret;
676 
677 	ret = of_property_read_u32(child, "reg", &val);
678 	if (ret) {
679 		dev_err(dev, "missing reg property of %pOFn\n", child);
680 		return ret;
681 	} else if (val > INA3221_CHANNEL3) {
682 		dev_err(dev, "invalid reg %d of %pOFn\n", val, child);
683 		return ret;
684 	}
685 
686 	input = &ina->inputs[val];
687 
688 	/* Log the disconnected channel input */
689 	if (!of_device_is_available(child)) {
690 		input->disconnected = true;
691 		return 0;
692 	}
693 
694 	/* Save the connected input label if available */
695 	of_property_read_string(child, "label", &input->label);
696 
697 	/* Overwrite default shunt resistor value optionally */
698 	if (!of_property_read_u32(child, "shunt-resistor-micro-ohms", &val)) {
699 		if (val < 1 || val > INT_MAX) {
700 			dev_err(dev, "invalid shunt resistor value %u of %pOFn\n",
701 				val, child);
702 			return -EINVAL;
703 		}
704 		input->shunt_resistor = val;
705 	}
706 
707 	return 0;
708 }
709 
710 static int ina3221_probe_from_dt(struct device *dev, struct ina3221_data *ina)
711 {
712 	const struct device_node *np = dev->of_node;
713 	struct device_node *child;
714 	int ret;
715 
716 	/* Compatible with non-DT platforms */
717 	if (!np)
718 		return 0;
719 
720 	ina->single_shot = of_property_read_bool(np, "ti,single-shot");
721 
722 	for_each_child_of_node(np, child) {
723 		ret = ina3221_probe_child_from_dt(dev, child, ina);
724 		if (ret)
725 			return ret;
726 	}
727 
728 	return 0;
729 }
730 
731 static int ina3221_probe(struct i2c_client *client,
732 			 const struct i2c_device_id *id)
733 {
734 	struct device *dev = &client->dev;
735 	struct ina3221_data *ina;
736 	struct device *hwmon_dev;
737 	int i, ret;
738 
739 	ina = devm_kzalloc(dev, sizeof(*ina), GFP_KERNEL);
740 	if (!ina)
741 		return -ENOMEM;
742 
743 	ina->regmap = devm_regmap_init_i2c(client, &ina3221_regmap_config);
744 	if (IS_ERR(ina->regmap)) {
745 		dev_err(dev, "Unable to allocate register map\n");
746 		return PTR_ERR(ina->regmap);
747 	}
748 
749 	for (i = 0; i < F_MAX_FIELDS; i++) {
750 		ina->fields[i] = devm_regmap_field_alloc(dev,
751 							 ina->regmap,
752 							 ina3221_reg_fields[i]);
753 		if (IS_ERR(ina->fields[i])) {
754 			dev_err(dev, "Unable to allocate regmap fields\n");
755 			return PTR_ERR(ina->fields[i]);
756 		}
757 	}
758 
759 	for (i = 0; i < INA3221_NUM_CHANNELS; i++)
760 		ina->inputs[i].shunt_resistor = INA3221_RSHUNT_DEFAULT;
761 
762 	ret = ina3221_probe_from_dt(dev, ina);
763 	if (ret) {
764 		dev_err(dev, "Unable to probe from device tree\n");
765 		return ret;
766 	}
767 
768 	/* The driver will be reset, so use reset value */
769 	ina->reg_config = INA3221_CONFIG_DEFAULT;
770 
771 	/* Clear continuous bit to use single-shot mode */
772 	if (ina->single_shot)
773 		ina->reg_config &= ~INA3221_CONFIG_MODE_CONTINUOUS;
774 
775 	/* Disable channels if their inputs are disconnected */
776 	for (i = 0; i < INA3221_NUM_CHANNELS; i++) {
777 		if (ina->inputs[i].disconnected)
778 			ina->reg_config &= ~INA3221_CONFIG_CHx_EN(i);
779 	}
780 
781 	ina->pm_dev = dev;
782 	mutex_init(&ina->lock);
783 	dev_set_drvdata(dev, ina);
784 
785 	/* Enable PM runtime -- status is suspended by default */
786 	pm_runtime_enable(ina->pm_dev);
787 
788 	/* Initialize (resume) the device */
789 	for (i = 0; i < INA3221_NUM_CHANNELS; i++) {
790 		if (ina->inputs[i].disconnected)
791 			continue;
792 		/* Match the refcount with number of enabled channels */
793 		ret = pm_runtime_get_sync(ina->pm_dev);
794 		if (ret < 0)
795 			goto fail;
796 	}
797 
798 	hwmon_dev = devm_hwmon_device_register_with_info(dev, client->name, ina,
799 							 &ina3221_chip_info,
800 							 ina3221_groups);
801 	if (IS_ERR(hwmon_dev)) {
802 		dev_err(dev, "Unable to register hwmon device\n");
803 		ret = PTR_ERR(hwmon_dev);
804 		goto fail;
805 	}
806 
807 	return 0;
808 
809 fail:
810 	pm_runtime_disable(ina->pm_dev);
811 	pm_runtime_set_suspended(ina->pm_dev);
812 	/* pm_runtime_put_noidle() will decrease the PM refcount until 0 */
813 	for (i = 0; i < INA3221_NUM_CHANNELS; i++)
814 		pm_runtime_put_noidle(ina->pm_dev);
815 	mutex_destroy(&ina->lock);
816 
817 	return ret;
818 }
819 
820 static int ina3221_remove(struct i2c_client *client)
821 {
822 	struct ina3221_data *ina = dev_get_drvdata(&client->dev);
823 	int i;
824 
825 	pm_runtime_disable(ina->pm_dev);
826 	pm_runtime_set_suspended(ina->pm_dev);
827 
828 	/* pm_runtime_put_noidle() will decrease the PM refcount until 0 */
829 	for (i = 0; i < INA3221_NUM_CHANNELS; i++)
830 		pm_runtime_put_noidle(ina->pm_dev);
831 
832 	mutex_destroy(&ina->lock);
833 
834 	return 0;
835 }
836 
837 static int __maybe_unused ina3221_suspend(struct device *dev)
838 {
839 	struct ina3221_data *ina = dev_get_drvdata(dev);
840 	int ret;
841 
842 	/* Save config register value and enable cache-only */
843 	ret = regmap_read(ina->regmap, INA3221_CONFIG, &ina->reg_config);
844 	if (ret)
845 		return ret;
846 
847 	/* Set to power-down mode for power saving */
848 	ret = regmap_update_bits(ina->regmap, INA3221_CONFIG,
849 				 INA3221_CONFIG_MODE_MASK,
850 				 INA3221_CONFIG_MODE_POWERDOWN);
851 	if (ret)
852 		return ret;
853 
854 	regcache_cache_only(ina->regmap, true);
855 	regcache_mark_dirty(ina->regmap);
856 
857 	return 0;
858 }
859 
860 static int __maybe_unused ina3221_resume(struct device *dev)
861 {
862 	struct ina3221_data *ina = dev_get_drvdata(dev);
863 	int ret;
864 
865 	regcache_cache_only(ina->regmap, false);
866 
867 	/* Software reset the chip */
868 	ret = regmap_field_write(ina->fields[F_RST], true);
869 	if (ret) {
870 		dev_err(dev, "Unable to reset device\n");
871 		return ret;
872 	}
873 
874 	/* Restore cached register values to hardware */
875 	ret = regcache_sync(ina->regmap);
876 	if (ret)
877 		return ret;
878 
879 	/* Restore config register value to hardware */
880 	ret = regmap_write(ina->regmap, INA3221_CONFIG, ina->reg_config);
881 	if (ret)
882 		return ret;
883 
884 	return 0;
885 }
886 
887 static const struct dev_pm_ops ina3221_pm = {
888 	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
889 				pm_runtime_force_resume)
890 	SET_RUNTIME_PM_OPS(ina3221_suspend, ina3221_resume, NULL)
891 };
892 
893 static const struct of_device_id ina3221_of_match_table[] = {
894 	{ .compatible = "ti,ina3221", },
895 	{ /* sentinel */ }
896 };
897 MODULE_DEVICE_TABLE(of, ina3221_of_match_table);
898 
899 static const struct i2c_device_id ina3221_ids[] = {
900 	{ "ina3221", 0 },
901 	{ /* sentinel */ }
902 };
903 MODULE_DEVICE_TABLE(i2c, ina3221_ids);
904 
905 static struct i2c_driver ina3221_i2c_driver = {
906 	.probe = ina3221_probe,
907 	.remove = ina3221_remove,
908 	.driver = {
909 		.name = INA3221_DRIVER_NAME,
910 		.of_match_table = ina3221_of_match_table,
911 		.pm = &ina3221_pm,
912 	},
913 	.id_table = ina3221_ids,
914 };
915 module_i2c_driver(ina3221_i2c_driver);
916 
917 MODULE_AUTHOR("Andrew F. Davis <afd@ti.com>");
918 MODULE_DESCRIPTION("Texas Instruments INA3221 HWMon Driver");
919 MODULE_LICENSE("GPL v2");
920