blob: 707bd69a7353c05c27661ed014b885894c0a9369 [file] [log] [blame]
Marc Titingerc43a1022015-12-07 10:09:34 +01001/*
2 * INA2XX Current and Power Monitors
3 *
4 * Copyright 2015 Baylibre SAS.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 2 as
8 * published by the Free Software Foundation.
9 *
10 * Based on linux/drivers/iio/adc/ad7291.c
11 * Copyright 2010-2011 Analog Devices Inc.
12 *
13 * Based on linux/drivers/hwmon/ina2xx.c
14 * Copyright 2012 Lothar Felten <l-felten@ti.com>
15 *
16 * Licensed under the GPL-2 or later.
17 *
18 * IIO driver for INA219-220-226-230-231
19 *
20 * Configurable 7-bit I2C slave address from 0x40 to 0x4F
21 */
22#include <linux/module.h>
23#include <linux/kthread.h>
24#include <linux/delay.h>
25#include <linux/iio/kfifo_buf.h>
26#include <linux/iio/sysfs.h>
27#include <linux/i2c.h>
28#include <linux/regmap.h>
29#include <linux/platform_data/ina2xx.h>
30
31#include <linux/util_macros.h>
32
33/* INA2XX registers definition */
34#define INA2XX_CONFIG 0x00
35#define INA2XX_SHUNT_VOLTAGE 0x01 /* readonly */
36#define INA2XX_BUS_VOLTAGE 0x02 /* readonly */
37#define INA2XX_POWER 0x03 /* readonly */
38#define INA2XX_CURRENT 0x04 /* readonly */
39#define INA2XX_CALIBRATION 0x05
40
41#define INA226_ALERT_MASK 0x06
42#define INA266_CVRF BIT(3)
43
44#define INA2XX_MAX_REGISTERS 8
45
46/* settings - depend on use case */
47#define INA219_CONFIG_DEFAULT 0x399F /* PGA=8 */
48#define INA226_CONFIG_DEFAULT 0x4327
49#define INA226_DEFAULT_AVG 4
50#define INA226_DEFAULT_IT 1110
51
52#define INA2XX_RSHUNT_DEFAULT 10000
53
54/*
55 * bit mask for reading the averaging setting in the configuration register
56 * FIXME: use regmap_fields.
57 */
58#define INA2XX_MODE_MASK GENMASK(3, 0)
59
60#define INA226_AVG_MASK GENMASK(11, 9)
61#define INA226_SHIFT_AVG(val) ((val) << 9)
62
63/* Integration time for VBus */
64#define INA226_ITB_MASK GENMASK(8, 6)
65#define INA226_SHIFT_ITB(val) ((val) << 6)
66
67/* Integration time for VShunt */
68#define INA226_ITS_MASK GENMASK(5, 3)
69#define INA226_SHIFT_ITS(val) ((val) << 3)
70
71/* Cosmetic macro giving the sampling period for a full P=UxI cycle */
72#define SAMPLING_PERIOD(c) ((c->int_time_vbus + c->int_time_vshunt) \
73 * c->avg)
74
75static bool ina2xx_is_writeable_reg(struct device *dev, unsigned int reg)
76{
77 return (reg == INA2XX_CONFIG) || (reg > INA2XX_CURRENT);
78}
79
80static bool ina2xx_is_volatile_reg(struct device *dev, unsigned int reg)
81{
82 return (reg != INA2XX_CONFIG);
83}
84
85static inline bool is_signed_reg(unsigned int reg)
86{
87 return (reg == INA2XX_SHUNT_VOLTAGE) || (reg == INA2XX_CURRENT);
88}
89
90static const struct regmap_config ina2xx_regmap_config = {
91 .reg_bits = 8,
92 .val_bits = 16,
93 .max_register = INA2XX_MAX_REGISTERS,
94 .writeable_reg = ina2xx_is_writeable_reg,
95 .volatile_reg = ina2xx_is_volatile_reg,
96};
97
98enum ina2xx_ids { ina219, ina226 };
99
100struct ina2xx_config {
101 u16 config_default;
102 int calibration_factor;
103 int shunt_div;
104 int bus_voltage_shift;
105 int bus_voltage_lsb; /* uV */
106 int power_lsb; /* uW */
107};
108
109struct ina2xx_chip_info {
110 struct regmap *regmap;
111 struct task_struct *task;
112 const struct ina2xx_config *config;
113 struct mutex state_lock;
114 long rshunt;
115 int avg;
116 s64 prev_ns; /* track buffer capture time, check for underruns*/
117 int int_time_vbus; /* Bus voltage integration time uS */
118 int int_time_vshunt; /* Shunt voltage integration time uS */
119};
120
121static const struct ina2xx_config ina2xx_config[] = {
122 [ina219] = {
123 .config_default = INA219_CONFIG_DEFAULT,
124 .calibration_factor = 40960000,
125 .shunt_div = 100,
126 .bus_voltage_shift = 3,
127 .bus_voltage_lsb = 4000,
128 .power_lsb = 20000,
129 },
130 [ina226] = {
131 .config_default = INA226_CONFIG_DEFAULT,
132 .calibration_factor = 5120000,
133 .shunt_div = 400,
134 .bus_voltage_shift = 0,
135 .bus_voltage_lsb = 1250,
136 .power_lsb = 25000,
137 },
138};
139
140static int ina2xx_read_raw(struct iio_dev *indio_dev,
141 struct iio_chan_spec const *chan,
142 int *val, int *val2, long mask)
143{
144 int ret;
145 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
146 unsigned int regval;
147
148 switch (mask) {
149 case IIO_CHAN_INFO_RAW:
150 ret = regmap_read(chip->regmap, chan->address, &regval);
151 if (ret < 0)
152 return ret;
153
154 if (is_signed_reg(chan->address))
155 *val = (s16) regval;
156 else
157 *val = regval;
158
159 return IIO_VAL_INT;
160
161 case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
162 *val = chip->avg;
163 return IIO_VAL_INT;
164
165 case IIO_CHAN_INFO_INT_TIME:
166 *val = 0;
167 if (chan->address == INA2XX_SHUNT_VOLTAGE)
168 *val2 = chip->int_time_vshunt;
169 else
170 *val2 = chip->int_time_vbus;
171
172 return IIO_VAL_INT_PLUS_MICRO;
173
174 case IIO_CHAN_INFO_SAMP_FREQ:
175 /*
176 * Sample freq is read only, it is a consequence of
177 * 1/AVG*(CT_bus+CT_shunt).
178 */
179 *val = DIV_ROUND_CLOSEST(1000000, SAMPLING_PERIOD(chip));
180
181 return IIO_VAL_INT;
182
183 case IIO_CHAN_INFO_SCALE:
184 switch (chan->address) {
185 case INA2XX_SHUNT_VOLTAGE:
186 /* processed (mV) = raw*1000/shunt_div */
187 *val2 = chip->config->shunt_div;
188 *val = 1000;
189 return IIO_VAL_FRACTIONAL;
190
191 case INA2XX_BUS_VOLTAGE:
192 /* processed (mV) = raw*lsb (uV) / (1000 << shift) */
193 *val = chip->config->bus_voltage_lsb;
194 *val2 = 1000 << chip->config->bus_voltage_shift;
195 return IIO_VAL_FRACTIONAL;
196
197 case INA2XX_POWER:
198 /* processed (mW) = raw*lsb (uW) / 1000 */
199 *val = chip->config->power_lsb;
200 *val2 = 1000;
201 return IIO_VAL_FRACTIONAL;
202
203 case INA2XX_CURRENT:
204 /* processed (mA) = raw (mA) */
205 *val = 1;
206 return IIO_VAL_INT;
207 }
208 }
209
210 return -EINVAL;
211}
212
213/*
214 * Available averaging rates for ina226. The indices correspond with
215 * the bit values expected by the chip (according to the ina226 datasheet,
216 * table 3 AVG bit settings, found at
217 * http://www.ti.com/lit/ds/symlink/ina226.pdf.
218 */
219static const int ina226_avg_tab[] = { 1, 4, 16, 64, 128, 256, 512, 1024 };
220
221static int ina226_set_average(struct ina2xx_chip_info *chip, unsigned int val,
222 unsigned int *config)
223{
224 int bits;
225
226 if (val > 1024 || val < 1)
227 return -EINVAL;
228
229 bits = find_closest(val, ina226_avg_tab,
230 ARRAY_SIZE(ina226_avg_tab));
231
232 chip->avg = ina226_avg_tab[bits];
233
234 *config &= ~INA226_AVG_MASK;
235 *config |= INA226_SHIFT_AVG(bits) & INA226_AVG_MASK;
236
237 return 0;
238}
239
240/* Conversion times in uS */
241static const int ina226_conv_time_tab[] = { 140, 204, 332, 588, 1100,
242 2116, 4156, 8244 };
243
244static int ina226_set_int_time_vbus(struct ina2xx_chip_info *chip,
245 unsigned int val_us, unsigned int *config)
246{
247 int bits;
248
249 if (val_us > 8244 || val_us < 140)
250 return -EINVAL;
251
252 bits = find_closest(val_us, ina226_conv_time_tab,
253 ARRAY_SIZE(ina226_conv_time_tab));
254
255 chip->int_time_vbus = ina226_conv_time_tab[bits];
256
257 *config &= ~INA226_ITB_MASK;
258 *config |= INA226_SHIFT_ITB(bits) & INA226_ITB_MASK;
259
260 return 0;
261}
262
263static int ina226_set_int_time_vshunt(struct ina2xx_chip_info *chip,
264 unsigned int val_us, unsigned int *config)
265{
266 int bits;
267
268 if (val_us > 8244 || val_us < 140)
269 return -EINVAL;
270
271 bits = find_closest(val_us, ina226_conv_time_tab,
272 ARRAY_SIZE(ina226_conv_time_tab));
273
274 chip->int_time_vshunt = ina226_conv_time_tab[bits];
275
276 *config &= ~INA226_ITS_MASK;
277 *config |= INA226_SHIFT_ITS(bits) & INA226_ITS_MASK;
278
279 return 0;
280}
281
282static int ina2xx_write_raw(struct iio_dev *indio_dev,
283 struct iio_chan_spec const *chan,
284 int val, int val2, long mask)
285{
286 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
287 int ret;
288 unsigned int config, tmp;
289
290 if (iio_buffer_enabled(indio_dev))
291 return -EBUSY;
292
293 mutex_lock(&chip->state_lock);
294
295 ret = regmap_read(chip->regmap, INA2XX_CONFIG, &config);
296 if (ret < 0)
297 goto _err;
298
299 tmp = config;
300
301 switch (mask) {
302 case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
303 ret = ina226_set_average(chip, val, &tmp);
304 break;
305
306 case IIO_CHAN_INFO_INT_TIME:
307 if (chan->address == INA2XX_SHUNT_VOLTAGE)
308 ret = ina226_set_int_time_vshunt(chip, val2, &tmp);
309 else
310 ret = ina226_set_int_time_vbus(chip, val2, &tmp);
311 break;
312 default:
313 ret = -EINVAL;
314 }
315
316 if (!ret && (tmp != config))
317 ret = regmap_write(chip->regmap, INA2XX_CONFIG, tmp);
318_err:
319 mutex_unlock(&chip->state_lock);
320
321 return ret;
322}
323
324
325#define INA2XX_CHAN(_type, _index, _address) { \
326 .type = (_type), \
327 .address = (_address), \
328 .indexed = 1, \
329 .channel = (_index), \
330 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) \
331 | BIT(IIO_CHAN_INFO_SCALE), \
332 .info_mask_shared_by_dir = BIT(IIO_CHAN_INFO_SAMP_FREQ) | \
333 BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), \
334 .scan_index = (_index), \
335 .scan_type = { \
336 .sign = 'u', \
337 .realbits = 16, \
338 .storagebits = 16, \
339 .endianness = IIO_LE, \
340 } \
341}
342
343/*
344 * Sampling Freq is a consequence of the integration times of
345 * the Voltage channels.
346 */
347#define INA2XX_CHAN_VOLTAGE(_index, _address) { \
348 .type = IIO_VOLTAGE, \
349 .address = (_address), \
350 .indexed = 1, \
351 .channel = (_index), \
352 .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
353 BIT(IIO_CHAN_INFO_SCALE) | \
354 BIT(IIO_CHAN_INFO_INT_TIME), \
355 .scan_index = (_index), \
356 .scan_type = { \
357 .sign = 'u', \
358 .realbits = 16, \
359 .storagebits = 16, \
360 .endianness = IIO_LE, \
361 } \
362}
363
364static const struct iio_chan_spec ina2xx_channels[] = {
365 INA2XX_CHAN_VOLTAGE(0, INA2XX_SHUNT_VOLTAGE),
366 INA2XX_CHAN_VOLTAGE(1, INA2XX_BUS_VOLTAGE),
367 INA2XX_CHAN(IIO_CURRENT, 2, INA2XX_CURRENT),
368 INA2XX_CHAN(IIO_POWER, 3, INA2XX_POWER),
369 IIO_CHAN_SOFT_TIMESTAMP(4),
370};
371
372static int ina2xx_work_buffer(struct iio_dev *indio_dev)
373{
374 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
375 unsigned short data[8];
376 int bit, ret, i = 0;
377 unsigned long buffer_us, elapsed_us;
378 s64 time_a, time_b;
379 unsigned int alert;
380
381 time_a = iio_get_time_ns();
382
383 /*
384 * Because the timer thread and the chip conversion clock
385 * are asynchronous, the period difference will eventually
386 * result in reading V[k-1] again, or skip V[k] at time Tk.
387 * In order to resync the timer with the conversion process
388 * we check the ConVersionReadyFlag.
389 * On hardware that supports using the ALERT pin to toggle a
390 * GPIO a triggered buffer could be used instead.
391 * For now, we pay for that extra read of the ALERT register
392 */
393 do {
394 ret = regmap_read(chip->regmap, INA226_ALERT_MASK,
395 &alert);
396 if (ret < 0)
397 return ret;
398
399 alert &= INA266_CVRF;
400 trace_printk("Conversion ready: %d\n", !!alert);
401
402 } while (!alert);
403
404 /*
405 * Single register reads: bulk_read will not work with ina226
406 * as there is no auto-increment of the address register for
407 * data length longer than 16bits.
408 */
409 for_each_set_bit(bit, indio_dev->active_scan_mask,
410 indio_dev->masklength) {
411 unsigned int val;
412
413 ret = regmap_read(chip->regmap,
414 INA2XX_SHUNT_VOLTAGE + bit, &val);
415 if (ret < 0)
416 return ret;
417
418 data[i++] = val;
419 }
420
421 time_b = iio_get_time_ns();
422
423 iio_push_to_buffers_with_timestamp(indio_dev,
424 (unsigned int *)data, time_a);
425
426 buffer_us = (unsigned long)(time_b - time_a) / 1000;
427 elapsed_us = (unsigned long)(time_a - chip->prev_ns) / 1000;
428
429 trace_printk("uS: elapsed: %lu, buf: %lu\n", elapsed_us, buffer_us);
430
431 chip->prev_ns = time_a;
432
433 return buffer_us;
434};
435
436static int ina2xx_capture_thread(void *data)
437{
438 struct iio_dev *indio_dev = (struct iio_dev *)data;
439 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
440 unsigned int sampling_us = SAMPLING_PERIOD(chip);
441 int buffer_us;
442
443 /*
444 * Poll a bit faster than the chip internal Fs, in case
445 * we wish to sync with the conversion ready flag.
446 */
447 sampling_us -= 200;
448
449 do {
450 buffer_us = ina2xx_work_buffer(indio_dev);
451 if (buffer_us < 0)
452 return buffer_us;
453
454 if (sampling_us > buffer_us)
455 udelay(sampling_us - buffer_us);
456
457 } while (!kthread_should_stop());
458
459 return 0;
460}
461
462static int ina2xx_buffer_enable(struct iio_dev *indio_dev)
463{
464 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
465 unsigned int sampling_us = SAMPLING_PERIOD(chip);
466
467 trace_printk("Enabling buffer w/ scan_mask %02x, freq = %d, avg =%u\n",
468 (unsigned int)(*indio_dev->active_scan_mask),
469 1000000/sampling_us, chip->avg);
470
471 trace_printk("Expected work period: %u us\n", sampling_us);
472
473 chip->prev_ns = iio_get_time_ns();
474
475 chip->task = kthread_run(ina2xx_capture_thread, (void *)indio_dev,
476 "ina2xx-%uus", sampling_us);
477
478 return PTR_ERR_OR_ZERO(chip->task);
479}
480
481static int ina2xx_buffer_disable(struct iio_dev *indio_dev)
482{
483 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
484
485 if (chip->task) {
486 kthread_stop(chip->task);
487 chip->task = NULL;
488 }
489
490 return 0;
491}
492
493static const struct iio_buffer_setup_ops ina2xx_setup_ops = {
494 .postenable = &ina2xx_buffer_enable,
495 .predisable = &ina2xx_buffer_disable,
496};
497
498static int ina2xx_debug_reg(struct iio_dev *indio_dev,
499 unsigned reg, unsigned writeval, unsigned *readval)
500{
501 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
502
503 if (!readval)
504 return regmap_write(chip->regmap, reg, writeval);
505
506 return regmap_read(chip->regmap, reg, readval);
507}
508
509/* Possible integration times for vshunt and vbus */
510static IIO_CONST_ATTR_INT_TIME_AVAIL \
511 ("0.000140 0.000204 0.000332 0.000588 0.001100 0.002116 0.004156 0.008244");
512
513static struct attribute *ina2xx_attributes[] = {
514 &iio_const_attr_integration_time_available.dev_attr.attr,
515 NULL,
516};
517
518static const struct attribute_group ina2xx_attribute_group = {
519 .attrs = ina2xx_attributes,
520};
521
522static const struct iio_info ina2xx_info = {
523 .debugfs_reg_access = &ina2xx_debug_reg,
524 .read_raw = &ina2xx_read_raw,
525 .write_raw = &ina2xx_write_raw,
526 .attrs = &ina2xx_attribute_group,
527 .driver_module = THIS_MODULE,
528};
529
530/* Initialize the configuration and calibration registers. */
531static int ina2xx_init(struct ina2xx_chip_info *chip, unsigned int config)
532{
533 u16 regval;
534 int ret = regmap_write(chip->regmap, INA2XX_CONFIG, config);
535
536 if (ret < 0)
537 return ret;
538 /*
539 * Set current LSB to 1mA, shunt is in uOhms
540 * (equation 13 in datasheet). We hardcode a Current_LSB
541 * of 1.0 x10-6. The only remaining parameter is RShunt.
542 * There is no need to expose the CALIBRATION register
543 * to the user for now.
544 */
545 regval = DIV_ROUND_CLOSEST(chip->config->calibration_factor,
546 chip->rshunt);
547
548 return regmap_write(chip->regmap, INA2XX_CALIBRATION, regval);
549}
550
551static int ina2xx_probe(struct i2c_client *client,
552 const struct i2c_device_id *id)
553{
554 struct ina2xx_chip_info *chip;
555 struct iio_dev *indio_dev;
556 struct iio_buffer *buffer;
557 int ret;
558 unsigned int val;
559
560 indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*chip));
561 if (!indio_dev)
562 return -ENOMEM;
563
564 chip = iio_priv(indio_dev);
565
566 chip->config = &ina2xx_config[id->driver_data];
567
568 if (of_property_read_u32(client->dev.of_node,
569 "shunt-resistor", &val) < 0) {
570 struct ina2xx_platform_data *pdata =
571 dev_get_platdata(&client->dev);
572
573 if (pdata)
574 val = pdata->shunt_uohms;
575 else
576 val = INA2XX_RSHUNT_DEFAULT;
577 }
578
579 if (val <= 0 || val > chip->config->calibration_factor)
580 return -ENODEV;
581
582 chip->rshunt = val;
583
584 mutex_init(&chip->state_lock);
585
586 /* This is only used for device removal purposes. */
587 i2c_set_clientdata(client, indio_dev);
588
589 indio_dev->name = id->name;
590 indio_dev->channels = ina2xx_channels;
591 indio_dev->num_channels = ARRAY_SIZE(ina2xx_channels);
592
593 indio_dev->dev.parent = &client->dev;
594 indio_dev->info = &ina2xx_info;
595 indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
596
597 chip->regmap = devm_regmap_init_i2c(client, &ina2xx_regmap_config);
598 if (IS_ERR(chip->regmap)) {
599 dev_err(&client->dev, "failed to allocate register map\n");
600 return PTR_ERR(chip->regmap);
601 }
602
603 /* Patch the current config register with default. */
604 val = chip->config->config_default;
605
606 if (id->driver_data == ina226) {
607 ina226_set_average(chip, INA226_DEFAULT_AVG, &val);
608 ina226_set_int_time_vbus(chip, INA226_DEFAULT_IT, &val);
609 ina226_set_int_time_vshunt(chip, INA226_DEFAULT_IT, &val);
610 }
611
612 ret = ina2xx_init(chip, val);
613 if (ret < 0) {
614 dev_err(&client->dev, "error configuring the device: %d\n",
615 ret);
616 return -ENODEV;
617 }
618
619 buffer = devm_iio_kfifo_allocate(&indio_dev->dev);
620 if (!buffer)
621 return -ENOMEM;
622
623 indio_dev->setup_ops = &ina2xx_setup_ops;
624
625 iio_device_attach_buffer(indio_dev, buffer);
626
627 return iio_device_register(indio_dev);
628}
629
630
631static int ina2xx_remove(struct i2c_client *client)
632{
633 struct iio_dev *indio_dev = i2c_get_clientdata(client);
634 struct ina2xx_chip_info *chip = iio_priv(indio_dev);
635
636 iio_device_unregister(indio_dev);
637
638 /* Powerdown */
639 return regmap_update_bits(chip->regmap, INA2XX_CONFIG,
640 INA2XX_MODE_MASK, 0);
641}
642
643
644static const struct i2c_device_id ina2xx_id[] = {
645 {"ina219", ina219},
646 {"ina220", ina219},
647 {"ina226", ina226},
648 {"ina230", ina226},
649 {"ina231", ina226},
650 {}
651};
652
653MODULE_DEVICE_TABLE(i2c, ina2xx_id);
654
655static struct i2c_driver ina2xx_driver = {
656 .driver = {
657 .name = KBUILD_MODNAME,
658 },
659 .probe = ina2xx_probe,
660 .remove = ina2xx_remove,
661 .id_table = ina2xx_id,
662};
663
664module_i2c_driver(ina2xx_driver);
665
666MODULE_AUTHOR("Marc Titinger <marc.titinger@baylibre.com>");
667MODULE_DESCRIPTION("Texas Instruments INA2XX ADC driver");
668MODULE_LICENSE("GPL v2");