xref: /linux/drivers/iio/adc/max11410.c (revision 4b132aacb0768ac1e652cf517097ea6f237214b9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * MAX11410 SPI ADC driver
4  *
5  * Copyright 2022 Analog Devices Inc.
6  */
7 #include <linux/bitfield.h>
8 #include <linux/delay.h>
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/interrupt.h>
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/regmap.h>
15 #include <linux/regulator/consumer.h>
16 #include <linux/spi/spi.h>
17 
18 #include <asm/unaligned.h>
19 
20 #include <linux/iio/buffer.h>
21 #include <linux/iio/sysfs.h>
22 #include <linux/iio/trigger.h>
23 #include <linux/iio/trigger_consumer.h>
24 #include <linux/iio/triggered_buffer.h>
25 
26 #define MAX11410_REG_CONV_START	0x01
27 #define		MAX11410_CONV_TYPE_SINGLE	0x00
28 #define		MAX11410_CONV_TYPE_CONTINUOUS	0x01
29 #define MAX11410_REG_CAL_START	0x03
30 #define		MAX11410_CAL_START_SELF		0x00
31 #define		MAX11410_CAL_START_PGA		0x01
32 #define MAX11410_REG_GPIO_CTRL(ch)		((ch) ? 0x05 : 0x04)
33 #define		MAX11410_GPIO_INTRB		0xC1
34 #define MAX11410_REG_FILTER	0x08
35 #define		MAX11410_FILTER_RATE_MASK	GENMASK(3, 0)
36 #define		MAX11410_FILTER_RATE_MAX	0x0F
37 #define		MAX11410_FILTER_LINEF_MASK	GENMASK(5, 4)
38 #define		MAX11410_FILTER_50HZ		BIT(5)
39 #define		MAX11410_FILTER_60HZ		BIT(4)
40 #define MAX11410_REG_CTRL	0x09
41 #define		MAX11410_CTRL_REFSEL_MASK	GENMASK(2, 0)
42 #define		MAX11410_CTRL_VREFN_BUF_BIT	BIT(3)
43 #define		MAX11410_CTRL_VREFP_BUF_BIT	BIT(4)
44 #define		MAX11410_CTRL_FORMAT_BIT	BIT(5)
45 #define		MAX11410_CTRL_UNIPOLAR_BIT	BIT(6)
46 #define MAX11410_REG_MUX_CTRL0	0x0B
47 #define MAX11410_REG_PGA	0x0E
48 #define		MAX11410_PGA_GAIN_MASK		GENMASK(2, 0)
49 #define		MAX11410_PGA_SIG_PATH_MASK	GENMASK(5, 4)
50 #define		MAX11410_PGA_SIG_PATH_BUFFERED	0x00
51 #define		MAX11410_PGA_SIG_PATH_BYPASS	0x01
52 #define		MAX11410_PGA_SIG_PATH_PGA	0x02
53 #define MAX11410_REG_DATA0	0x30
54 #define MAX11410_REG_STATUS	0x38
55 #define		MAX11410_STATUS_CONV_READY_BIT	BIT(0)
56 #define		MAX11410_STATUS_CAL_READY_BIT	BIT(2)
57 
58 #define MAX11410_REFSEL_AVDD_AGND	0x03
59 #define MAX11410_REFSEL_MAX		0x06
60 #define MAX11410_SIG_PATH_MAX		0x02
61 #define MAX11410_CHANNEL_INDEX_MAX	0x0A
62 #define MAX11410_AINP_AVDD	0x0A
63 #define MAX11410_AINN_GND	0x0A
64 
65 #define MAX11410_CONVERSION_TIMEOUT_MS	2000
66 #define MAX11410_CALIB_TIMEOUT_MS	2000
67 
68 #define MAX11410_SCALE_AVAIL_SIZE	8
69 
70 enum max11410_filter {
71 	MAX11410_FILTER_FIR5060,
72 	MAX11410_FILTER_FIR50,
73 	MAX11410_FILTER_FIR60,
74 	MAX11410_FILTER_SINC4,
75 };
76 
77 static const u8 max11410_sampling_len[] = {
78 	[MAX11410_FILTER_FIR5060] = 5,
79 	[MAX11410_FILTER_FIR50] = 6,
80 	[MAX11410_FILTER_FIR60] = 6,
81 	[MAX11410_FILTER_SINC4] = 10,
82 };
83 
84 static const int max11410_sampling_rates[4][10][2] = {
85 	[MAX11410_FILTER_FIR5060] = {
86 		{ 1, 100000 },
87 		{ 2, 100000 },
88 		{ 4, 200000 },
89 		{ 8, 400000 },
90 		{ 16, 800000 }
91 	},
92 	[MAX11410_FILTER_FIR50] = {
93 		{ 1, 300000 },
94 		{ 2, 700000 },
95 		{ 5, 300000 },
96 		{ 10, 700000 },
97 		{ 21, 300000 },
98 		{ 40 }
99 	},
100 	[MAX11410_FILTER_FIR60] = {
101 		{ 1, 300000 },
102 		{ 2, 700000 },
103 		{ 5, 300000 },
104 		{ 10, 700000 },
105 		{ 21, 300000 },
106 		{ 40 }
107 	},
108 	[MAX11410_FILTER_SINC4] = {
109 		{ 4 },
110 		{ 10 },
111 		{ 20 },
112 		{ 40 },
113 		{ 60 },
114 		{ 120 },
115 		{ 240 },
116 		{ 480 },
117 		{ 960 },
118 		{ 1920 }
119 	}
120 };
121 
122 struct max11410_channel_config {
123 	u32 settling_time_us;
124 	u32 *scale_avail;
125 	u8 refsel;
126 	u8 sig_path;
127 	u8 gain;
128 	bool bipolar;
129 	bool buffered_vrefp;
130 	bool buffered_vrefn;
131 };
132 
133 struct max11410_state {
134 	struct spi_device *spi_dev;
135 	struct iio_trigger *trig;
136 	struct completion completion;
137 	struct mutex lock; /* Prevent changing channel config during sampling */
138 	struct regmap *regmap;
139 	struct regulator *avdd;
140 	struct regulator *vrefp[3];
141 	struct regulator *vrefn[3];
142 	struct max11410_channel_config *channels;
143 	int irq;
144 	struct {
145 		u32 data __aligned(IIO_DMA_MINALIGN);
146 		s64 ts __aligned(8);
147 	} scan;
148 };
149 
150 static const struct iio_chan_spec chanspec_template = {
151 	.type = IIO_VOLTAGE,
152 	.indexed = 1,
153 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
154 			      BIT(IIO_CHAN_INFO_SCALE) |
155 			      BIT(IIO_CHAN_INFO_OFFSET),
156 	.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ),
157 	.info_mask_shared_by_all_available = BIT(IIO_CHAN_INFO_SAMP_FREQ),
158 	.scan_type = {
159 		.sign = 's',
160 		.realbits = 24,
161 		.storagebits = 32,
162 		.endianness = IIO_LE,
163 	},
164 };
165 
166 static unsigned int max11410_reg_size(unsigned int reg)
167 {
168 	/* Registers from 0x00 to 0x10 are 1 byte, the rest are 3 bytes long. */
169 	return reg <= 0x10 ? 1 : 3;
170 }
171 
172 static int max11410_write_reg(struct max11410_state *st, unsigned int reg,
173 			      unsigned int val)
174 {
175 	/* This driver only needs to write 8-bit registers */
176 	if (max11410_reg_size(reg) != 1)
177 		return -EINVAL;
178 
179 	return regmap_write(st->regmap, reg, val);
180 }
181 
182 static int max11410_read_reg(struct max11410_state *st, unsigned int reg,
183 			     int *val)
184 {
185 	int ret;
186 
187 	if (max11410_reg_size(reg) == 3) {
188 		ret = regmap_bulk_read(st->regmap, reg, &st->scan.data, 3);
189 		if (ret)
190 			return ret;
191 
192 		*val = get_unaligned_be24(&st->scan.data);
193 		return 0;
194 	}
195 
196 	return regmap_read(st->regmap, reg, val);
197 }
198 
199 static struct regulator *max11410_get_vrefp(struct max11410_state *st,
200 					    u8 refsel)
201 {
202 	refsel = refsel % 4;
203 	if (refsel == 3)
204 		return st->avdd;
205 
206 	return st->vrefp[refsel];
207 }
208 
209 static struct regulator *max11410_get_vrefn(struct max11410_state *st,
210 					    u8 refsel)
211 {
212 	if (refsel > 2)
213 		return NULL;
214 
215 	return st->vrefn[refsel];
216 }
217 
218 static const struct regmap_config regmap_config = {
219 	.reg_bits = 8,
220 	.val_bits = 8,
221 	.max_register = 0x39,
222 };
223 
224 static ssize_t max11410_notch_en_show(struct device *dev,
225 				      struct device_attribute *devattr,
226 				      char *buf)
227 {
228 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
229 	struct max11410_state *state = iio_priv(indio_dev);
230 	struct iio_dev_attr *iio_attr = to_iio_dev_attr(devattr);
231 	unsigned int val;
232 	int ret;
233 
234 	ret = max11410_read_reg(state, MAX11410_REG_FILTER, &val);
235 	if (ret)
236 		return ret;
237 
238 	switch (iio_attr->address) {
239 	case 0:
240 		val = !FIELD_GET(MAX11410_FILTER_50HZ, val);
241 		break;
242 	case 1:
243 		val = !FIELD_GET(MAX11410_FILTER_60HZ, val);
244 		break;
245 	case 2:
246 		val = FIELD_GET(MAX11410_FILTER_LINEF_MASK, val) == 3;
247 		break;
248 	default:
249 		return -EINVAL;
250 	}
251 
252 	return sysfs_emit(buf, "%d\n", val);
253 }
254 
255 static ssize_t max11410_notch_en_store(struct device *dev,
256 				       struct device_attribute *devattr,
257 				       const char *buf, size_t count)
258 {
259 	struct iio_dev_attr *iio_attr = to_iio_dev_attr(devattr);
260 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
261 	struct max11410_state *state = iio_priv(indio_dev);
262 	unsigned int filter_bits;
263 	bool enable;
264 	int ret;
265 
266 	ret = kstrtobool(buf, &enable);
267 	if (ret)
268 		return ret;
269 
270 	switch (iio_attr->address) {
271 	case 0:
272 		filter_bits = MAX11410_FILTER_50HZ;
273 		break;
274 	case 1:
275 		filter_bits = MAX11410_FILTER_60HZ;
276 		break;
277 	case 2:
278 	default:
279 		filter_bits = MAX11410_FILTER_50HZ | MAX11410_FILTER_60HZ;
280 		enable = !enable;
281 		break;
282 	}
283 
284 	if (enable)
285 		ret = regmap_clear_bits(state->regmap, MAX11410_REG_FILTER,
286 					filter_bits);
287 	else
288 		ret = regmap_set_bits(state->regmap, MAX11410_REG_FILTER,
289 				      filter_bits);
290 
291 	if (ret)
292 		return ret;
293 
294 	return count;
295 }
296 
297 static ssize_t in_voltage_filter2_notch_center_show(struct device *dev,
298 						    struct device_attribute *devattr,
299 						    char *buf)
300 {
301 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
302 	struct max11410_state *state = iio_priv(indio_dev);
303 	int ret, reg, rate, filter;
304 
305 	ret = regmap_read(state->regmap, MAX11410_REG_FILTER, &reg);
306 	if (ret)
307 		return ret;
308 
309 	rate = FIELD_GET(MAX11410_FILTER_RATE_MASK, reg);
310 	rate = clamp_val(rate, 0,
311 			 max11410_sampling_len[MAX11410_FILTER_SINC4] - 1);
312 	filter = max11410_sampling_rates[MAX11410_FILTER_SINC4][rate][0];
313 
314 	return sysfs_emit(buf, "%d\n", filter);
315 }
316 
317 static IIO_CONST_ATTR(in_voltage_filter0_notch_center, "50");
318 static IIO_CONST_ATTR(in_voltage_filter1_notch_center, "60");
319 static IIO_DEVICE_ATTR_RO(in_voltage_filter2_notch_center, 2);
320 
321 static IIO_DEVICE_ATTR(in_voltage_filter0_notch_en, 0644,
322 		       max11410_notch_en_show, max11410_notch_en_store, 0);
323 static IIO_DEVICE_ATTR(in_voltage_filter1_notch_en, 0644,
324 		       max11410_notch_en_show, max11410_notch_en_store, 1);
325 static IIO_DEVICE_ATTR(in_voltage_filter2_notch_en, 0644,
326 		       max11410_notch_en_show, max11410_notch_en_store, 2);
327 
328 static struct attribute *max11410_attributes[] = {
329 	&iio_const_attr_in_voltage_filter0_notch_center.dev_attr.attr,
330 	&iio_const_attr_in_voltage_filter1_notch_center.dev_attr.attr,
331 	&iio_dev_attr_in_voltage_filter2_notch_center.dev_attr.attr,
332 	&iio_dev_attr_in_voltage_filter0_notch_en.dev_attr.attr,
333 	&iio_dev_attr_in_voltage_filter1_notch_en.dev_attr.attr,
334 	&iio_dev_attr_in_voltage_filter2_notch_en.dev_attr.attr,
335 	NULL
336 };
337 
338 static const struct attribute_group max11410_attribute_group = {
339 	.attrs = max11410_attributes,
340 };
341 
342 static int max11410_set_input_mux(struct max11410_state *st, u8 ainp, u8 ainn)
343 {
344 	if (ainp > MAX11410_CHANNEL_INDEX_MAX ||
345 	    ainn > MAX11410_CHANNEL_INDEX_MAX)
346 		return -EINVAL;
347 
348 	return max11410_write_reg(st, MAX11410_REG_MUX_CTRL0,
349 				  (ainp << 4) | ainn);
350 }
351 
352 static int max11410_configure_channel(struct max11410_state *st,
353 				      struct iio_chan_spec const *chan)
354 {
355 	struct max11410_channel_config cfg = st->channels[chan->address];
356 	unsigned int regval;
357 	int ret;
358 
359 	if (chan->differential)
360 		ret = max11410_set_input_mux(st, chan->channel, chan->channel2);
361 	else
362 		ret = max11410_set_input_mux(st, chan->channel,
363 					     MAX11410_AINN_GND);
364 
365 	if (ret)
366 		return ret;
367 
368 	regval = FIELD_PREP(MAX11410_CTRL_VREFP_BUF_BIT, cfg.buffered_vrefp) |
369 		 FIELD_PREP(MAX11410_CTRL_VREFN_BUF_BIT, cfg.buffered_vrefn) |
370 		 FIELD_PREP(MAX11410_CTRL_REFSEL_MASK, cfg.refsel) |
371 		 FIELD_PREP(MAX11410_CTRL_UNIPOLAR_BIT, cfg.bipolar ? 0 : 1);
372 	ret = regmap_update_bits(st->regmap, MAX11410_REG_CTRL,
373 				 MAX11410_CTRL_REFSEL_MASK |
374 				 MAX11410_CTRL_VREFP_BUF_BIT |
375 				 MAX11410_CTRL_VREFN_BUF_BIT |
376 				 MAX11410_CTRL_UNIPOLAR_BIT, regval);
377 	if (ret)
378 		return ret;
379 
380 	regval = FIELD_PREP(MAX11410_PGA_SIG_PATH_MASK, cfg.sig_path) |
381 		 FIELD_PREP(MAX11410_PGA_GAIN_MASK, cfg.gain);
382 	ret = regmap_write(st->regmap, MAX11410_REG_PGA, regval);
383 	if (ret)
384 		return ret;
385 
386 	if (cfg.settling_time_us)
387 		fsleep(cfg.settling_time_us);
388 
389 	return 0;
390 }
391 
392 static int max11410_sample(struct max11410_state *st, int *sample_raw,
393 			   struct iio_chan_spec const *chan)
394 {
395 	int val, ret;
396 
397 	ret = max11410_configure_channel(st, chan);
398 	if (ret)
399 		return ret;
400 
401 	if (st->irq > 0)
402 		reinit_completion(&st->completion);
403 
404 	/* Start Conversion */
405 	ret = max11410_write_reg(st, MAX11410_REG_CONV_START,
406 				 MAX11410_CONV_TYPE_SINGLE);
407 	if (ret)
408 		return ret;
409 
410 	if (st->irq > 0) {
411 		/* Wait for an interrupt. */
412 		ret = wait_for_completion_timeout(&st->completion,
413 						  msecs_to_jiffies(MAX11410_CONVERSION_TIMEOUT_MS));
414 		if (!ret)
415 			return -ETIMEDOUT;
416 	} else {
417 		int ret2;
418 
419 		/* Wait for status register Conversion Ready flag */
420 		ret = read_poll_timeout(max11410_read_reg, ret2,
421 					ret2 || (val & MAX11410_STATUS_CONV_READY_BIT),
422 					5000, MAX11410_CONVERSION_TIMEOUT_MS * 1000,
423 					true, st, MAX11410_REG_STATUS, &val);
424 		if (ret)
425 			return ret;
426 		if (ret2)
427 			return ret2;
428 	}
429 
430 	/* Read ADC Data */
431 	return max11410_read_reg(st, MAX11410_REG_DATA0, sample_raw);
432 }
433 
434 static int max11410_get_scale(struct max11410_state *state,
435 			      struct max11410_channel_config cfg)
436 {
437 	struct regulator *vrefp, *vrefn;
438 	int scale;
439 
440 	vrefp = max11410_get_vrefp(state, cfg.refsel);
441 
442 	scale = regulator_get_voltage(vrefp) / 1000;
443 	vrefn = max11410_get_vrefn(state, cfg.refsel);
444 	if (vrefn)
445 		scale -= regulator_get_voltage(vrefn) / 1000;
446 
447 	if (cfg.bipolar)
448 		scale *= 2;
449 
450 	return scale >> cfg.gain;
451 }
452 
453 static int max11410_read_raw(struct iio_dev *indio_dev,
454 			     struct iio_chan_spec const *chan,
455 			     int *val, int *val2, long info)
456 {
457 	struct max11410_state *state = iio_priv(indio_dev);
458 	struct max11410_channel_config cfg = state->channels[chan->address];
459 	int ret, reg_val, filter, rate;
460 
461 	switch (info) {
462 	case IIO_CHAN_INFO_SCALE:
463 		*val = max11410_get_scale(state, cfg);
464 		*val2 = chan->scan_type.realbits;
465 		return IIO_VAL_FRACTIONAL_LOG2;
466 	case IIO_CHAN_INFO_OFFSET:
467 		if (cfg.bipolar)
468 			*val = -BIT(chan->scan_type.realbits - 1);
469 		else
470 			*val = 0;
471 
472 		return IIO_VAL_INT;
473 	case IIO_CHAN_INFO_RAW:
474 		ret = iio_device_claim_direct_mode(indio_dev);
475 		if (ret)
476 			return ret;
477 
478 		mutex_lock(&state->lock);
479 
480 		ret = max11410_sample(state, &reg_val, chan);
481 
482 		mutex_unlock(&state->lock);
483 
484 		iio_device_release_direct_mode(indio_dev);
485 
486 		if (ret)
487 			return ret;
488 
489 		*val = reg_val;
490 
491 		return IIO_VAL_INT;
492 	case IIO_CHAN_INFO_SAMP_FREQ:
493 		ret = regmap_read(state->regmap, MAX11410_REG_FILTER, &reg_val);
494 		if (ret)
495 			return ret;
496 
497 		filter = FIELD_GET(MAX11410_FILTER_LINEF_MASK, reg_val);
498 		rate = reg_val & MAX11410_FILTER_RATE_MASK;
499 		if (rate >= max11410_sampling_len[filter])
500 			rate = max11410_sampling_len[filter] - 1;
501 
502 		*val = max11410_sampling_rates[filter][rate][0];
503 		*val2 = max11410_sampling_rates[filter][rate][1];
504 
505 		return IIO_VAL_INT_PLUS_MICRO;
506 	}
507 	return -EINVAL;
508 }
509 
510 static int max11410_write_raw(struct iio_dev *indio_dev,
511 			      struct iio_chan_spec const *chan,
512 			      int val, int val2, long mask)
513 {
514 	struct max11410_state *st = iio_priv(indio_dev);
515 	int i, ret, reg_val, filter, gain;
516 	u32 *scale_avail;
517 
518 	switch (mask) {
519 	case IIO_CHAN_INFO_SCALE:
520 		scale_avail = st->channels[chan->address].scale_avail;
521 		if (!scale_avail)
522 			return -EOPNOTSUPP;
523 
524 		/* Accept values in range 0.000001 <= scale < 1.000000 */
525 		if (val != 0 || val2 == 0)
526 			return -EINVAL;
527 
528 		ret = iio_device_claim_direct_mode(indio_dev);
529 		if (ret)
530 			return ret;
531 
532 		/* Convert from INT_PLUS_MICRO to FRACTIONAL_LOG2 */
533 		val2 = val2 * DIV_ROUND_CLOSEST(BIT(24), 1000000);
534 		val2 = DIV_ROUND_CLOSEST(scale_avail[0], val2);
535 		gain = order_base_2(val2);
536 
537 		st->channels[chan->address].gain = clamp_val(gain, 0, 7);
538 
539 		iio_device_release_direct_mode(indio_dev);
540 
541 		return 0;
542 	case IIO_CHAN_INFO_SAMP_FREQ:
543 		ret = iio_device_claim_direct_mode(indio_dev);
544 		if (ret)
545 			return ret;
546 
547 		mutex_lock(&st->lock);
548 
549 		ret = regmap_read(st->regmap, MAX11410_REG_FILTER, &reg_val);
550 		if (ret)
551 			goto out;
552 
553 		filter = FIELD_GET(MAX11410_FILTER_LINEF_MASK, reg_val);
554 
555 		for (i = 0; i < max11410_sampling_len[filter]; ++i) {
556 			if (val == max11410_sampling_rates[filter][i][0] &&
557 			    val2 == max11410_sampling_rates[filter][i][1])
558 				break;
559 		}
560 		if (i == max11410_sampling_len[filter]) {
561 			ret = -EINVAL;
562 			goto out;
563 		}
564 
565 		ret = regmap_write_bits(st->regmap, MAX11410_REG_FILTER,
566 					MAX11410_FILTER_RATE_MASK, i);
567 
568 out:
569 		mutex_unlock(&st->lock);
570 		iio_device_release_direct_mode(indio_dev);
571 
572 		return ret;
573 	default:
574 		return -EINVAL;
575 	}
576 }
577 
578 static int max11410_read_avail(struct iio_dev *indio_dev,
579 			       struct iio_chan_spec const *chan,
580 			       const int **vals, int *type, int *length,
581 			       long info)
582 {
583 	struct max11410_state *st = iio_priv(indio_dev);
584 	struct max11410_channel_config cfg;
585 	int ret, reg_val, filter;
586 
587 	switch (info) {
588 	case IIO_CHAN_INFO_SAMP_FREQ:
589 		ret = regmap_read(st->regmap, MAX11410_REG_FILTER, &reg_val);
590 		if (ret)
591 			return ret;
592 
593 		filter = FIELD_GET(MAX11410_FILTER_LINEF_MASK, reg_val);
594 
595 		*vals = (const int *)max11410_sampling_rates[filter];
596 		*length = max11410_sampling_len[filter] * 2;
597 		*type = IIO_VAL_INT_PLUS_MICRO;
598 
599 		return IIO_AVAIL_LIST;
600 	case IIO_CHAN_INFO_SCALE:
601 		cfg = st->channels[chan->address];
602 
603 		if (!cfg.scale_avail)
604 			return -EINVAL;
605 
606 		*vals = cfg.scale_avail;
607 		*length = MAX11410_SCALE_AVAIL_SIZE * 2;
608 		*type = IIO_VAL_FRACTIONAL_LOG2;
609 
610 		return IIO_AVAIL_LIST;
611 	}
612 	return -EINVAL;
613 }
614 
615 static const struct iio_info max11410_info = {
616 	.read_raw = max11410_read_raw,
617 	.write_raw = max11410_write_raw,
618 	.read_avail = max11410_read_avail,
619 	.attrs = &max11410_attribute_group,
620 };
621 
622 static irqreturn_t max11410_trigger_handler(int irq, void *p)
623 {
624 	struct iio_poll_func *pf = p;
625 	struct iio_dev *indio_dev = pf->indio_dev;
626 	struct max11410_state *st = iio_priv(indio_dev);
627 	int ret;
628 
629 	ret = max11410_read_reg(st, MAX11410_REG_DATA0, &st->scan.data);
630 	if (ret) {
631 		dev_err(&indio_dev->dev, "cannot read data\n");
632 		goto out;
633 	}
634 
635 	iio_push_to_buffers_with_timestamp(indio_dev, &st->scan,
636 					   iio_get_time_ns(indio_dev));
637 
638 out:
639 	iio_trigger_notify_done(indio_dev->trig);
640 
641 	return IRQ_HANDLED;
642 }
643 
644 static int max11410_buffer_postenable(struct iio_dev *indio_dev)
645 {
646 	struct max11410_state *st = iio_priv(indio_dev);
647 	int scan_ch, ret;
648 
649 	scan_ch = ffs(*indio_dev->active_scan_mask) - 1;
650 
651 	ret = max11410_configure_channel(st, &indio_dev->channels[scan_ch]);
652 	if (ret)
653 		return ret;
654 
655 	/* Start continuous conversion. */
656 	return max11410_write_reg(st, MAX11410_REG_CONV_START,
657 				  MAX11410_CONV_TYPE_CONTINUOUS);
658 }
659 
660 static int max11410_buffer_predisable(struct iio_dev *indio_dev)
661 {
662 	struct max11410_state *st = iio_priv(indio_dev);
663 
664 	/* Stop continuous conversion. */
665 	return max11410_write_reg(st, MAX11410_REG_CONV_START,
666 				  MAX11410_CONV_TYPE_SINGLE);
667 }
668 
669 static const struct iio_buffer_setup_ops max11410_buffer_ops = {
670 	.postenable = &max11410_buffer_postenable,
671 	.predisable = &max11410_buffer_predisable,
672 	.validate_scan_mask = &iio_validate_scan_mask_onehot,
673 };
674 
675 static const struct iio_trigger_ops max11410_trigger_ops = {
676 	.validate_device = iio_trigger_validate_own_device,
677 };
678 
679 static irqreturn_t max11410_interrupt(int irq, void *dev_id)
680 {
681 	struct iio_dev *indio_dev = dev_id;
682 	struct max11410_state *st = iio_priv(indio_dev);
683 
684 	if (iio_buffer_enabled(indio_dev))
685 		iio_trigger_poll_nested(st->trig);
686 	else
687 		complete(&st->completion);
688 
689 	return IRQ_HANDLED;
690 };
691 
692 static int max11410_parse_channels(struct max11410_state *st,
693 				   struct iio_dev *indio_dev)
694 {
695 	struct iio_chan_spec chanspec = chanspec_template;
696 	struct device *dev = &st->spi_dev->dev;
697 	struct max11410_channel_config *cfg;
698 	struct iio_chan_spec *channels;
699 	u32 reference, sig_path;
700 	const char *node_name;
701 	u32 inputs[2], scale;
702 	unsigned int num_ch;
703 	int chan_idx = 0;
704 	int ret, i;
705 
706 	num_ch = device_get_child_node_count(dev);
707 	if (num_ch == 0)
708 		return dev_err_probe(&indio_dev->dev, -ENODEV,
709 				     "FW has no channels defined\n");
710 
711 	/* Reserve space for soft timestamp channel */
712 	num_ch++;
713 	channels = devm_kcalloc(dev, num_ch, sizeof(*channels), GFP_KERNEL);
714 	if (!channels)
715 		return -ENOMEM;
716 
717 	st->channels = devm_kcalloc(dev, num_ch, sizeof(*st->channels),
718 				    GFP_KERNEL);
719 	if (!st->channels)
720 		return -ENOMEM;
721 
722 	device_for_each_child_node_scoped(dev, child) {
723 		node_name = fwnode_get_name(child);
724 		if (fwnode_property_present(child, "diff-channels")) {
725 			ret = fwnode_property_read_u32_array(child,
726 							     "diff-channels",
727 							     inputs,
728 							     ARRAY_SIZE(inputs));
729 
730 			chanspec.differential = 1;
731 		} else {
732 			ret = fwnode_property_read_u32(child, "reg", &inputs[0]);
733 
734 			inputs[1] = 0;
735 			chanspec.differential = 0;
736 		}
737 		if (ret)
738 			return ret;
739 
740 		if (inputs[0] > MAX11410_CHANNEL_INDEX_MAX ||
741 		    inputs[1] > MAX11410_CHANNEL_INDEX_MAX)
742 			return dev_err_probe(&indio_dev->dev, -EINVAL,
743 					     "Invalid channel index for %s, should be less than %d\n",
744 					     node_name,
745 					     MAX11410_CHANNEL_INDEX_MAX + 1);
746 
747 		cfg = &st->channels[chan_idx];
748 
749 		reference = MAX11410_REFSEL_AVDD_AGND;
750 		fwnode_property_read_u32(child, "adi,reference", &reference);
751 		if (reference > MAX11410_REFSEL_MAX)
752 			return dev_err_probe(&indio_dev->dev, -EINVAL,
753 					     "Invalid adi,reference value for %s, should be less than %d.\n",
754 					     node_name, MAX11410_REFSEL_MAX + 1);
755 
756 		if (!max11410_get_vrefp(st, reference) ||
757 		    (!max11410_get_vrefn(st, reference) && reference <= 2))
758 			return dev_err_probe(&indio_dev->dev, -EINVAL,
759 					     "Invalid VREF configuration for %s, either specify corresponding VREF regulators or change adi,reference property.\n",
760 					     node_name);
761 
762 		sig_path = MAX11410_PGA_SIG_PATH_BUFFERED;
763 		fwnode_property_read_u32(child, "adi,input-mode", &sig_path);
764 		if (sig_path > MAX11410_SIG_PATH_MAX)
765 			return dev_err_probe(&indio_dev->dev, -EINVAL,
766 					     "Invalid adi,input-mode value for %s, should be less than %d.\n",
767 					     node_name, MAX11410_SIG_PATH_MAX + 1);
768 
769 		fwnode_property_read_u32(child, "settling-time-us",
770 					 &cfg->settling_time_us);
771 		cfg->bipolar = fwnode_property_read_bool(child, "bipolar");
772 		cfg->buffered_vrefp = fwnode_property_read_bool(child, "adi,buffered-vrefp");
773 		cfg->buffered_vrefn = fwnode_property_read_bool(child, "adi,buffered-vrefn");
774 		cfg->refsel = reference;
775 		cfg->sig_path = sig_path;
776 		cfg->gain = 0;
777 
778 		/* Enable scale_available property if input mode is PGA */
779 		if (sig_path == MAX11410_PGA_SIG_PATH_PGA) {
780 			__set_bit(IIO_CHAN_INFO_SCALE,
781 				  &chanspec.info_mask_separate_available);
782 			cfg->scale_avail = devm_kcalloc(dev, MAX11410_SCALE_AVAIL_SIZE * 2,
783 							sizeof(*cfg->scale_avail),
784 							GFP_KERNEL);
785 			if (!cfg->scale_avail)
786 				return -ENOMEM;
787 
788 			scale = max11410_get_scale(st, *cfg);
789 			for (i = 0; i < MAX11410_SCALE_AVAIL_SIZE; i++) {
790 				cfg->scale_avail[2 * i] = scale >> i;
791 				cfg->scale_avail[2 * i + 1] = chanspec.scan_type.realbits;
792 			}
793 		} else {
794 			__clear_bit(IIO_CHAN_INFO_SCALE,
795 				    &chanspec.info_mask_separate_available);
796 		}
797 
798 		chanspec.address = chan_idx;
799 		chanspec.scan_index = chan_idx;
800 		chanspec.channel = inputs[0];
801 		chanspec.channel2 = inputs[1];
802 
803 		channels[chan_idx] = chanspec;
804 		chan_idx++;
805 	}
806 
807 	channels[chan_idx] = (struct iio_chan_spec)IIO_CHAN_SOFT_TIMESTAMP(chan_idx);
808 
809 	indio_dev->num_channels = chan_idx + 1;
810 	indio_dev->channels = channels;
811 
812 	return 0;
813 }
814 
815 static void max11410_disable_reg(void *reg)
816 {
817 	regulator_disable(reg);
818 }
819 
820 static int max11410_init_vref(struct device *dev,
821 			      struct regulator **vref,
822 			      const char *id)
823 {
824 	struct regulator *reg;
825 	int ret;
826 
827 	reg = devm_regulator_get_optional(dev, id);
828 	if (PTR_ERR(reg) == -ENODEV) {
829 		*vref = NULL;
830 		return 0;
831 	} else if (IS_ERR(reg)) {
832 		return PTR_ERR(reg);
833 	}
834 	ret = regulator_enable(reg);
835 	if (ret)
836 		return dev_err_probe(dev, ret,
837 				     "Failed to enable regulator %s\n", id);
838 
839 	*vref = reg;
840 	return devm_add_action_or_reset(dev, max11410_disable_reg, reg);
841 }
842 
843 static int max11410_calibrate(struct max11410_state *st, u32 cal_type)
844 {
845 	int ret, ret2, val;
846 
847 	ret = max11410_write_reg(st, MAX11410_REG_CAL_START, cal_type);
848 	if (ret)
849 		return ret;
850 
851 	/* Wait for status register Calibration Ready flag */
852 	ret = read_poll_timeout(max11410_read_reg, ret2,
853 				ret2 || (val & MAX11410_STATUS_CAL_READY_BIT),
854 				50000, MAX11410_CALIB_TIMEOUT_MS * 1000, true,
855 				st, MAX11410_REG_STATUS, &val);
856 	if (ret)
857 		return ret;
858 
859 	return ret2;
860 }
861 
862 static int max11410_self_calibrate(struct max11410_state *st)
863 {
864 	int ret, i;
865 
866 	ret = regmap_write_bits(st->regmap, MAX11410_REG_FILTER,
867 				MAX11410_FILTER_RATE_MASK,
868 				FIELD_PREP(MAX11410_FILTER_RATE_MASK,
869 					   MAX11410_FILTER_RATE_MAX));
870 	if (ret)
871 		return ret;
872 
873 	ret = max11410_calibrate(st, MAX11410_CAL_START_SELF);
874 	if (ret)
875 		return ret;
876 
877 	ret = regmap_write_bits(st->regmap, MAX11410_REG_PGA,
878 				MAX11410_PGA_SIG_PATH_MASK,
879 				FIELD_PREP(MAX11410_PGA_SIG_PATH_MASK,
880 					   MAX11410_PGA_SIG_PATH_PGA));
881 	if (ret)
882 		return ret;
883 
884 	/* PGA calibrations */
885 	for (i = 1; i < 8; ++i) {
886 		ret = regmap_write_bits(st->regmap, MAX11410_REG_PGA,
887 					MAX11410_PGA_GAIN_MASK, i);
888 		if (ret)
889 			return ret;
890 
891 		ret = max11410_calibrate(st, MAX11410_CAL_START_PGA);
892 		if (ret)
893 			return ret;
894 	}
895 
896 	/* Cleanup */
897 	ret = regmap_write_bits(st->regmap, MAX11410_REG_PGA,
898 				MAX11410_PGA_GAIN_MASK, 0);
899 	if (ret)
900 		return ret;
901 
902 	ret = regmap_write_bits(st->regmap, MAX11410_REG_FILTER,
903 				MAX11410_FILTER_RATE_MASK, 0);
904 	if (ret)
905 		return ret;
906 
907 	return regmap_write_bits(st->regmap, MAX11410_REG_PGA,
908 				 MAX11410_PGA_SIG_PATH_MASK,
909 				 FIELD_PREP(MAX11410_PGA_SIG_PATH_MASK,
910 					    MAX11410_PGA_SIG_PATH_BUFFERED));
911 }
912 
913 static int max11410_probe(struct spi_device *spi)
914 {
915 	const char *vrefp_regs[] = { "vref0p", "vref1p", "vref2p" };
916 	const char *vrefn_regs[] = { "vref0n", "vref1n", "vref2n" };
917 	struct device *dev = &spi->dev;
918 	struct max11410_state *st;
919 	struct iio_dev *indio_dev;
920 	int ret, irqs[2];
921 	int i;
922 
923 	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
924 	if (!indio_dev)
925 		return -ENOMEM;
926 
927 	st = iio_priv(indio_dev);
928 	st->spi_dev = spi;
929 	init_completion(&st->completion);
930 	mutex_init(&st->lock);
931 
932 	indio_dev->name = "max11410";
933 	indio_dev->modes = INDIO_DIRECT_MODE;
934 	indio_dev->info = &max11410_info;
935 
936 	st->regmap = devm_regmap_init_spi(spi, &regmap_config);
937 	if (IS_ERR(st->regmap))
938 		return dev_err_probe(dev, PTR_ERR(st->regmap),
939 				     "regmap initialization failed\n");
940 
941 	ret = max11410_init_vref(dev, &st->avdd, "avdd");
942 	if (ret)
943 		return ret;
944 
945 	for (i = 0; i < ARRAY_SIZE(vrefp_regs); i++) {
946 		ret = max11410_init_vref(dev, &st->vrefp[i], vrefp_regs[i]);
947 		if (ret)
948 			return ret;
949 
950 		ret = max11410_init_vref(dev, &st->vrefn[i], vrefn_regs[i]);
951 		if (ret)
952 			return ret;
953 	}
954 
955 	/*
956 	 * Regulators must be configured before parsing channels for
957 	 * validating "adi,reference" property of each channel.
958 	 */
959 	ret = max11410_parse_channels(st, indio_dev);
960 	if (ret)
961 		return ret;
962 
963 	irqs[0] = fwnode_irq_get_byname(dev_fwnode(dev), "gpio0");
964 	irqs[1] = fwnode_irq_get_byname(dev_fwnode(dev), "gpio1");
965 
966 	if (irqs[0] > 0) {
967 		st->irq = irqs[0];
968 		ret = regmap_write(st->regmap, MAX11410_REG_GPIO_CTRL(0),
969 				   MAX11410_GPIO_INTRB);
970 	} else if (irqs[1] > 0) {
971 		st->irq = irqs[1];
972 		ret = regmap_write(st->regmap, MAX11410_REG_GPIO_CTRL(1),
973 				   MAX11410_GPIO_INTRB);
974 	} else if (spi->irq > 0) {
975 		return dev_err_probe(dev, -ENODEV,
976 				     "no interrupt name specified");
977 	}
978 
979 	if (ret)
980 		return ret;
981 
982 	ret = regmap_set_bits(st->regmap, MAX11410_REG_CTRL,
983 			      MAX11410_CTRL_FORMAT_BIT);
984 	if (ret)
985 		return ret;
986 
987 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev, NULL,
988 					      &max11410_trigger_handler,
989 					      &max11410_buffer_ops);
990 	if (ret)
991 		return ret;
992 
993 	if (st->irq > 0) {
994 		st->trig = devm_iio_trigger_alloc(dev, "%s-dev%d",
995 						  indio_dev->name,
996 						  iio_device_id(indio_dev));
997 		if (!st->trig)
998 			return -ENOMEM;
999 
1000 		st->trig->ops = &max11410_trigger_ops;
1001 		ret = devm_iio_trigger_register(dev, st->trig);
1002 		if (ret)
1003 			return ret;
1004 
1005 		ret = devm_request_threaded_irq(dev, st->irq, NULL,
1006 						&max11410_interrupt,
1007 						IRQF_ONESHOT, "max11410",
1008 						indio_dev);
1009 		if (ret)
1010 			return ret;
1011 	}
1012 
1013 	ret = max11410_self_calibrate(st);
1014 	if (ret)
1015 		return dev_err_probe(dev, ret,
1016 				     "cannot perform device self calibration\n");
1017 
1018 	return devm_iio_device_register(dev, indio_dev);
1019 }
1020 
1021 static const struct of_device_id max11410_spi_of_id[] = {
1022 	{ .compatible = "adi,max11410" },
1023 	{ }
1024 };
1025 MODULE_DEVICE_TABLE(of, max11410_spi_of_id);
1026 
1027 static const struct spi_device_id max11410_id[] = {
1028 	{ "max11410" },
1029 	{ }
1030 };
1031 MODULE_DEVICE_TABLE(spi, max11410_id);
1032 
1033 static struct spi_driver max11410_driver = {
1034 	.driver = {
1035 		.name	= "max11410",
1036 		.of_match_table = max11410_spi_of_id,
1037 	},
1038 	.probe		= max11410_probe,
1039 	.id_table	= max11410_id,
1040 };
1041 module_spi_driver(max11410_driver);
1042 
1043 MODULE_AUTHOR("David Jung <David.Jung@analog.com>");
1044 MODULE_AUTHOR("Ibrahim Tilki <Ibrahim.Tilki@analog.com>");
1045 MODULE_DESCRIPTION("Analog Devices MAX11410 ADC");
1046 MODULE_LICENSE("GPL");
1047