xref: /openbmc/linux/drivers/iio/adc/ti-ads1015.c (revision 6f2bde9b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * ADS1015 - Texas Instruments Analog-to-Digital Converter
4  *
5  * Copyright (c) 2016, Intel Corporation.
6  *
7  * IIO driver for ADS1015 ADC 7-bit I2C slave address:
8  *	* 0x48 - ADDR connected to Ground
9  *	* 0x49 - ADDR connected to Vdd
10  *	* 0x4A - ADDR connected to SDA
11  *	* 0x4B - ADDR connected to SCL
12  */
13 
14 #include <linux/module.h>
15 #include <linux/init.h>
16 #include <linux/irq.h>
17 #include <linux/i2c.h>
18 #include <linux/property.h>
19 #include <linux/regmap.h>
20 #include <linux/pm_runtime.h>
21 #include <linux/mutex.h>
22 #include <linux/delay.h>
23 
24 #include <linux/iio/iio.h>
25 #include <linux/iio/types.h>
26 #include <linux/iio/sysfs.h>
27 #include <linux/iio/events.h>
28 #include <linux/iio/buffer.h>
29 #include <linux/iio/triggered_buffer.h>
30 #include <linux/iio/trigger_consumer.h>
31 
32 #define ADS1015_DRV_NAME "ads1015"
33 
34 #define ADS1015_CHANNELS 8
35 
36 #define ADS1015_CONV_REG	0x00
37 #define ADS1015_CFG_REG		0x01
38 #define ADS1015_LO_THRESH_REG	0x02
39 #define ADS1015_HI_THRESH_REG	0x03
40 
41 #define ADS1015_CFG_COMP_QUE_SHIFT	0
42 #define ADS1015_CFG_COMP_LAT_SHIFT	2
43 #define ADS1015_CFG_COMP_POL_SHIFT	3
44 #define ADS1015_CFG_COMP_MODE_SHIFT	4
45 #define ADS1015_CFG_DR_SHIFT	5
46 #define ADS1015_CFG_MOD_SHIFT	8
47 #define ADS1015_CFG_PGA_SHIFT	9
48 #define ADS1015_CFG_MUX_SHIFT	12
49 
50 #define ADS1015_CFG_COMP_QUE_MASK	GENMASK(1, 0)
51 #define ADS1015_CFG_COMP_LAT_MASK	BIT(2)
52 #define ADS1015_CFG_COMP_POL_MASK	BIT(3)
53 #define ADS1015_CFG_COMP_MODE_MASK	BIT(4)
54 #define ADS1015_CFG_DR_MASK	GENMASK(7, 5)
55 #define ADS1015_CFG_MOD_MASK	BIT(8)
56 #define ADS1015_CFG_PGA_MASK	GENMASK(11, 9)
57 #define ADS1015_CFG_MUX_MASK	GENMASK(14, 12)
58 
59 /* Comparator queue and disable field */
60 #define ADS1015_CFG_COMP_DISABLE	3
61 
62 /* Comparator polarity field */
63 #define ADS1015_CFG_COMP_POL_LOW	0
64 #define ADS1015_CFG_COMP_POL_HIGH	1
65 
66 /* Comparator mode field */
67 #define ADS1015_CFG_COMP_MODE_TRAD	0
68 #define ADS1015_CFG_COMP_MODE_WINDOW	1
69 
70 /* device operating modes */
71 #define ADS1015_CONTINUOUS	0
72 #define ADS1015_SINGLESHOT	1
73 
74 #define ADS1015_SLEEP_DELAY_MS		2000
75 #define ADS1015_DEFAULT_PGA		2
76 #define ADS1015_DEFAULT_DATA_RATE	4
77 #define ADS1015_DEFAULT_CHAN		0
78 
79 struct ads1015_chip_data {
80 	struct iio_chan_spec const	*channels;
81 	int				num_channels;
82 	const struct iio_info		*info;
83 	const int			*data_rate;
84 	const int			data_rate_len;
85 	const int			*scale;
86 	const int			scale_len;
87 	bool				has_comparator;
88 };
89 
90 enum ads1015_channels {
91 	ADS1015_AIN0_AIN1 = 0,
92 	ADS1015_AIN0_AIN3,
93 	ADS1015_AIN1_AIN3,
94 	ADS1015_AIN2_AIN3,
95 	ADS1015_AIN0,
96 	ADS1015_AIN1,
97 	ADS1015_AIN2,
98 	ADS1015_AIN3,
99 	ADS1015_TIMESTAMP,
100 };
101 
102 static const int ads1015_data_rate[] = {
103 	128, 250, 490, 920, 1600, 2400, 3300, 3300
104 };
105 
106 static const int ads1115_data_rate[] = {
107 	8, 16, 32, 64, 128, 250, 475, 860
108 };
109 
110 /*
111  * Translation from PGA bits to full-scale positive and negative input voltage
112  * range in mV
113  */
114 static const int ads1015_fullscale_range[] = {
115 	6144, 4096, 2048, 1024, 512, 256, 256, 256
116 };
117 
118 static const int ads1015_scale[] = {	/* 12bit ADC */
119 	256, 11,
120 	512, 11,
121 	1024, 11,
122 	2048, 11,
123 	4096, 11,
124 	6144, 11
125 };
126 
127 static const int ads1115_scale[] = {	/* 16bit ADC */
128 	256, 15,
129 	512, 15,
130 	1024, 15,
131 	2048, 15,
132 	4096, 15,
133 	6144, 15
134 };
135 
136 /*
137  * Translation from COMP_QUE field value to the number of successive readings
138  * exceed the threshold values before an interrupt is generated
139  */
140 static const int ads1015_comp_queue[] = { 1, 2, 4 };
141 
142 static const struct iio_event_spec ads1015_events[] = {
143 	{
144 		.type = IIO_EV_TYPE_THRESH,
145 		.dir = IIO_EV_DIR_RISING,
146 		.mask_separate = BIT(IIO_EV_INFO_VALUE) |
147 				BIT(IIO_EV_INFO_ENABLE),
148 	}, {
149 		.type = IIO_EV_TYPE_THRESH,
150 		.dir = IIO_EV_DIR_FALLING,
151 		.mask_separate = BIT(IIO_EV_INFO_VALUE),
152 	}, {
153 		.type = IIO_EV_TYPE_THRESH,
154 		.dir = IIO_EV_DIR_EITHER,
155 		.mask_separate = BIT(IIO_EV_INFO_ENABLE) |
156 				BIT(IIO_EV_INFO_PERIOD),
157 	},
158 };
159 
160 /*
161  * Compile-time check whether _fitbits can accommodate up to _testbits
162  * bits. Returns _fitbits on success, fails to compile otherwise.
163  *
164  * The test works such that it multiplies constant _fitbits by constant
165  * double-negation of size of a non-empty structure, i.e. it multiplies
166  * constant _fitbits by constant 1 in each successful compilation case.
167  * The non-empty structure may contain C11 _Static_assert(), make use of
168  * this and place the kernel variant of static assert in there, so that
169  * it performs the compile-time check for _testbits <= _fitbits. Note
170  * that it is not possible to directly use static_assert in compound
171  * statements, hence this convoluted construct.
172  */
173 #define FIT_CHECK(_testbits, _fitbits)					\
174 	(								\
175 		(_fitbits) *						\
176 		!!sizeof(struct {					\
177 			static_assert((_testbits) <= (_fitbits));	\
178 			int pad;					\
179 		})							\
180 	)
181 
182 #define ADS1015_V_CHAN(_chan, _addr, _realbits, _shift, _event_spec, _num_event_specs) { \
183 	.type = IIO_VOLTAGE,					\
184 	.indexed = 1,						\
185 	.address = _addr,					\
186 	.channel = _chan,					\
187 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |		\
188 				BIT(IIO_CHAN_INFO_SCALE) |	\
189 				BIT(IIO_CHAN_INFO_SAMP_FREQ),	\
190 	.info_mask_shared_by_all_available =			\
191 				BIT(IIO_CHAN_INFO_SCALE) |	\
192 				BIT(IIO_CHAN_INFO_SAMP_FREQ),	\
193 	.scan_index = _addr,					\
194 	.scan_type = {						\
195 		.sign = 's',					\
196 		.realbits = (_realbits),			\
197 		.storagebits = FIT_CHECK((_realbits) + (_shift), 16),	\
198 		.shift = (_shift),				\
199 		.endianness = IIO_CPU,				\
200 	},							\
201 	.event_spec = (_event_spec),				\
202 	.num_event_specs = (_num_event_specs),			\
203 	.datasheet_name = "AIN"#_chan,				\
204 }
205 
206 #define ADS1015_V_DIFF_CHAN(_chan, _chan2, _addr, _realbits, _shift, _event_spec, _num_event_specs) { \
207 	.type = IIO_VOLTAGE,					\
208 	.differential = 1,					\
209 	.indexed = 1,						\
210 	.address = _addr,					\
211 	.channel = _chan,					\
212 	.channel2 = _chan2,					\
213 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |		\
214 				BIT(IIO_CHAN_INFO_SCALE) |	\
215 				BIT(IIO_CHAN_INFO_SAMP_FREQ),	\
216 	.info_mask_shared_by_all_available =			\
217 				BIT(IIO_CHAN_INFO_SCALE) |	\
218 				BIT(IIO_CHAN_INFO_SAMP_FREQ),	\
219 	.scan_index = _addr,					\
220 	.scan_type = {						\
221 		.sign = 's',					\
222 		.realbits = (_realbits),			\
223 		.storagebits = FIT_CHECK((_realbits) + (_shift), 16),	\
224 		.shift = (_shift),				\
225 		.endianness = IIO_CPU,				\
226 	},							\
227 	.event_spec = (_event_spec),				\
228 	.num_event_specs = (_num_event_specs),			\
229 	.datasheet_name = "AIN"#_chan"-AIN"#_chan2,		\
230 }
231 
232 struct ads1015_channel_data {
233 	bool enabled;
234 	unsigned int pga;
235 	unsigned int data_rate;
236 };
237 
238 struct ads1015_thresh_data {
239 	unsigned int comp_queue;
240 	int high_thresh;
241 	int low_thresh;
242 };
243 
244 struct ads1015_data {
245 	struct regmap *regmap;
246 	/*
247 	 * Protects ADC ops, e.g: concurrent sysfs/buffered
248 	 * data reads, configuration updates
249 	 */
250 	struct mutex lock;
251 	struct ads1015_channel_data channel_data[ADS1015_CHANNELS];
252 
253 	unsigned int event_channel;
254 	unsigned int comp_mode;
255 	struct ads1015_thresh_data thresh_data[ADS1015_CHANNELS];
256 
257 	const struct ads1015_chip_data *chip;
258 	/*
259 	 * Set to true when the ADC is switched to the continuous-conversion
260 	 * mode and exits from a power-down state.  This flag is used to avoid
261 	 * getting the stale result from the conversion register.
262 	 */
263 	bool conv_invalid;
264 };
265 
266 static bool ads1015_event_channel_enabled(struct ads1015_data *data)
267 {
268 	return (data->event_channel != ADS1015_CHANNELS);
269 }
270 
271 static void ads1015_event_channel_enable(struct ads1015_data *data, int chan,
272 					 int comp_mode)
273 {
274 	WARN_ON(ads1015_event_channel_enabled(data));
275 
276 	data->event_channel = chan;
277 	data->comp_mode = comp_mode;
278 }
279 
280 static void ads1015_event_channel_disable(struct ads1015_data *data, int chan)
281 {
282 	data->event_channel = ADS1015_CHANNELS;
283 }
284 
285 static const struct regmap_range ads1015_writeable_ranges[] = {
286 	regmap_reg_range(ADS1015_CFG_REG, ADS1015_HI_THRESH_REG),
287 };
288 
289 static const struct regmap_access_table ads1015_writeable_table = {
290 	.yes_ranges = ads1015_writeable_ranges,
291 	.n_yes_ranges = ARRAY_SIZE(ads1015_writeable_ranges),
292 };
293 
294 static const struct regmap_config ads1015_regmap_config = {
295 	.reg_bits = 8,
296 	.val_bits = 16,
297 	.max_register = ADS1015_HI_THRESH_REG,
298 	.wr_table = &ads1015_writeable_table,
299 };
300 
301 static const struct regmap_range tla2024_writeable_ranges[] = {
302 	regmap_reg_range(ADS1015_CFG_REG, ADS1015_CFG_REG),
303 };
304 
305 static const struct regmap_access_table tla2024_writeable_table = {
306 	.yes_ranges = tla2024_writeable_ranges,
307 	.n_yes_ranges = ARRAY_SIZE(tla2024_writeable_ranges),
308 };
309 
310 static const struct regmap_config tla2024_regmap_config = {
311 	.reg_bits = 8,
312 	.val_bits = 16,
313 	.max_register = ADS1015_CFG_REG,
314 	.wr_table = &tla2024_writeable_table,
315 };
316 
317 static const struct iio_chan_spec ads1015_channels[] = {
318 	ADS1015_V_DIFF_CHAN(0, 1, ADS1015_AIN0_AIN1, 12, 4,
319 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
320 	ADS1015_V_DIFF_CHAN(0, 3, ADS1015_AIN0_AIN3, 12, 4,
321 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
322 	ADS1015_V_DIFF_CHAN(1, 3, ADS1015_AIN1_AIN3, 12, 4,
323 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
324 	ADS1015_V_DIFF_CHAN(2, 3, ADS1015_AIN2_AIN3, 12, 4,
325 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
326 	ADS1015_V_CHAN(0, ADS1015_AIN0, 12, 4,
327 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
328 	ADS1015_V_CHAN(1, ADS1015_AIN1, 12, 4,
329 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
330 	ADS1015_V_CHAN(2, ADS1015_AIN2, 12, 4,
331 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
332 	ADS1015_V_CHAN(3, ADS1015_AIN3, 12, 4,
333 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
334 	IIO_CHAN_SOFT_TIMESTAMP(ADS1015_TIMESTAMP),
335 };
336 
337 static const struct iio_chan_spec ads1115_channels[] = {
338 	ADS1015_V_DIFF_CHAN(0, 1, ADS1015_AIN0_AIN1, 16, 0,
339 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
340 	ADS1015_V_DIFF_CHAN(0, 3, ADS1015_AIN0_AIN3, 16, 0,
341 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
342 	ADS1015_V_DIFF_CHAN(1, 3, ADS1015_AIN1_AIN3, 16, 0,
343 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
344 	ADS1015_V_DIFF_CHAN(2, 3, ADS1015_AIN2_AIN3, 16, 0,
345 			    ads1015_events, ARRAY_SIZE(ads1015_events)),
346 	ADS1015_V_CHAN(0, ADS1015_AIN0, 16, 0,
347 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
348 	ADS1015_V_CHAN(1, ADS1015_AIN1, 16, 0,
349 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
350 	ADS1015_V_CHAN(2, ADS1015_AIN2, 16, 0,
351 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
352 	ADS1015_V_CHAN(3, ADS1015_AIN3, 16, 0,
353 		       ads1015_events, ARRAY_SIZE(ads1015_events)),
354 	IIO_CHAN_SOFT_TIMESTAMP(ADS1015_TIMESTAMP),
355 };
356 
357 static const struct iio_chan_spec tla2024_channels[] = {
358 	ADS1015_V_DIFF_CHAN(0, 1, ADS1015_AIN0_AIN1, 12, 4, NULL, 0),
359 	ADS1015_V_DIFF_CHAN(0, 3, ADS1015_AIN0_AIN3, 12, 4, NULL, 0),
360 	ADS1015_V_DIFF_CHAN(1, 3, ADS1015_AIN1_AIN3, 12, 4, NULL, 0),
361 	ADS1015_V_DIFF_CHAN(2, 3, ADS1015_AIN2_AIN3, 12, 4, NULL, 0),
362 	ADS1015_V_CHAN(0, ADS1015_AIN0, 12, 4, NULL, 0),
363 	ADS1015_V_CHAN(1, ADS1015_AIN1, 12, 4, NULL, 0),
364 	ADS1015_V_CHAN(2, ADS1015_AIN2, 12, 4, NULL, 0),
365 	ADS1015_V_CHAN(3, ADS1015_AIN3, 12, 4, NULL, 0),
366 	IIO_CHAN_SOFT_TIMESTAMP(ADS1015_TIMESTAMP),
367 };
368 
369 
370 #ifdef CONFIG_PM
371 static int ads1015_set_power_state(struct ads1015_data *data, bool on)
372 {
373 	int ret;
374 	struct device *dev = regmap_get_device(data->regmap);
375 
376 	if (on) {
377 		ret = pm_runtime_resume_and_get(dev);
378 	} else {
379 		pm_runtime_mark_last_busy(dev);
380 		ret = pm_runtime_put_autosuspend(dev);
381 	}
382 
383 	return ret < 0 ? ret : 0;
384 }
385 
386 #else /* !CONFIG_PM */
387 
388 static int ads1015_set_power_state(struct ads1015_data *data, bool on)
389 {
390 	return 0;
391 }
392 
393 #endif /* !CONFIG_PM */
394 
395 static
396 int ads1015_get_adc_result(struct ads1015_data *data, int chan, int *val)
397 {
398 	const int *data_rate = data->chip->data_rate;
399 	int ret, pga, dr, dr_old, conv_time;
400 	unsigned int old, mask, cfg;
401 
402 	if (chan < 0 || chan >= ADS1015_CHANNELS)
403 		return -EINVAL;
404 
405 	ret = regmap_read(data->regmap, ADS1015_CFG_REG, &old);
406 	if (ret)
407 		return ret;
408 
409 	pga = data->channel_data[chan].pga;
410 	dr = data->channel_data[chan].data_rate;
411 	mask = ADS1015_CFG_MUX_MASK | ADS1015_CFG_PGA_MASK |
412 		ADS1015_CFG_DR_MASK;
413 	cfg = chan << ADS1015_CFG_MUX_SHIFT | pga << ADS1015_CFG_PGA_SHIFT |
414 		dr << ADS1015_CFG_DR_SHIFT;
415 
416 	if (ads1015_event_channel_enabled(data)) {
417 		mask |= ADS1015_CFG_COMP_QUE_MASK | ADS1015_CFG_COMP_MODE_MASK;
418 		cfg |= data->thresh_data[chan].comp_queue <<
419 				ADS1015_CFG_COMP_QUE_SHIFT |
420 			data->comp_mode <<
421 				ADS1015_CFG_COMP_MODE_SHIFT;
422 	}
423 
424 	cfg = (old & ~mask) | (cfg & mask);
425 	if (old != cfg) {
426 		ret = regmap_write(data->regmap, ADS1015_CFG_REG, cfg);
427 		if (ret)
428 			return ret;
429 		data->conv_invalid = true;
430 	}
431 	if (data->conv_invalid) {
432 		dr_old = (old & ADS1015_CFG_DR_MASK) >> ADS1015_CFG_DR_SHIFT;
433 		conv_time = DIV_ROUND_UP(USEC_PER_SEC, data_rate[dr_old]);
434 		conv_time += DIV_ROUND_UP(USEC_PER_SEC, data_rate[dr]);
435 		conv_time += conv_time / 10; /* 10% internal clock inaccuracy */
436 		usleep_range(conv_time, conv_time + 1);
437 		data->conv_invalid = false;
438 	}
439 
440 	return regmap_read(data->regmap, ADS1015_CONV_REG, val);
441 }
442 
443 static irqreturn_t ads1015_trigger_handler(int irq, void *p)
444 {
445 	struct iio_poll_func *pf = p;
446 	struct iio_dev *indio_dev = pf->indio_dev;
447 	struct ads1015_data *data = iio_priv(indio_dev);
448 	/* Ensure natural alignment of timestamp */
449 	struct {
450 		s16 chan;
451 		s64 timestamp __aligned(8);
452 	} scan;
453 	int chan, ret, res;
454 
455 	memset(&scan, 0, sizeof(scan));
456 
457 	mutex_lock(&data->lock);
458 	chan = find_first_bit(indio_dev->active_scan_mask,
459 			      indio_dev->masklength);
460 	ret = ads1015_get_adc_result(data, chan, &res);
461 	if (ret < 0) {
462 		mutex_unlock(&data->lock);
463 		goto err;
464 	}
465 
466 	scan.chan = res;
467 	mutex_unlock(&data->lock);
468 
469 	iio_push_to_buffers_with_timestamp(indio_dev, &scan,
470 					   iio_get_time_ns(indio_dev));
471 
472 err:
473 	iio_trigger_notify_done(indio_dev->trig);
474 
475 	return IRQ_HANDLED;
476 }
477 
478 static int ads1015_set_scale(struct ads1015_data *data,
479 			     struct iio_chan_spec const *chan,
480 			     int scale, int uscale)
481 {
482 	int i;
483 	int fullscale = div_s64((scale * 1000000LL + uscale) <<
484 				(chan->scan_type.realbits - 1), 1000000);
485 
486 	for (i = 0; i < ARRAY_SIZE(ads1015_fullscale_range); i++) {
487 		if (ads1015_fullscale_range[i] == fullscale) {
488 			data->channel_data[chan->address].pga = i;
489 			return 0;
490 		}
491 	}
492 
493 	return -EINVAL;
494 }
495 
496 static int ads1015_set_data_rate(struct ads1015_data *data, int chan, int rate)
497 {
498 	int i;
499 
500 	for (i = 0; i < data->chip->data_rate_len; i++) {
501 		if (data->chip->data_rate[i] == rate) {
502 			data->channel_data[chan].data_rate = i;
503 			return 0;
504 		}
505 	}
506 
507 	return -EINVAL;
508 }
509 
510 static int ads1015_read_avail(struct iio_dev *indio_dev,
511 			      struct iio_chan_spec const *chan,
512 			      const int **vals, int *type, int *length,
513 			      long mask)
514 {
515 	struct ads1015_data *data = iio_priv(indio_dev);
516 
517 	if (chan->type != IIO_VOLTAGE)
518 		return -EINVAL;
519 
520 	switch (mask) {
521 	case IIO_CHAN_INFO_SCALE:
522 		*type = IIO_VAL_FRACTIONAL_LOG2;
523 		*vals =  data->chip->scale;
524 		*length = data->chip->scale_len;
525 		return IIO_AVAIL_LIST;
526 	case IIO_CHAN_INFO_SAMP_FREQ:
527 		*type = IIO_VAL_INT;
528 		*vals = data->chip->data_rate;
529 		*length = data->chip->data_rate_len;
530 		return IIO_AVAIL_LIST;
531 	default:
532 		return -EINVAL;
533 	}
534 }
535 
536 static int ads1015_read_raw(struct iio_dev *indio_dev,
537 			    struct iio_chan_spec const *chan, int *val,
538 			    int *val2, long mask)
539 {
540 	int ret, idx;
541 	struct ads1015_data *data = iio_priv(indio_dev);
542 
543 	mutex_lock(&data->lock);
544 	switch (mask) {
545 	case IIO_CHAN_INFO_RAW:
546 		ret = iio_device_claim_direct_mode(indio_dev);
547 		if (ret)
548 			break;
549 
550 		if (ads1015_event_channel_enabled(data) &&
551 				data->event_channel != chan->address) {
552 			ret = -EBUSY;
553 			goto release_direct;
554 		}
555 
556 		ret = ads1015_set_power_state(data, true);
557 		if (ret < 0)
558 			goto release_direct;
559 
560 		ret = ads1015_get_adc_result(data, chan->address, val);
561 		if (ret < 0) {
562 			ads1015_set_power_state(data, false);
563 			goto release_direct;
564 		}
565 
566 		*val = sign_extend32(*val >> chan->scan_type.shift,
567 				     chan->scan_type.realbits - 1);
568 
569 		ret = ads1015_set_power_state(data, false);
570 		if (ret < 0)
571 			goto release_direct;
572 
573 		ret = IIO_VAL_INT;
574 release_direct:
575 		iio_device_release_direct_mode(indio_dev);
576 		break;
577 	case IIO_CHAN_INFO_SCALE:
578 		idx = data->channel_data[chan->address].pga;
579 		*val = ads1015_fullscale_range[idx];
580 		*val2 = chan->scan_type.realbits - 1;
581 		ret = IIO_VAL_FRACTIONAL_LOG2;
582 		break;
583 	case IIO_CHAN_INFO_SAMP_FREQ:
584 		idx = data->channel_data[chan->address].data_rate;
585 		*val = data->chip->data_rate[idx];
586 		ret = IIO_VAL_INT;
587 		break;
588 	default:
589 		ret = -EINVAL;
590 		break;
591 	}
592 	mutex_unlock(&data->lock);
593 
594 	return ret;
595 }
596 
597 static int ads1015_write_raw(struct iio_dev *indio_dev,
598 			     struct iio_chan_spec const *chan, int val,
599 			     int val2, long mask)
600 {
601 	struct ads1015_data *data = iio_priv(indio_dev);
602 	int ret;
603 
604 	mutex_lock(&data->lock);
605 	switch (mask) {
606 	case IIO_CHAN_INFO_SCALE:
607 		ret = ads1015_set_scale(data, chan, val, val2);
608 		break;
609 	case IIO_CHAN_INFO_SAMP_FREQ:
610 		ret = ads1015_set_data_rate(data, chan->address, val);
611 		break;
612 	default:
613 		ret = -EINVAL;
614 		break;
615 	}
616 	mutex_unlock(&data->lock);
617 
618 	return ret;
619 }
620 
621 static int ads1015_read_event(struct iio_dev *indio_dev,
622 	const struct iio_chan_spec *chan, enum iio_event_type type,
623 	enum iio_event_direction dir, enum iio_event_info info, int *val,
624 	int *val2)
625 {
626 	struct ads1015_data *data = iio_priv(indio_dev);
627 	int ret;
628 	unsigned int comp_queue;
629 	int period;
630 	int dr;
631 
632 	mutex_lock(&data->lock);
633 
634 	switch (info) {
635 	case IIO_EV_INFO_VALUE:
636 		*val = (dir == IIO_EV_DIR_RISING) ?
637 			data->thresh_data[chan->address].high_thresh :
638 			data->thresh_data[chan->address].low_thresh;
639 		ret = IIO_VAL_INT;
640 		break;
641 	case IIO_EV_INFO_PERIOD:
642 		dr = data->channel_data[chan->address].data_rate;
643 		comp_queue = data->thresh_data[chan->address].comp_queue;
644 		period = ads1015_comp_queue[comp_queue] *
645 			USEC_PER_SEC / data->chip->data_rate[dr];
646 
647 		*val = period / USEC_PER_SEC;
648 		*val2 = period % USEC_PER_SEC;
649 		ret = IIO_VAL_INT_PLUS_MICRO;
650 		break;
651 	default:
652 		ret = -EINVAL;
653 		break;
654 	}
655 
656 	mutex_unlock(&data->lock);
657 
658 	return ret;
659 }
660 
661 static int ads1015_write_event(struct iio_dev *indio_dev,
662 	const struct iio_chan_spec *chan, enum iio_event_type type,
663 	enum iio_event_direction dir, enum iio_event_info info, int val,
664 	int val2)
665 {
666 	struct ads1015_data *data = iio_priv(indio_dev);
667 	const int *data_rate = data->chip->data_rate;
668 	int realbits = chan->scan_type.realbits;
669 	int ret = 0;
670 	long long period;
671 	int i;
672 	int dr;
673 
674 	mutex_lock(&data->lock);
675 
676 	switch (info) {
677 	case IIO_EV_INFO_VALUE:
678 		if (val >= 1 << (realbits - 1) || val < -1 << (realbits - 1)) {
679 			ret = -EINVAL;
680 			break;
681 		}
682 		if (dir == IIO_EV_DIR_RISING)
683 			data->thresh_data[chan->address].high_thresh = val;
684 		else
685 			data->thresh_data[chan->address].low_thresh = val;
686 		break;
687 	case IIO_EV_INFO_PERIOD:
688 		dr = data->channel_data[chan->address].data_rate;
689 		period = val * USEC_PER_SEC + val2;
690 
691 		for (i = 0; i < ARRAY_SIZE(ads1015_comp_queue) - 1; i++) {
692 			if (period <= ads1015_comp_queue[i] *
693 					USEC_PER_SEC / data_rate[dr])
694 				break;
695 		}
696 		data->thresh_data[chan->address].comp_queue = i;
697 		break;
698 	default:
699 		ret = -EINVAL;
700 		break;
701 	}
702 
703 	mutex_unlock(&data->lock);
704 
705 	return ret;
706 }
707 
708 static int ads1015_read_event_config(struct iio_dev *indio_dev,
709 	const struct iio_chan_spec *chan, enum iio_event_type type,
710 	enum iio_event_direction dir)
711 {
712 	struct ads1015_data *data = iio_priv(indio_dev);
713 	int ret = 0;
714 
715 	mutex_lock(&data->lock);
716 	if (data->event_channel == chan->address) {
717 		switch (dir) {
718 		case IIO_EV_DIR_RISING:
719 			ret = 1;
720 			break;
721 		case IIO_EV_DIR_EITHER:
722 			ret = (data->comp_mode == ADS1015_CFG_COMP_MODE_WINDOW);
723 			break;
724 		default:
725 			ret = -EINVAL;
726 			break;
727 		}
728 	}
729 	mutex_unlock(&data->lock);
730 
731 	return ret;
732 }
733 
734 static int ads1015_enable_event_config(struct ads1015_data *data,
735 	const struct iio_chan_spec *chan, int comp_mode)
736 {
737 	int low_thresh = data->thresh_data[chan->address].low_thresh;
738 	int high_thresh = data->thresh_data[chan->address].high_thresh;
739 	int ret;
740 	unsigned int val;
741 
742 	if (ads1015_event_channel_enabled(data)) {
743 		if (data->event_channel != chan->address ||
744 			(data->comp_mode == ADS1015_CFG_COMP_MODE_TRAD &&
745 				comp_mode == ADS1015_CFG_COMP_MODE_WINDOW))
746 			return -EBUSY;
747 
748 		return 0;
749 	}
750 
751 	if (comp_mode == ADS1015_CFG_COMP_MODE_TRAD) {
752 		low_thresh = max(-1 << (chan->scan_type.realbits - 1),
753 				high_thresh - 1);
754 	}
755 	ret = regmap_write(data->regmap, ADS1015_LO_THRESH_REG,
756 			low_thresh << chan->scan_type.shift);
757 	if (ret)
758 		return ret;
759 
760 	ret = regmap_write(data->regmap, ADS1015_HI_THRESH_REG,
761 			high_thresh << chan->scan_type.shift);
762 	if (ret)
763 		return ret;
764 
765 	ret = ads1015_set_power_state(data, true);
766 	if (ret < 0)
767 		return ret;
768 
769 	ads1015_event_channel_enable(data, chan->address, comp_mode);
770 
771 	ret = ads1015_get_adc_result(data, chan->address, &val);
772 	if (ret) {
773 		ads1015_event_channel_disable(data, chan->address);
774 		ads1015_set_power_state(data, false);
775 	}
776 
777 	return ret;
778 }
779 
780 static int ads1015_disable_event_config(struct ads1015_data *data,
781 	const struct iio_chan_spec *chan, int comp_mode)
782 {
783 	int ret;
784 
785 	if (!ads1015_event_channel_enabled(data))
786 		return 0;
787 
788 	if (data->event_channel != chan->address)
789 		return 0;
790 
791 	if (data->comp_mode == ADS1015_CFG_COMP_MODE_TRAD &&
792 			comp_mode == ADS1015_CFG_COMP_MODE_WINDOW)
793 		return 0;
794 
795 	ret = regmap_update_bits(data->regmap, ADS1015_CFG_REG,
796 				ADS1015_CFG_COMP_QUE_MASK,
797 				ADS1015_CFG_COMP_DISABLE <<
798 					ADS1015_CFG_COMP_QUE_SHIFT);
799 	if (ret)
800 		return ret;
801 
802 	ads1015_event_channel_disable(data, chan->address);
803 
804 	return ads1015_set_power_state(data, false);
805 }
806 
807 static int ads1015_write_event_config(struct iio_dev *indio_dev,
808 	const struct iio_chan_spec *chan, enum iio_event_type type,
809 	enum iio_event_direction dir, int state)
810 {
811 	struct ads1015_data *data = iio_priv(indio_dev);
812 	int ret;
813 	int comp_mode = (dir == IIO_EV_DIR_EITHER) ?
814 		ADS1015_CFG_COMP_MODE_WINDOW : ADS1015_CFG_COMP_MODE_TRAD;
815 
816 	mutex_lock(&data->lock);
817 
818 	/* Prevent from enabling both buffer and event at a time */
819 	ret = iio_device_claim_direct_mode(indio_dev);
820 	if (ret) {
821 		mutex_unlock(&data->lock);
822 		return ret;
823 	}
824 
825 	if (state)
826 		ret = ads1015_enable_event_config(data, chan, comp_mode);
827 	else
828 		ret = ads1015_disable_event_config(data, chan, comp_mode);
829 
830 	iio_device_release_direct_mode(indio_dev);
831 	mutex_unlock(&data->lock);
832 
833 	return ret;
834 }
835 
836 static irqreturn_t ads1015_event_handler(int irq, void *priv)
837 {
838 	struct iio_dev *indio_dev = priv;
839 	struct ads1015_data *data = iio_priv(indio_dev);
840 	int val;
841 	int ret;
842 
843 	/* Clear the latched ALERT/RDY pin */
844 	ret = regmap_read(data->regmap, ADS1015_CONV_REG, &val);
845 	if (ret)
846 		return IRQ_HANDLED;
847 
848 	if (ads1015_event_channel_enabled(data)) {
849 		enum iio_event_direction dir;
850 		u64 code;
851 
852 		dir = data->comp_mode == ADS1015_CFG_COMP_MODE_TRAD ?
853 					IIO_EV_DIR_RISING : IIO_EV_DIR_EITHER;
854 		code = IIO_UNMOD_EVENT_CODE(IIO_VOLTAGE, data->event_channel,
855 					IIO_EV_TYPE_THRESH, dir);
856 		iio_push_event(indio_dev, code, iio_get_time_ns(indio_dev));
857 	}
858 
859 	return IRQ_HANDLED;
860 }
861 
862 static int ads1015_buffer_preenable(struct iio_dev *indio_dev)
863 {
864 	struct ads1015_data *data = iio_priv(indio_dev);
865 
866 	/* Prevent from enabling both buffer and event at a time */
867 	if (ads1015_event_channel_enabled(data))
868 		return -EBUSY;
869 
870 	return ads1015_set_power_state(iio_priv(indio_dev), true);
871 }
872 
873 static int ads1015_buffer_postdisable(struct iio_dev *indio_dev)
874 {
875 	return ads1015_set_power_state(iio_priv(indio_dev), false);
876 }
877 
878 static const struct iio_buffer_setup_ops ads1015_buffer_setup_ops = {
879 	.preenable	= ads1015_buffer_preenable,
880 	.postdisable	= ads1015_buffer_postdisable,
881 	.validate_scan_mask = &iio_validate_scan_mask_onehot,
882 };
883 
884 static const struct iio_info ads1015_info = {
885 	.read_avail	= ads1015_read_avail,
886 	.read_raw	= ads1015_read_raw,
887 	.write_raw	= ads1015_write_raw,
888 	.read_event_value = ads1015_read_event,
889 	.write_event_value = ads1015_write_event,
890 	.read_event_config = ads1015_read_event_config,
891 	.write_event_config = ads1015_write_event_config,
892 };
893 
894 static const struct iio_info tla2024_info = {
895 	.read_avail	= ads1015_read_avail,
896 	.read_raw	= ads1015_read_raw,
897 	.write_raw	= ads1015_write_raw,
898 };
899 
900 static int ads1015_client_get_channels_config(struct i2c_client *client)
901 {
902 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
903 	struct ads1015_data *data = iio_priv(indio_dev);
904 	struct device *dev = &client->dev;
905 	struct fwnode_handle *node;
906 	int i = -1;
907 
908 	device_for_each_child_node(dev, node) {
909 		u32 pval;
910 		unsigned int channel;
911 		unsigned int pga = ADS1015_DEFAULT_PGA;
912 		unsigned int data_rate = ADS1015_DEFAULT_DATA_RATE;
913 
914 		if (fwnode_property_read_u32(node, "reg", &pval)) {
915 			dev_err(dev, "invalid reg on %pfw\n", node);
916 			continue;
917 		}
918 
919 		channel = pval;
920 		if (channel >= ADS1015_CHANNELS) {
921 			dev_err(dev, "invalid channel index %d on %pfw\n",
922 				channel, node);
923 			continue;
924 		}
925 
926 		if (!fwnode_property_read_u32(node, "ti,gain", &pval)) {
927 			pga = pval;
928 			if (pga > 6) {
929 				dev_err(dev, "invalid gain on %pfw\n", node);
930 				fwnode_handle_put(node);
931 				return -EINVAL;
932 			}
933 		}
934 
935 		if (!fwnode_property_read_u32(node, "ti,datarate", &pval)) {
936 			data_rate = pval;
937 			if (data_rate > 7) {
938 				dev_err(dev, "invalid data_rate on %pfw\n", node);
939 				fwnode_handle_put(node);
940 				return -EINVAL;
941 			}
942 		}
943 
944 		data->channel_data[channel].pga = pga;
945 		data->channel_data[channel].data_rate = data_rate;
946 
947 		i++;
948 	}
949 
950 	return i < 0 ? -EINVAL : 0;
951 }
952 
953 static void ads1015_get_channels_config(struct i2c_client *client)
954 {
955 	unsigned int k;
956 
957 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
958 	struct ads1015_data *data = iio_priv(indio_dev);
959 
960 	if (!ads1015_client_get_channels_config(client))
961 		return;
962 
963 	/* fallback on default configuration */
964 	for (k = 0; k < ADS1015_CHANNELS; ++k) {
965 		data->channel_data[k].pga = ADS1015_DEFAULT_PGA;
966 		data->channel_data[k].data_rate = ADS1015_DEFAULT_DATA_RATE;
967 	}
968 }
969 
970 static int ads1015_set_conv_mode(struct ads1015_data *data, int mode)
971 {
972 	return regmap_update_bits(data->regmap, ADS1015_CFG_REG,
973 				  ADS1015_CFG_MOD_MASK,
974 				  mode << ADS1015_CFG_MOD_SHIFT);
975 }
976 
977 static int ads1015_probe(struct i2c_client *client)
978 {
979 	const struct i2c_device_id *id = i2c_client_get_device_id(client);
980 	const struct ads1015_chip_data *chip;
981 	struct iio_dev *indio_dev;
982 	struct ads1015_data *data;
983 	int ret;
984 	int i;
985 
986 	chip = device_get_match_data(&client->dev);
987 	if (!chip)
988 		chip = (const struct ads1015_chip_data *)id->driver_data;
989 	if (!chip)
990 		return dev_err_probe(&client->dev, -EINVAL, "Unknown chip\n");
991 
992 	indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
993 	if (!indio_dev)
994 		return -ENOMEM;
995 
996 	data = iio_priv(indio_dev);
997 	i2c_set_clientdata(client, indio_dev);
998 
999 	mutex_init(&data->lock);
1000 
1001 	indio_dev->name = ADS1015_DRV_NAME;
1002 	indio_dev->modes = INDIO_DIRECT_MODE;
1003 
1004 	indio_dev->channels = chip->channels;
1005 	indio_dev->num_channels = chip->num_channels;
1006 	indio_dev->info = chip->info;
1007 	data->chip = chip;
1008 	data->event_channel = ADS1015_CHANNELS;
1009 
1010 	/*
1011 	 * Set default lower and upper threshold to min and max value
1012 	 * respectively.
1013 	 */
1014 	for (i = 0; i < ADS1015_CHANNELS; i++) {
1015 		int realbits = indio_dev->channels[i].scan_type.realbits;
1016 
1017 		data->thresh_data[i].low_thresh = -1 << (realbits - 1);
1018 		data->thresh_data[i].high_thresh = (1 << (realbits - 1)) - 1;
1019 	}
1020 
1021 	/* we need to keep this ABI the same as used by hwmon ADS1015 driver */
1022 	ads1015_get_channels_config(client);
1023 
1024 	data->regmap = devm_regmap_init_i2c(client, chip->has_comparator ?
1025 					    &ads1015_regmap_config :
1026 					    &tla2024_regmap_config);
1027 	if (IS_ERR(data->regmap)) {
1028 		dev_err(&client->dev, "Failed to allocate register map\n");
1029 		return PTR_ERR(data->regmap);
1030 	}
1031 
1032 	ret = devm_iio_triggered_buffer_setup(&client->dev, indio_dev, NULL,
1033 					      ads1015_trigger_handler,
1034 					      &ads1015_buffer_setup_ops);
1035 	if (ret < 0) {
1036 		dev_err(&client->dev, "iio triggered buffer setup failed\n");
1037 		return ret;
1038 	}
1039 
1040 	if (client->irq && chip->has_comparator) {
1041 		unsigned long irq_trig =
1042 			irqd_get_trigger_type(irq_get_irq_data(client->irq));
1043 		unsigned int cfg_comp_mask = ADS1015_CFG_COMP_QUE_MASK |
1044 			ADS1015_CFG_COMP_LAT_MASK | ADS1015_CFG_COMP_POL_MASK;
1045 		unsigned int cfg_comp =
1046 			ADS1015_CFG_COMP_DISABLE << ADS1015_CFG_COMP_QUE_SHIFT |
1047 			1 << ADS1015_CFG_COMP_LAT_SHIFT;
1048 
1049 		switch (irq_trig) {
1050 		case IRQF_TRIGGER_LOW:
1051 			cfg_comp |= ADS1015_CFG_COMP_POL_LOW <<
1052 					ADS1015_CFG_COMP_POL_SHIFT;
1053 			break;
1054 		case IRQF_TRIGGER_HIGH:
1055 			cfg_comp |= ADS1015_CFG_COMP_POL_HIGH <<
1056 					ADS1015_CFG_COMP_POL_SHIFT;
1057 			break;
1058 		default:
1059 			return -EINVAL;
1060 		}
1061 
1062 		ret = regmap_update_bits(data->regmap, ADS1015_CFG_REG,
1063 					cfg_comp_mask, cfg_comp);
1064 		if (ret)
1065 			return ret;
1066 
1067 		ret = devm_request_threaded_irq(&client->dev, client->irq,
1068 						NULL, ads1015_event_handler,
1069 						irq_trig | IRQF_ONESHOT,
1070 						client->name, indio_dev);
1071 		if (ret)
1072 			return ret;
1073 	}
1074 
1075 	ret = ads1015_set_conv_mode(data, ADS1015_CONTINUOUS);
1076 	if (ret)
1077 		return ret;
1078 
1079 	data->conv_invalid = true;
1080 
1081 	ret = pm_runtime_set_active(&client->dev);
1082 	if (ret)
1083 		return ret;
1084 	pm_runtime_set_autosuspend_delay(&client->dev, ADS1015_SLEEP_DELAY_MS);
1085 	pm_runtime_use_autosuspend(&client->dev);
1086 	pm_runtime_enable(&client->dev);
1087 
1088 	ret = iio_device_register(indio_dev);
1089 	if (ret < 0) {
1090 		dev_err(&client->dev, "Failed to register IIO device\n");
1091 		return ret;
1092 	}
1093 
1094 	return 0;
1095 }
1096 
1097 static void ads1015_remove(struct i2c_client *client)
1098 {
1099 	struct iio_dev *indio_dev = i2c_get_clientdata(client);
1100 	struct ads1015_data *data = iio_priv(indio_dev);
1101 	int ret;
1102 
1103 	iio_device_unregister(indio_dev);
1104 
1105 	pm_runtime_disable(&client->dev);
1106 	pm_runtime_set_suspended(&client->dev);
1107 
1108 	/* power down single shot mode */
1109 	ret = ads1015_set_conv_mode(data, ADS1015_SINGLESHOT);
1110 	if (ret)
1111 		dev_warn(&client->dev, "Failed to power down (%pe)\n",
1112 			 ERR_PTR(ret));
1113 }
1114 
1115 #ifdef CONFIG_PM
1116 static int ads1015_runtime_suspend(struct device *dev)
1117 {
1118 	struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
1119 	struct ads1015_data *data = iio_priv(indio_dev);
1120 
1121 	return ads1015_set_conv_mode(data, ADS1015_SINGLESHOT);
1122 }
1123 
1124 static int ads1015_runtime_resume(struct device *dev)
1125 {
1126 	struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
1127 	struct ads1015_data *data = iio_priv(indio_dev);
1128 	int ret;
1129 
1130 	ret = ads1015_set_conv_mode(data, ADS1015_CONTINUOUS);
1131 	if (!ret)
1132 		data->conv_invalid = true;
1133 
1134 	return ret;
1135 }
1136 #endif
1137 
1138 static const struct dev_pm_ops ads1015_pm_ops = {
1139 	SET_RUNTIME_PM_OPS(ads1015_runtime_suspend,
1140 			   ads1015_runtime_resume, NULL)
1141 };
1142 
1143 static const struct ads1015_chip_data ads1015_data = {
1144 	.channels	= ads1015_channels,
1145 	.num_channels	= ARRAY_SIZE(ads1015_channels),
1146 	.info		= &ads1015_info,
1147 	.data_rate	= ads1015_data_rate,
1148 	.data_rate_len	= ARRAY_SIZE(ads1015_data_rate),
1149 	.scale		= ads1015_scale,
1150 	.scale_len	= ARRAY_SIZE(ads1015_scale),
1151 	.has_comparator	= true,
1152 };
1153 
1154 static const struct ads1015_chip_data ads1115_data = {
1155 	.channels	= ads1115_channels,
1156 	.num_channels	= ARRAY_SIZE(ads1115_channels),
1157 	.info		= &ads1015_info,
1158 	.data_rate	= ads1115_data_rate,
1159 	.data_rate_len	= ARRAY_SIZE(ads1115_data_rate),
1160 	.scale		= ads1115_scale,
1161 	.scale_len	= ARRAY_SIZE(ads1115_scale),
1162 	.has_comparator	= true,
1163 };
1164 
1165 static const struct ads1015_chip_data tla2024_data = {
1166 	.channels	= tla2024_channels,
1167 	.num_channels	= ARRAY_SIZE(tla2024_channels),
1168 	.info		= &tla2024_info,
1169 	.data_rate	= ads1015_data_rate,
1170 	.data_rate_len	= ARRAY_SIZE(ads1015_data_rate),
1171 	.scale		= ads1015_scale,
1172 	.scale_len	= ARRAY_SIZE(ads1015_scale),
1173 	.has_comparator	= false,
1174 };
1175 
1176 static const struct i2c_device_id ads1015_id[] = {
1177 	{ "ads1015", (kernel_ulong_t)&ads1015_data },
1178 	{ "ads1115", (kernel_ulong_t)&ads1115_data },
1179 	{ "tla2024", (kernel_ulong_t)&tla2024_data },
1180 	{}
1181 };
1182 MODULE_DEVICE_TABLE(i2c, ads1015_id);
1183 
1184 static const struct of_device_id ads1015_of_match[] = {
1185 	{ .compatible = "ti,ads1015", .data = &ads1015_data },
1186 	{ .compatible = "ti,ads1115", .data = &ads1115_data },
1187 	{ .compatible = "ti,tla2024", .data = &tla2024_data },
1188 	{}
1189 };
1190 MODULE_DEVICE_TABLE(of, ads1015_of_match);
1191 
1192 static struct i2c_driver ads1015_driver = {
1193 	.driver = {
1194 		.name = ADS1015_DRV_NAME,
1195 		.of_match_table = ads1015_of_match,
1196 		.pm = &ads1015_pm_ops,
1197 	},
1198 	.probe_new	= ads1015_probe,
1199 	.remove		= ads1015_remove,
1200 	.id_table	= ads1015_id,
1201 };
1202 
1203 module_i2c_driver(ads1015_driver);
1204 
1205 MODULE_AUTHOR("Daniel Baluta <daniel.baluta@intel.com>");
1206 MODULE_DESCRIPTION("Texas Instruments ADS1015 ADC driver");
1207 MODULE_LICENSE("GPL v2");
1208