1/*
2 * Driver for Texas Instruments INA219, INA226 power monitor chips
3 *
4 * INA219:
5 * Zero Drift Bi-Directional Current/Power Monitor with I2C Interface
6 * Datasheet: http://www.ti.com/product/ina219
7 *
8 * INA220:
9 * Bi-Directional Current/Power Monitor with I2C Interface
10 * Datasheet: http://www.ti.com/product/ina220
11 *
12 * INA226:
13 * Bi-Directional Current/Power Monitor with I2C Interface
14 * Datasheet: http://www.ti.com/product/ina226
15 *
16 * INA230:
17 * Bi-directional Current/Power Monitor with I2C Interface
18 * Datasheet: http://www.ti.com/product/ina230
19 *
20 * Copyright (C) 2012 Lothar Felten <l-felten@ti.com>
21 * Thanks to Jan Volkering
22 *
23 * This program is free software; you can redistribute it and/or modify
24 * it under the terms of the GNU General Public License as published by
25 * the Free Software Foundation; version 2 of the License.
26 */
27
28#include <linux/kernel.h>
29#include <linux/module.h>
30#include <linux/init.h>
31#include <linux/err.h>
32#include <linux/slab.h>
33#include <linux/i2c.h>
34#include <linux/hwmon.h>
35#include <linux/hwmon-sysfs.h>
36#include <linux/jiffies.h>
37#include <linux/of.h>
38#include <linux/delay.h>
39#include <linux/util_macros.h>
40
41#include <linux/platform_data/ina2xx.h>
42
43/* common register definitions */
44#define INA2XX_CONFIG			0x00
45#define INA2XX_SHUNT_VOLTAGE		0x01 /* readonly */
46#define INA2XX_BUS_VOLTAGE		0x02 /* readonly */
47#define INA2XX_POWER			0x03 /* readonly */
48#define INA2XX_CURRENT			0x04 /* readonly */
49#define INA2XX_CALIBRATION		0x05
50
51/* INA226 register definitions */
52#define INA226_MASK_ENABLE		0x06
53#define INA226_ALERT_LIMIT		0x07
54#define INA226_DIE_ID			0xFF
55
56/* register count */
57#define INA219_REGISTERS		6
58#define INA226_REGISTERS		8
59
60#define INA2XX_MAX_REGISTERS		8
61
62/* settings - depend on use case */
63#define INA219_CONFIG_DEFAULT		0x399F	/* PGA=8 */
64#define INA226_CONFIG_DEFAULT		0x4527	/* averages=16 */
65
66/* worst case is 68.10 ms (~14.6Hz, ina219) */
67#define INA2XX_CONVERSION_RATE		15
68#define INA2XX_MAX_DELAY		69 /* worst case delay in ms */
69
70#define INA2XX_RSHUNT_DEFAULT		10000
71
72/* bit mask for reading the averaging setting in the configuration register */
73#define INA226_AVG_RD_MASK		0x0E00
74
75#define INA226_READ_AVG(reg)		(((reg) & INA226_AVG_RD_MASK) >> 9)
76#define INA226_SHIFT_AVG(val)		((val) << 9)
77
78/* common attrs, ina226 attrs and NULL */
79#define INA2XX_MAX_ATTRIBUTE_GROUPS	3
80
81/*
82 * Both bus voltage and shunt voltage conversion times for ina226 are set
83 * to 0b0100 on POR, which translates to 2200 microseconds in total.
84 */
85#define INA226_TOTAL_CONV_TIME_DEFAULT	2200
86
87enum ina2xx_ids { ina219, ina226 };
88
89struct ina2xx_config {
90	u16 config_default;
91	int calibration_factor;
92	int registers;
93	int shunt_div;
94	int bus_voltage_shift;
95	int bus_voltage_lsb;	/* uV */
96	int power_lsb;		/* uW */
97};
98
99struct ina2xx_data {
100	struct i2c_client *client;
101	const struct ina2xx_config *config;
102
103	long rshunt;
104	u16 curr_config;
105
106	struct mutex update_lock;
107	bool valid;
108	unsigned long last_updated;
109	int update_interval; /* in jiffies */
110
111	int kind;
112	const struct attribute_group *groups[INA2XX_MAX_ATTRIBUTE_GROUPS];
113	u16 regs[INA2XX_MAX_REGISTERS];
114};
115
116static const struct ina2xx_config ina2xx_config[] = {
117	[ina219] = {
118		.config_default = INA219_CONFIG_DEFAULT,
119		.calibration_factor = 40960000,
120		.registers = INA219_REGISTERS,
121		.shunt_div = 100,
122		.bus_voltage_shift = 3,
123		.bus_voltage_lsb = 4000,
124		.power_lsb = 20000,
125	},
126	[ina226] = {
127		.config_default = INA226_CONFIG_DEFAULT,
128		.calibration_factor = 5120000,
129		.registers = INA226_REGISTERS,
130		.shunt_div = 400,
131		.bus_voltage_shift = 0,
132		.bus_voltage_lsb = 1250,
133		.power_lsb = 25000,
134	},
135};
136
137/*
138 * Available averaging rates for ina226. The indices correspond with
139 * the bit values expected by the chip (according to the ina226 datasheet,
140 * table 3 AVG bit settings, found at
141 * http://www.ti.com/lit/ds/symlink/ina226.pdf.
142 */
143static const int ina226_avg_tab[] = { 1, 4, 16, 64, 128, 256, 512, 1024 };
144
145static int ina226_reg_to_interval(u16 config)
146{
147	int avg = ina226_avg_tab[INA226_READ_AVG(config)];
148
149	/*
150	 * Multiply the total conversion time by the number of averages.
151	 * Return the result in milliseconds.
152	 */
153	return DIV_ROUND_CLOSEST(avg * INA226_TOTAL_CONV_TIME_DEFAULT, 1000);
154}
155
156static u16 ina226_interval_to_reg(int interval, u16 config)
157{
158	int avg, avg_bits;
159
160	avg = DIV_ROUND_CLOSEST(interval * 1000,
161				INA226_TOTAL_CONV_TIME_DEFAULT);
162	avg_bits = find_closest(avg, ina226_avg_tab,
163				ARRAY_SIZE(ina226_avg_tab));
164
165	return (config & ~INA226_AVG_RD_MASK) | INA226_SHIFT_AVG(avg_bits);
166}
167
168static void ina226_set_update_interval(struct ina2xx_data *data)
169{
170	int ms;
171
172	ms = ina226_reg_to_interval(data->curr_config);
173	data->update_interval = msecs_to_jiffies(ms);
174}
175
176static int ina2xx_calibrate(struct ina2xx_data *data)
177{
178	u16 val = DIV_ROUND_CLOSEST(data->config->calibration_factor,
179				    data->rshunt);
180
181	return i2c_smbus_write_word_swapped(data->client,
182					    INA2XX_CALIBRATION, val);
183}
184
185/*
186 * Initialize the configuration and calibration registers.
187 */
188static int ina2xx_init(struct ina2xx_data *data)
189{
190	struct i2c_client *client = data->client;
191	int ret;
192
193	/* device configuration */
194	ret = i2c_smbus_write_word_swapped(client, INA2XX_CONFIG,
195					   data->curr_config);
196	if (ret < 0)
197		return ret;
198
199	/*
200	 * Set current LSB to 1mA, shunt is in uOhms
201	 * (equation 13 in datasheet).
202	 */
203	return ina2xx_calibrate(data);
204}
205
206static int ina2xx_do_update(struct device *dev)
207{
208	struct ina2xx_data *data = dev_get_drvdata(dev);
209	struct i2c_client *client = data->client;
210	int i, rv, retry;
211
212	dev_dbg(&client->dev, "Starting ina2xx update\n");
213
214	for (retry = 5; retry; retry--) {
215		/* Read all registers */
216		for (i = 0; i < data->config->registers; i++) {
217			rv = i2c_smbus_read_word_swapped(client, i);
218			if (rv < 0)
219				return rv;
220			data->regs[i] = rv;
221		}
222
223		/*
224		 * If the current value in the calibration register is 0, the
225		 * power and current registers will also remain at 0. In case
226		 * the chip has been reset let's check the calibration
227		 * register and reinitialize if needed.
228		 */
229		if (data->regs[INA2XX_CALIBRATION] == 0) {
230			dev_warn(dev, "chip not calibrated, reinitializing\n");
231
232			rv = ina2xx_init(data);
233			if (rv < 0)
234				return rv;
235
236			/*
237			 * Let's make sure the power and current registers
238			 * have been updated before trying again.
239			 */
240			msleep(INA2XX_MAX_DELAY);
241			continue;
242		}
243
244		data->last_updated = jiffies;
245		data->valid = 1;
246
247		return 0;
248	}
249
250	/*
251	 * If we're here then although all write operations succeeded, the
252	 * chip still returns 0 in the calibration register. Nothing more we
253	 * can do here.
254	 */
255	dev_err(dev, "unable to reinitialize the chip\n");
256	return -ENODEV;
257}
258
259static struct ina2xx_data *ina2xx_update_device(struct device *dev)
260{
261	struct ina2xx_data *data = dev_get_drvdata(dev);
262	struct ina2xx_data *ret = data;
263	unsigned long after;
264	int rv;
265
266	mutex_lock(&data->update_lock);
267
268	after = data->last_updated + data->update_interval;
269	if (time_after(jiffies, after) || !data->valid) {
270		rv = ina2xx_do_update(dev);
271		if (rv < 0)
272			ret = ERR_PTR(rv);
273	}
274
275	mutex_unlock(&data->update_lock);
276	return ret;
277}
278
279static int ina2xx_get_value(struct ina2xx_data *data, u8 reg)
280{
281	int val;
282
283	switch (reg) {
284	case INA2XX_SHUNT_VOLTAGE:
285		/* signed register */
286		val = DIV_ROUND_CLOSEST((s16)data->regs[reg],
287					data->config->shunt_div);
288		break;
289	case INA2XX_BUS_VOLTAGE:
290		val = (data->regs[reg] >> data->config->bus_voltage_shift)
291		  * data->config->bus_voltage_lsb;
292		val = DIV_ROUND_CLOSEST(val, 1000);
293		break;
294	case INA2XX_POWER:
295		val = data->regs[reg] * data->config->power_lsb;
296		break;
297	case INA2XX_CURRENT:
298		/* signed register, LSB=1mA (selected), in mA */
299		val = (s16)data->regs[reg];
300		break;
301	case INA2XX_CALIBRATION:
302		val = DIV_ROUND_CLOSEST(data->config->calibration_factor,
303					data->regs[reg]);
304		break;
305	default:
306		/* programmer goofed */
307		WARN_ON_ONCE(1);
308		val = 0;
309		break;
310	}
311
312	return val;
313}
314
315static ssize_t ina2xx_show_value(struct device *dev,
316				 struct device_attribute *da, char *buf)
317{
318	struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
319	struct ina2xx_data *data = ina2xx_update_device(dev);
320
321	if (IS_ERR(data))
322		return PTR_ERR(data);
323
324	return snprintf(buf, PAGE_SIZE, "%d\n",
325			ina2xx_get_value(data, attr->index));
326}
327
328static ssize_t ina2xx_set_shunt(struct device *dev,
329				struct device_attribute *da,
330				const char *buf, size_t count)
331{
332	struct ina2xx_data *data = ina2xx_update_device(dev);
333	unsigned long val;
334	int status;
335
336	if (IS_ERR(data))
337		return PTR_ERR(data);
338
339	status = kstrtoul(buf, 10, &val);
340	if (status < 0)
341		return status;
342
343	if (val == 0 ||
344	    /* Values greater than the calibration factor make no sense. */
345	    val > data->config->calibration_factor)
346		return -EINVAL;
347
348	mutex_lock(&data->update_lock);
349	data->rshunt = val;
350	status = ina2xx_calibrate(data);
351	mutex_unlock(&data->update_lock);
352	if (status < 0)
353		return status;
354
355	return count;
356}
357
358static ssize_t ina226_set_interval(struct device *dev,
359				   struct device_attribute *da,
360				   const char *buf, size_t count)
361{
362	struct ina2xx_data *data = dev_get_drvdata(dev);
363	unsigned long val;
364	int status;
365
366	status = kstrtoul(buf, 10, &val);
367	if (status < 0)
368		return status;
369
370	if (val > INT_MAX || val == 0)
371		return -EINVAL;
372
373	mutex_lock(&data->update_lock);
374	data->curr_config = ina226_interval_to_reg(val,
375						   data->regs[INA2XX_CONFIG]);
376	status = i2c_smbus_write_word_swapped(data->client,
377					      INA2XX_CONFIG,
378					      data->curr_config);
379
380	ina226_set_update_interval(data);
381	/* Make sure the next access re-reads all registers. */
382	data->valid = 0;
383	mutex_unlock(&data->update_lock);
384	if (status < 0)
385		return status;
386
387	return count;
388}
389
390static ssize_t ina226_show_interval(struct device *dev,
391				    struct device_attribute *da, char *buf)
392{
393	struct ina2xx_data *data = ina2xx_update_device(dev);
394
395	if (IS_ERR(data))
396		return PTR_ERR(data);
397
398	/*
399	 * We don't use data->update_interval here as we want to display
400	 * the actual interval used by the chip and jiffies_to_msecs()
401	 * doesn't seem to be accurate enough.
402	 */
403	return snprintf(buf, PAGE_SIZE, "%d\n",
404			ina226_reg_to_interval(data->regs[INA2XX_CONFIG]));
405}
406
407/* shunt voltage */
408static SENSOR_DEVICE_ATTR(in0_input, S_IRUGO, ina2xx_show_value, NULL,
409			  INA2XX_SHUNT_VOLTAGE);
410
411/* bus voltage */
412static SENSOR_DEVICE_ATTR(in1_input, S_IRUGO, ina2xx_show_value, NULL,
413			  INA2XX_BUS_VOLTAGE);
414
415/* calculated current */
416static SENSOR_DEVICE_ATTR(curr1_input, S_IRUGO, ina2xx_show_value, NULL,
417			  INA2XX_CURRENT);
418
419/* calculated power */
420static SENSOR_DEVICE_ATTR(power1_input, S_IRUGO, ina2xx_show_value, NULL,
421			  INA2XX_POWER);
422
423/* shunt resistance */
424static SENSOR_DEVICE_ATTR(shunt_resistor, S_IRUGO | S_IWUSR,
425			  ina2xx_show_value, ina2xx_set_shunt,
426			  INA2XX_CALIBRATION);
427
428/* update interval (ina226 only) */
429static SENSOR_DEVICE_ATTR(update_interval, S_IRUGO | S_IWUSR,
430			  ina226_show_interval, ina226_set_interval, 0);
431
432/* pointers to created device attributes */
433static struct attribute *ina2xx_attrs[] = {
434	&sensor_dev_attr_in0_input.dev_attr.attr,
435	&sensor_dev_attr_in1_input.dev_attr.attr,
436	&sensor_dev_attr_curr1_input.dev_attr.attr,
437	&sensor_dev_attr_power1_input.dev_attr.attr,
438	&sensor_dev_attr_shunt_resistor.dev_attr.attr,
439	NULL,
440};
441
442static const struct attribute_group ina2xx_group = {
443	.attrs = ina2xx_attrs,
444};
445
446static struct attribute *ina226_attrs[] = {
447	&sensor_dev_attr_update_interval.dev_attr.attr,
448	NULL,
449};
450
451static const struct attribute_group ina226_group = {
452	.attrs = ina226_attrs,
453};
454
455static int ina2xx_probe(struct i2c_client *client,
456			const struct i2c_device_id *id)
457{
458	struct i2c_adapter *adapter = client->adapter;
459	struct ina2xx_platform_data *pdata;
460	struct device *dev = &client->dev;
461	struct ina2xx_data *data;
462	struct device *hwmon_dev;
463	u32 val;
464	int ret, group = 0;
465
466	if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA))
467		return -ENODEV;
468
469	data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);
470	if (!data)
471		return -ENOMEM;
472
473	if (dev_get_platdata(dev)) {
474		pdata = dev_get_platdata(dev);
475		data->rshunt = pdata->shunt_uohms;
476	} else if (!of_property_read_u32(dev->of_node,
477					 "shunt-resistor", &val)) {
478		data->rshunt = val;
479	} else {
480		data->rshunt = INA2XX_RSHUNT_DEFAULT;
481	}
482
483	/* set the device type */
484	data->kind = id->driver_data;
485	data->config = &ina2xx_config[data->kind];
486	data->curr_config = data->config->config_default;
487	data->client = client;
488
489	/*
490	 * Ina226 has a variable update_interval. For ina219 we
491	 * use a constant value.
492	 */
493	if (data->kind == ina226)
494		ina226_set_update_interval(data);
495	else
496		data->update_interval = HZ / INA2XX_CONVERSION_RATE;
497
498	if (data->rshunt <= 0 ||
499	    data->rshunt > data->config->calibration_factor)
500		return -ENODEV;
501
502	ret = ina2xx_init(data);
503	if (ret < 0) {
504		dev_err(dev, "error configuring the device: %d\n", ret);
505		return -ENODEV;
506	}
507
508	mutex_init(&data->update_lock);
509
510	data->groups[group++] = &ina2xx_group;
511	if (data->kind == ina226)
512		data->groups[group++] = &ina226_group;
513
514	hwmon_dev = devm_hwmon_device_register_with_groups(dev, client->name,
515							   data, data->groups);
516	if (IS_ERR(hwmon_dev))
517		return PTR_ERR(hwmon_dev);
518
519	dev_info(dev, "power monitor %s (Rshunt = %li uOhm)\n",
520		 id->name, data->rshunt);
521
522	return 0;
523}
524
525static const struct i2c_device_id ina2xx_id[] = {
526	{ "ina219", ina219 },
527	{ "ina220", ina219 },
528	{ "ina226", ina226 },
529	{ "ina230", ina226 },
530	{ "ina231", ina226 },
531	{ }
532};
533MODULE_DEVICE_TABLE(i2c, ina2xx_id);
534
535static struct i2c_driver ina2xx_driver = {
536	.driver = {
537		.name	= "ina2xx",
538	},
539	.probe		= ina2xx_probe,
540	.id_table	= ina2xx_id,
541};
542
543module_i2c_driver(ina2xx_driver);
544
545MODULE_AUTHOR("Lothar Felten <l-felten@ti.com>");
546MODULE_DESCRIPTION("ina2xx driver");
547MODULE_LICENSE("GPL");
548