xref: /linux/drivers/iio/adc/ad4695.c (revision 2fcea44e1ba16c55f4602948d2d43f3a365d6070)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * SPI ADC driver for Analog Devices Inc. AD4695 and similar chips
4  *
5  * https://www.analog.com/en/products/ad4695.html
6  * https://www.analog.com/en/products/ad4696.html
7  * https://www.analog.com/en/products/ad4697.html
8  * https://www.analog.com/en/products/ad4698.html
9  *
10  * Copyright 2024 Analog Devices Inc.
11  * Copyright 2024 BayLibre, SAS
12  */
13 
14 #include <linux/align.h>
15 #include <linux/bitfield.h>
16 #include <linux/bits.h>
17 #include <linux/compiler.h>
18 #include <linux/delay.h>
19 #include <linux/device.h>
20 #include <linux/err.h>
21 #include <linux/gpio/consumer.h>
22 #include <linux/iio/buffer.h>
23 #include <linux/iio/iio.h>
24 #include <linux/iio/triggered_buffer.h>
25 #include <linux/iio/trigger_consumer.h>
26 #include <linux/property.h>
27 #include <linux/regmap.h>
28 #include <linux/regulator/consumer.h>
29 #include <linux/spi/spi.h>
30 #include <linux/units.h>
31 
32 #include <dt-bindings/iio/adi,ad4695.h>
33 
34 /* AD4695 registers */
35 #define AD4695_REG_SPI_CONFIG_A				0x0000
36 #define   AD4695_REG_SPI_CONFIG_A_SW_RST		  (BIT(7) | BIT(0))
37 #define AD4695_REG_SPI_CONFIG_B				0x0001
38 #define   AD4695_REG_SPI_CONFIG_B_INST_MODE		  BIT(7)
39 #define AD4695_REG_DEVICE_TYPE				0x0003
40 #define AD4695_REG_SCRATCH_PAD				0x000A
41 #define AD4695_REG_VENDOR_L				0x000C
42 #define AD4695_REG_VENDOR_H				0x000D
43 #define AD4695_REG_LOOP_MODE				0x000E
44 #define AD4695_REG_SPI_CONFIG_C				0x0010
45 #define   AD4695_REG_SPI_CONFIG_C_MB_STRICT		  BIT(7)
46 #define AD4695_REG_SPI_STATUS				0x0011
47 #define AD4695_REG_STATUS				0x0014
48 #define AD4695_REG_ALERT_STATUS1			0x0015
49 #define AD4695_REG_ALERT_STATUS2			0x0016
50 #define AD4695_REG_CLAMP_STATUS				0x001A
51 #define AD4695_REG_SETUP				0x0020
52 #define   AD4695_REG_SETUP_LDO_EN			  BIT(4)
53 #define   AD4695_REG_SETUP_SPI_MODE			  BIT(2)
54 #define   AD4695_REG_SETUP_SPI_CYC_CTRL			  BIT(1)
55 #define AD4695_REG_REF_CTRL				0x0021
56 #define   AD4695_REG_REF_CTRL_OV_MODE			  BIT(7)
57 #define   AD4695_REG_REF_CTRL_VREF_SET			  GENMASK(4, 2)
58 #define   AD4695_REG_REF_CTRL_REFHIZ_EN			  BIT(1)
59 #define   AD4695_REG_REF_CTRL_REFBUF_EN			  BIT(0)
60 #define AD4695_REG_SEQ_CTRL				0x0022
61 #define   AD4695_REG_SEQ_CTRL_STD_SEQ_EN		  BIT(7)
62 #define   AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS		  GENMASK(6, 0)
63 #define AD4695_REG_AC_CTRL				0x0023
64 #define AD4695_REG_STD_SEQ_CONFIG			0x0024
65 #define AD4695_REG_GPIO_CTRL				0x0026
66 #define AD4695_REG_GP_MODE				0x0027
67 #define AD4695_REG_TEMP_CTRL				0x0029
68 #define   AD4695_REG_TEMP_CTRL_TEMP_EN			  BIT(0)
69 #define AD4695_REG_CONFIG_IN(n)				(0x0030 | (n))
70 #define   AD4695_REG_CONFIG_IN_MODE			  BIT(6)
71 #define   AD4695_REG_CONFIG_IN_PAIR			  GENMASK(5, 4)
72 #define   AD4695_REG_CONFIG_IN_AINHIGHZ_EN		  BIT(3)
73 #define AD4695_REG_UPPER_IN(n)				(0x0040 | (2 * (n)))
74 #define AD4695_REG_LOWER_IN(n)				(0x0060 | (2 * (n)))
75 #define AD4695_REG_HYST_IN(n)				(0x0080 | (2 * (n)))
76 #define AD4695_REG_OFFSET_IN(n)				(0x00A0 | (2 * (n)))
77 #define AD4695_REG_GAIN_IN(n)				(0x00C0 | (2 * (n)))
78 #define AD4695_REG_AS_SLOT(n)				(0x0100 | (n))
79 #define   AD4695_REG_AS_SLOT_INX			  GENMASK(3, 0)
80 #define AD4695_MAX_REG					0x017F
81 
82 /* Conversion mode commands */
83 #define AD4695_CMD_EXIT_CNV_MODE	0x0A
84 #define AD4695_CMD_TEMP_CHAN		0x0F
85 #define AD4695_CMD_VOLTAGE_CHAN(n)	(0x10 | (n))
86 
87 /* timing specs */
88 #define AD4695_T_CONVERT_NS		415
89 #define AD4695_T_WAKEUP_HW_MS		3
90 #define AD4695_T_WAKEUP_SW_MS		3
91 #define AD4695_T_REFBUF_MS		100
92 #define AD4695_T_REGCONFIG_NS		20
93 #define AD4695_REG_ACCESS_SCLK_HZ	(10 * MEGA)
94 
95 /* Max number of voltage input channels. */
96 #define AD4695_MAX_CHANNELS		16
97 /* Max size of 1 raw sample in bytes. */
98 #define AD4695_MAX_CHANNEL_SIZE		2
99 
100 enum ad4695_in_pair {
101 	AD4695_IN_PAIR_REFGND,
102 	AD4695_IN_PAIR_COM,
103 	AD4695_IN_PAIR_EVEN_ODD,
104 };
105 
106 struct ad4695_chip_info {
107 	const char *name;
108 	int max_sample_rate;
109 	u32 t_acq_ns;
110 	u8 num_voltage_inputs;
111 };
112 
113 struct ad4695_channel_config {
114 	unsigned int channel;
115 	bool highz_en;
116 	bool bipolar;
117 	enum ad4695_in_pair pin_pairing;
118 	unsigned int common_mode_mv;
119 };
120 
121 struct ad4695_state {
122 	struct spi_device *spi;
123 	struct regmap *regmap;
124 	struct gpio_desc *reset_gpio;
125 	/* voltages channels plus temperature and timestamp */
126 	struct iio_chan_spec iio_chan[AD4695_MAX_CHANNELS + 2];
127 	struct ad4695_channel_config channels_cfg[AD4695_MAX_CHANNELS];
128 	const struct ad4695_chip_info *chip_info;
129 	/* Reference voltage. */
130 	unsigned int vref_mv;
131 	/* Common mode input pin voltage. */
132 	unsigned int com_mv;
133 	/* 1 per voltage and temperature chan plus 1 xfer to trigger 1st CNV */
134 	struct spi_transfer buf_read_xfer[AD4695_MAX_CHANNELS + 2];
135 	struct spi_message buf_read_msg;
136 	/* Raw conversion data received. */
137 	u8 buf[ALIGN((AD4695_MAX_CHANNELS + 2) * AD4695_MAX_CHANNEL_SIZE,
138 		     sizeof(s64)) + sizeof(s64)] __aligned(IIO_DMA_MINALIGN);
139 	u16 raw_data;
140 	/* Commands to send for single conversion. */
141 	u16 cnv_cmd;
142 	u8 cnv_cmd2;
143 };
144 
145 static const struct regmap_range ad4695_regmap_rd_ranges[] = {
146 	regmap_reg_range(AD4695_REG_SPI_CONFIG_A, AD4695_REG_SPI_CONFIG_B),
147 	regmap_reg_range(AD4695_REG_DEVICE_TYPE, AD4695_REG_DEVICE_TYPE),
148 	regmap_reg_range(AD4695_REG_SCRATCH_PAD, AD4695_REG_SCRATCH_PAD),
149 	regmap_reg_range(AD4695_REG_VENDOR_L, AD4695_REG_LOOP_MODE),
150 	regmap_reg_range(AD4695_REG_SPI_CONFIG_C, AD4695_REG_SPI_STATUS),
151 	regmap_reg_range(AD4695_REG_STATUS, AD4695_REG_ALERT_STATUS2),
152 	regmap_reg_range(AD4695_REG_CLAMP_STATUS, AD4695_REG_CLAMP_STATUS),
153 	regmap_reg_range(AD4695_REG_SETUP, AD4695_REG_TEMP_CTRL),
154 	regmap_reg_range(AD4695_REG_CONFIG_IN(0), AD4695_MAX_REG),
155 };
156 
157 static const struct regmap_access_table ad4695_regmap_rd_table = {
158 	.yes_ranges = ad4695_regmap_rd_ranges,
159 	.n_yes_ranges = ARRAY_SIZE(ad4695_regmap_rd_ranges),
160 };
161 
162 static const struct regmap_range ad4695_regmap_wr_ranges[] = {
163 	regmap_reg_range(AD4695_REG_SPI_CONFIG_A, AD4695_REG_SPI_CONFIG_B),
164 	regmap_reg_range(AD4695_REG_SCRATCH_PAD, AD4695_REG_SCRATCH_PAD),
165 	regmap_reg_range(AD4695_REG_LOOP_MODE, AD4695_REG_LOOP_MODE),
166 	regmap_reg_range(AD4695_REG_SPI_CONFIG_C, AD4695_REG_SPI_STATUS),
167 	regmap_reg_range(AD4695_REG_SETUP, AD4695_REG_TEMP_CTRL),
168 	regmap_reg_range(AD4695_REG_CONFIG_IN(0), AD4695_MAX_REG),
169 };
170 
171 static const struct regmap_access_table ad4695_regmap_wr_table = {
172 	.yes_ranges = ad4695_regmap_wr_ranges,
173 	.n_yes_ranges = ARRAY_SIZE(ad4695_regmap_wr_ranges),
174 };
175 
176 static const struct regmap_config ad4695_regmap_config = {
177 	.name = "ad4695",
178 	.reg_bits = 16,
179 	.val_bits = 8,
180 	.max_register = AD4695_MAX_REG,
181 	.rd_table = &ad4695_regmap_rd_table,
182 	.wr_table = &ad4695_regmap_wr_table,
183 	.can_multi_write = true,
184 };
185 
186 static const struct iio_chan_spec ad4695_channel_template = {
187 	.type = IIO_VOLTAGE,
188 	.indexed = 1,
189 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
190 			      BIT(IIO_CHAN_INFO_SCALE) |
191 			      BIT(IIO_CHAN_INFO_OFFSET),
192 	.scan_type = {
193 		.sign = 'u',
194 		.realbits = 16,
195 		.storagebits = 16,
196 	},
197 };
198 
199 static const struct iio_chan_spec ad4695_temp_channel_template = {
200 	.address = AD4695_CMD_TEMP_CHAN,
201 	.type = IIO_TEMP,
202 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
203 			      BIT(IIO_CHAN_INFO_SCALE) |
204 			      BIT(IIO_CHAN_INFO_OFFSET),
205 	.scan_type = {
206 		.sign = 's',
207 		.realbits = 16,
208 		.storagebits = 16,
209 	},
210 };
211 
212 static const struct iio_chan_spec ad4695_soft_timestamp_channel_template =
213 	IIO_CHAN_SOFT_TIMESTAMP(0);
214 
215 static const char * const ad4695_power_supplies[] = {
216 	"avdd", "vio"
217 };
218 
219 static const struct ad4695_chip_info ad4695_chip_info = {
220 	.name = "ad4695",
221 	.max_sample_rate = 500 * KILO,
222 	.t_acq_ns = 1715,
223 	.num_voltage_inputs = 16,
224 };
225 
226 static const struct ad4695_chip_info ad4696_chip_info = {
227 	.name = "ad4696",
228 	.max_sample_rate = 1 * MEGA,
229 	.t_acq_ns = 715,
230 	.num_voltage_inputs = 16,
231 };
232 
233 static const struct ad4695_chip_info ad4697_chip_info = {
234 	.name = "ad4697",
235 	.max_sample_rate = 500 * KILO,
236 	.t_acq_ns = 1715,
237 	.num_voltage_inputs = 8,
238 };
239 
240 static const struct ad4695_chip_info ad4698_chip_info = {
241 	.name = "ad4698",
242 	.max_sample_rate = 1 * MEGA,
243 	.t_acq_ns = 715,
244 	.num_voltage_inputs = 8,
245 };
246 
247 /**
248  * ad4695_set_single_cycle_mode - Set the device in single cycle mode
249  * @st: The AD4695 state
250  * @channel: The first channel to read
251  *
252  * As per the datasheet, to enable single cycle mode, we need to set
253  * STD_SEQ_EN=0, NUM_SLOTS_AS=0 and CYC_CTRL=1 (Table 15). Setting SPI_MODE=1
254  * triggers the first conversion using the channel in AS_SLOT0.
255  *
256  * Context: can sleep, must be called with iio_device_claim_direct held
257  * Return: 0 on success, a negative error code on failure
258  */
259 static int ad4695_set_single_cycle_mode(struct ad4695_state *st,
260 					unsigned int channel)
261 {
262 	int ret;
263 
264 	ret = regmap_clear_bits(st->regmap, AD4695_REG_SEQ_CTRL,
265 				AD4695_REG_SEQ_CTRL_STD_SEQ_EN |
266 				AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS);
267 	if (ret)
268 		return ret;
269 
270 	ret = regmap_write(st->regmap, AD4695_REG_AS_SLOT(0),
271 			   FIELD_PREP(AD4695_REG_AS_SLOT_INX, channel));
272 	if (ret)
273 		return ret;
274 
275 	return regmap_set_bits(st->regmap, AD4695_REG_SETUP,
276 			       AD4695_REG_SETUP_SPI_MODE |
277 			       AD4695_REG_SETUP_SPI_CYC_CTRL);
278 }
279 
280 /**
281  * ad4695_enter_advanced_sequencer_mode - Put the ADC in advanced sequencer mode
282  * @st: The driver state
283  * @n: The number of slots to use - must be >= 2, <= 128
284  *
285  * As per the datasheet, to enable advanced sequencer, we need to set
286  * STD_SEQ_EN=0, NUM_SLOTS_AS=n-1 and CYC_CTRL=0 (Table 15). Setting SPI_MODE=1
287  * triggers the first conversion using the channel in AS_SLOT0.
288  *
289  * Return: 0 on success, a negative error code on failure
290  */
291 static int ad4695_enter_advanced_sequencer_mode(struct ad4695_state *st, u32 n)
292 {
293 	int ret;
294 
295 	ret = regmap_update_bits(st->regmap, AD4695_REG_SEQ_CTRL,
296 		AD4695_REG_SEQ_CTRL_STD_SEQ_EN |
297 		AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS,
298 		FIELD_PREP(AD4695_REG_SEQ_CTRL_STD_SEQ_EN, 0) |
299 		FIELD_PREP(AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS, n - 1));
300 	if (ret)
301 		return ret;
302 
303 	return regmap_update_bits(st->regmap, AD4695_REG_SETUP,
304 		AD4695_REG_SETUP_SPI_MODE | AD4695_REG_SETUP_SPI_CYC_CTRL,
305 		FIELD_PREP(AD4695_REG_SETUP_SPI_MODE, 1) |
306 		FIELD_PREP(AD4695_REG_SETUP_SPI_CYC_CTRL, 0));
307 }
308 
309 /**
310  * ad4695_exit_conversion_mode - Exit conversion mode
311  * @st: The AD4695 state
312  *
313  * Sends SPI command to exit conversion mode.
314  *
315  * Return: 0 on success, a negative error code on failure
316  */
317 static int ad4695_exit_conversion_mode(struct ad4695_state *st)
318 {
319 	struct spi_transfer xfer = {
320 		.tx_buf = &st->cnv_cmd2,
321 		.len = 1,
322 		.delay.value = AD4695_T_REGCONFIG_NS,
323 		.delay.unit = SPI_DELAY_UNIT_NSECS,
324 	};
325 
326 	/*
327 	 * Technically, could do a 5-bit transfer, but shifting to start of
328 	 * 8 bits instead for better SPI controller support.
329 	 */
330 	st->cnv_cmd2 = AD4695_CMD_EXIT_CNV_MODE << 3;
331 
332 	return spi_sync_transfer(st->spi, &xfer, 1);
333 }
334 
335 static int ad4695_set_ref_voltage(struct ad4695_state *st, int vref_mv)
336 {
337 	u8 val;
338 
339 	if (vref_mv >= 2400 && vref_mv <= 2750)
340 		val = 0;
341 	else if (vref_mv > 2750 && vref_mv <= 3250)
342 		val = 1;
343 	else if (vref_mv > 3250 && vref_mv <= 3750)
344 		val = 2;
345 	else if (vref_mv > 3750 && vref_mv <= 4500)
346 		val = 3;
347 	else if (vref_mv > 4500 && vref_mv <= 5100)
348 		val = 4;
349 	else
350 		return -EINVAL;
351 
352 	return regmap_update_bits(st->regmap, AD4695_REG_REF_CTRL,
353 				  AD4695_REG_REF_CTRL_VREF_SET,
354 				  FIELD_PREP(AD4695_REG_REF_CTRL_VREF_SET, val));
355 }
356 
357 static int ad4695_write_chn_cfg(struct ad4695_state *st,
358 				struct ad4695_channel_config *cfg)
359 {
360 	u32 mask, val;
361 
362 	mask = AD4695_REG_CONFIG_IN_MODE;
363 	val = FIELD_PREP(AD4695_REG_CONFIG_IN_MODE, cfg->bipolar ? 1 : 0);
364 
365 	mask |= AD4695_REG_CONFIG_IN_PAIR;
366 	val |= FIELD_PREP(AD4695_REG_CONFIG_IN_PAIR, cfg->pin_pairing);
367 
368 	mask |= AD4695_REG_CONFIG_IN_AINHIGHZ_EN;
369 	val |= FIELD_PREP(AD4695_REG_CONFIG_IN_AINHIGHZ_EN,
370 			  cfg->highz_en ? 1 : 0);
371 
372 	return regmap_update_bits(st->regmap,
373 				  AD4695_REG_CONFIG_IN(cfg->channel),
374 				  mask, val);
375 }
376 
377 static int ad4695_buffer_preenable(struct iio_dev *indio_dev)
378 {
379 	struct ad4695_state *st = iio_priv(indio_dev);
380 	struct spi_transfer *xfer;
381 	u8 temp_chan_bit = st->chip_info->num_voltage_inputs;
382 	u32 bit, num_xfer, num_slots;
383 	u32 temp_en = 0;
384 	int ret;
385 
386 	/*
387 	 * We are using the advanced sequencer since it is the only way to read
388 	 * multiple channels that allows individual configuration of each
389 	 * voltage input channel. Slot 0 in the advanced sequencer is used to
390 	 * account for the gap between trigger polls - we don't read data from
391 	 * this slot. Each enabled voltage channel is assigned a slot starting
392 	 * with slot 1.
393 	 */
394 	num_slots = 1;
395 
396 	memset(st->buf_read_xfer, 0, sizeof(st->buf_read_xfer));
397 
398 	/* First xfer is only to trigger conversion of slot 1, so no rx. */
399 	xfer = &st->buf_read_xfer[0];
400 	xfer->cs_change = 1;
401 	xfer->delay.value = st->chip_info->t_acq_ns;
402 	xfer->delay.unit = SPI_DELAY_UNIT_NSECS;
403 	xfer->cs_change_delay.value = AD4695_T_CONVERT_NS;
404 	xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
405 	num_xfer = 1;
406 
407 	iio_for_each_active_channel(indio_dev, bit) {
408 		xfer = &st->buf_read_xfer[num_xfer];
409 		xfer->bits_per_word = 16;
410 		xfer->rx_buf = &st->buf[(num_xfer - 1) * 2];
411 		xfer->len = 2;
412 		xfer->cs_change = 1;
413 		xfer->cs_change_delay.value = AD4695_T_CONVERT_NS;
414 		xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
415 
416 		if (bit == temp_chan_bit) {
417 			temp_en = 1;
418 		} else {
419 			ret = regmap_write(st->regmap,
420 				AD4695_REG_AS_SLOT(num_slots),
421 				FIELD_PREP(AD4695_REG_AS_SLOT_INX, bit));
422 			if (ret)
423 				return ret;
424 
425 			num_slots++;
426 		}
427 
428 		num_xfer++;
429 	}
430 
431 	/*
432 	 * The advanced sequencer requires that at least 2 slots are enabled.
433 	 * Since slot 0 is always used for other purposes, we need only 1
434 	 * enabled voltage channel to meet this requirement. If the temperature
435 	 * channel is the only enabled channel, we need to add one more slot
436 	 * in the sequence but not read from it.
437 	 */
438 	if (num_slots < 2) {
439 		/* move last xfer so we can insert one more xfer before it */
440 		st->buf_read_xfer[num_xfer] = *xfer;
441 		num_xfer++;
442 
443 		/* modify 2nd to last xfer for extra slot */
444 		memset(xfer, 0, sizeof(*xfer));
445 		xfer->cs_change = 1;
446 		xfer->delay.value = st->chip_info->t_acq_ns;
447 		xfer->delay.unit = SPI_DELAY_UNIT_NSECS;
448 		xfer->cs_change_delay.value = AD4695_T_CONVERT_NS;
449 		xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
450 		xfer++;
451 
452 		/* and add the extra slot in the sequencer */
453 		ret = regmap_write(st->regmap,
454 				   AD4695_REG_AS_SLOT(num_slots),
455 				   FIELD_PREP(AD4695_REG_AS_SLOT_INX, 0));
456 		if (ret)
457 			return ret;
458 
459 		num_slots++;
460 	}
461 
462 	/*
463 	 * Don't keep CS asserted after last xfer. Also triggers conversion of
464 	 * slot 0.
465 	 */
466 	xfer->cs_change = 0;
467 
468 	/*
469 	 * Temperature channel isn't included in the sequence, but rather
470 	 * controlled by setting a bit in the TEMP_CTRL register.
471 	 */
472 
473 	ret = regmap_update_bits(st->regmap, AD4695_REG_TEMP_CTRL,
474 		AD4695_REG_TEMP_CTRL_TEMP_EN,
475 		FIELD_PREP(AD4695_REG_TEMP_CTRL_TEMP_EN, temp_en));
476 	if (ret)
477 		return ret;
478 
479 	spi_message_init_with_transfers(&st->buf_read_msg, st->buf_read_xfer,
480 					num_xfer);
481 
482 	ret = spi_optimize_message(st->spi, &st->buf_read_msg);
483 	if (ret)
484 		return ret;
485 
486 	/* This triggers conversion of slot 0. */
487 	ret = ad4695_enter_advanced_sequencer_mode(st, num_slots);
488 	if (ret)
489 		spi_unoptimize_message(&st->buf_read_msg);
490 
491 	return ret;
492 }
493 
494 static int ad4695_buffer_postdisable(struct iio_dev *indio_dev)
495 {
496 	struct ad4695_state *st = iio_priv(indio_dev);
497 	int ret;
498 
499 	ret = ad4695_exit_conversion_mode(st);
500 	if (ret)
501 		return ret;
502 
503 	spi_unoptimize_message(&st->buf_read_msg);
504 
505 	return 0;
506 }
507 
508 static const struct iio_buffer_setup_ops ad4695_buffer_setup_ops = {
509 	.preenable = ad4695_buffer_preenable,
510 	.postdisable = ad4695_buffer_postdisable,
511 };
512 
513 static irqreturn_t ad4695_trigger_handler(int irq, void *p)
514 {
515 	struct iio_poll_func *pf = p;
516 	struct iio_dev *indio_dev = pf->indio_dev;
517 	struct ad4695_state *st = iio_priv(indio_dev);
518 	int ret;
519 
520 	ret = spi_sync(st->spi, &st->buf_read_msg);
521 	if (ret)
522 		goto out;
523 
524 	iio_push_to_buffers_with_timestamp(indio_dev, st->buf, pf->timestamp);
525 
526 out:
527 	iio_trigger_notify_done(indio_dev->trig);
528 
529 	return IRQ_HANDLED;
530 }
531 
532 /**
533  * ad4695_read_one_sample - Read a single sample using single-cycle mode
534  * @st: The AD4695 state
535  * @address: The address of the channel to read
536  *
537  * Upon successful return, the sample will be stored in `st->raw_data`.
538  *
539  * Context: can sleep, must be called with iio_device_claim_direct held
540  * Return: 0 on success, a negative error code on failure
541  */
542 static int ad4695_read_one_sample(struct ad4695_state *st, unsigned int address)
543 {
544 	struct spi_transfer xfer[2] = { };
545 	int ret, i = 0;
546 
547 	ret = ad4695_set_single_cycle_mode(st, address);
548 	if (ret)
549 		return ret;
550 
551 	/*
552 	 * Setting the first channel to the temperature channel isn't supported
553 	 * in single-cycle mode, so we have to do an extra xfer to read the
554 	 * temperature.
555 	 */
556 	if (address == AD4695_CMD_TEMP_CHAN) {
557 		/* We aren't reading, so we can make this a short xfer. */
558 		st->cnv_cmd2 = AD4695_CMD_TEMP_CHAN << 3;
559 		xfer[0].tx_buf = &st->cnv_cmd2;
560 		xfer[0].len = 1;
561 		xfer[0].cs_change = 1;
562 		xfer[0].cs_change_delay.value = AD4695_T_CONVERT_NS;
563 		xfer[0].cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
564 
565 		i = 1;
566 	}
567 
568 	/* Then read the result and exit conversion mode. */
569 	st->cnv_cmd = AD4695_CMD_EXIT_CNV_MODE << 11;
570 	xfer[i].bits_per_word = 16;
571 	xfer[i].tx_buf = &st->cnv_cmd;
572 	xfer[i].rx_buf = &st->raw_data;
573 	xfer[i].len = 2;
574 
575 	return spi_sync_transfer(st->spi, xfer, i + 1);
576 }
577 
578 static int ad4695_read_raw(struct iio_dev *indio_dev,
579 			   struct iio_chan_spec const *chan,
580 			   int *val, int *val2, long mask)
581 {
582 	struct ad4695_state *st = iio_priv(indio_dev);
583 	struct ad4695_channel_config *cfg = &st->channels_cfg[chan->scan_index];
584 	u8 realbits = chan->scan_type.realbits;
585 	int ret;
586 
587 	switch (mask) {
588 	case IIO_CHAN_INFO_RAW:
589 		iio_device_claim_direct_scoped(return -EBUSY, indio_dev) {
590 			ret = ad4695_read_one_sample(st, chan->address);
591 			if (ret)
592 				return ret;
593 
594 			if (chan->scan_type.sign == 's')
595 				*val = sign_extend32(st->raw_data, realbits - 1);
596 			else
597 				*val = st->raw_data;
598 
599 			return IIO_VAL_INT;
600 		}
601 		unreachable();
602 	case IIO_CHAN_INFO_SCALE:
603 		switch (chan->type) {
604 		case IIO_VOLTAGE:
605 			*val = st->vref_mv;
606 			*val2 = chan->scan_type.realbits;
607 			return IIO_VAL_FRACTIONAL_LOG2;
608 		case IIO_TEMP:
609 			/* T_scale (°C) = raw * V_REF (mV) / (-1.8 mV/°C * 2^16) */
610 			*val = st->vref_mv * -556;
611 			*val2 = 16;
612 			return IIO_VAL_FRACTIONAL_LOG2;
613 		default:
614 			return -EINVAL;
615 		}
616 	case IIO_CHAN_INFO_OFFSET:
617 		switch (chan->type) {
618 		case IIO_VOLTAGE:
619 			if (cfg->pin_pairing == AD4695_IN_PAIR_COM)
620 				*val = st->com_mv * (1 << realbits) / st->vref_mv;
621 			else if (cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD)
622 				*val = cfg->common_mode_mv * (1 << realbits) / st->vref_mv;
623 			else
624 				*val = 0;
625 
626 			return IIO_VAL_INT;
627 		case IIO_TEMP:
628 			/* T_offset (°C) = -725 mV / (-1.8 mV/°C) */
629 			/* T_offset (raw) = T_offset (°C) * (-1.8 mV/°C) * 2^16 / V_REF (mV) */
630 			*val = -47513600;
631 			*val2 = st->vref_mv;
632 			return IIO_VAL_FRACTIONAL;
633 		default:
634 			return -EINVAL;
635 		}
636 	default:
637 		return -EINVAL;
638 	}
639 }
640 
641 static int ad4695_debugfs_reg_access(struct iio_dev *indio_dev,
642 				     unsigned int reg,
643 				     unsigned int writeval,
644 				     unsigned int *readval)
645 {
646 	struct ad4695_state *st = iio_priv(indio_dev);
647 
648 	iio_device_claim_direct_scoped(return -EBUSY, indio_dev) {
649 		if (readval)
650 			return regmap_read(st->regmap, reg, readval);
651 
652 		return regmap_write(st->regmap, reg, writeval);
653 	}
654 
655 	unreachable();
656 }
657 
658 static const struct iio_info ad4695_info = {
659 	.read_raw = &ad4695_read_raw,
660 	.debugfs_reg_access = &ad4695_debugfs_reg_access,
661 };
662 
663 static int ad4695_parse_channel_cfg(struct ad4695_state *st)
664 {
665 	struct device *dev = &st->spi->dev;
666 	struct ad4695_channel_config *chan_cfg;
667 	struct iio_chan_spec *iio_chan;
668 	int ret, i;
669 
670 	/* populate defaults */
671 	for (i = 0; i < st->chip_info->num_voltage_inputs; i++) {
672 		chan_cfg = &st->channels_cfg[i];
673 		iio_chan = &st->iio_chan[i];
674 
675 		chan_cfg->highz_en = true;
676 		chan_cfg->channel = i;
677 
678 		*iio_chan = ad4695_channel_template;
679 		iio_chan->channel = i;
680 		iio_chan->scan_index = i;
681 		iio_chan->address = AD4695_CMD_VOLTAGE_CHAN(i);
682 	}
683 
684 	/* modify based on firmware description */
685 	device_for_each_child_node_scoped(dev, child) {
686 		u32 reg, val;
687 
688 		ret = fwnode_property_read_u32(child, "reg", &reg);
689 		if (ret)
690 			return dev_err_probe(dev, ret,
691 				"failed to read reg property (%s)\n",
692 				fwnode_get_name(child));
693 
694 		if (reg >= st->chip_info->num_voltage_inputs)
695 			return dev_err_probe(dev, -EINVAL,
696 				"reg out of range (%s)\n",
697 				fwnode_get_name(child));
698 
699 		iio_chan = &st->iio_chan[reg];
700 		chan_cfg = &st->channels_cfg[reg];
701 
702 		chan_cfg->highz_en =
703 			!fwnode_property_read_bool(child, "adi,no-high-z");
704 		chan_cfg->bipolar = fwnode_property_read_bool(child, "bipolar");
705 
706 		ret = fwnode_property_read_u32(child, "common-mode-channel",
707 					       &val);
708 		if (ret && ret != -EINVAL)
709 			return dev_err_probe(dev, ret,
710 				"failed to read common-mode-channel (%s)\n",
711 				fwnode_get_name(child));
712 
713 		if (ret == -EINVAL || val == AD4695_COMMON_MODE_REFGND)
714 			chan_cfg->pin_pairing = AD4695_IN_PAIR_REFGND;
715 		else if (val == AD4695_COMMON_MODE_COM)
716 			chan_cfg->pin_pairing = AD4695_IN_PAIR_COM;
717 		else
718 			chan_cfg->pin_pairing = AD4695_IN_PAIR_EVEN_ODD;
719 
720 		if (chan_cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD &&
721 		    val % 2 == 0)
722 			return dev_err_probe(dev, -EINVAL,
723 				"common-mode-channel must be odd number (%s)\n",
724 				fwnode_get_name(child));
725 
726 		if (chan_cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD &&
727 		    val != reg + 1)
728 			return dev_err_probe(dev, -EINVAL,
729 				"common-mode-channel must be next consecutive channel (%s)\n",
730 				fwnode_get_name(child));
731 
732 		if (chan_cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD) {
733 			char name[5];
734 
735 			snprintf(name, sizeof(name), "in%d", reg + 1);
736 
737 			ret = devm_regulator_get_enable_read_voltage(dev, name);
738 			if (ret < 0)
739 				return dev_err_probe(dev, ret,
740 					"failed to get %s voltage (%s)\n",
741 					name, fwnode_get_name(child));
742 
743 			chan_cfg->common_mode_mv = ret / 1000;
744 		}
745 
746 		if (chan_cfg->bipolar &&
747 		    chan_cfg->pin_pairing == AD4695_IN_PAIR_REFGND)
748 			return dev_err_probe(dev, -EINVAL,
749 				"bipolar mode is not available for inputs paired with REFGND (%s).\n",
750 				fwnode_get_name(child));
751 
752 		if (chan_cfg->bipolar)
753 			iio_chan->scan_type.sign = 's';
754 
755 		ret = ad4695_write_chn_cfg(st, chan_cfg);
756 		if (ret)
757 			return ret;
758 	}
759 
760 	/* Temperature channel must be next scan index after voltage channels. */
761 	st->iio_chan[i] = ad4695_temp_channel_template;
762 	st->iio_chan[i].scan_index = i;
763 	i++;
764 
765 	st->iio_chan[i] = ad4695_soft_timestamp_channel_template;
766 	st->iio_chan[i].scan_index = i;
767 
768 	return 0;
769 }
770 
771 static int ad4695_probe(struct spi_device *spi)
772 {
773 	struct device *dev = &spi->dev;
774 	struct ad4695_state *st;
775 	struct iio_dev *indio_dev;
776 	struct gpio_desc *cnv_gpio;
777 	bool use_internal_ldo_supply;
778 	bool use_internal_ref_buffer;
779 	int ret;
780 
781 	cnv_gpio = devm_gpiod_get_optional(dev, "cnv", GPIOD_OUT_LOW);
782 	if (IS_ERR(cnv_gpio))
783 		return dev_err_probe(dev, PTR_ERR(cnv_gpio),
784 				     "Failed to get CNV GPIO\n");
785 
786 	/* Driver currently requires CNV pin to be connected to SPI CS */
787 	if (cnv_gpio)
788 		return dev_err_probe(dev, -ENODEV,
789 				     "CNV GPIO is not supported\n");
790 
791 	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
792 	if (!indio_dev)
793 		return -ENOMEM;
794 
795 	st = iio_priv(indio_dev);
796 	st->spi = spi;
797 
798 	st->chip_info = spi_get_device_match_data(spi);
799 	if (!st->chip_info)
800 		return -EINVAL;
801 
802 	/* Registers cannot be read at the max allowable speed */
803 	spi->max_speed_hz = AD4695_REG_ACCESS_SCLK_HZ;
804 
805 	st->regmap = devm_regmap_init_spi(spi, &ad4695_regmap_config);
806 	if (IS_ERR(st->regmap))
807 		return dev_err_probe(dev, PTR_ERR(st->regmap),
808 				     "Failed to initialize regmap\n");
809 
810 	ret = devm_regulator_bulk_get_enable(dev,
811 					     ARRAY_SIZE(ad4695_power_supplies),
812 					     ad4695_power_supplies);
813 	if (ret)
814 		return dev_err_probe(dev, ret,
815 				     "Failed to enable power supplies\n");
816 
817 	/* If LDO_IN supply is present, then we are using internal LDO. */
818 	ret = devm_regulator_get_enable_optional(dev, "ldo-in");
819 	if (ret < 0 && ret != -ENODEV)
820 		return dev_err_probe(dev, ret,
821 				     "Failed to enable LDO_IN supply\n");
822 
823 	use_internal_ldo_supply = ret == 0;
824 
825 	if (!use_internal_ldo_supply) {
826 		/* Otherwise we need an external VDD supply. */
827 		ret = devm_regulator_get_enable(dev, "vdd");
828 		if (ret < 0)
829 			return dev_err_probe(dev, ret,
830 					     "Failed to enable VDD supply\n");
831 	}
832 
833 	/* If REFIN supply is given, then we are using internal buffer */
834 	ret = devm_regulator_get_enable_read_voltage(dev, "refin");
835 	if (ret < 0 && ret != -ENODEV)
836 		return dev_err_probe(dev, ret, "Failed to get REFIN voltage\n");
837 
838 	if (ret != -ENODEV) {
839 		st->vref_mv = ret / 1000;
840 		use_internal_ref_buffer = true;
841 	} else {
842 		/* Otherwise, we need an external reference. */
843 		ret = devm_regulator_get_enable_read_voltage(dev, "ref");
844 		if (ret < 0)
845 			return dev_err_probe(dev, ret,
846 					     "Failed to get REF voltage\n");
847 
848 		st->vref_mv = ret / 1000;
849 		use_internal_ref_buffer = false;
850 	}
851 
852 	ret = devm_regulator_get_enable_read_voltage(dev, "com");
853 	if (ret < 0 && ret != -ENODEV)
854 		return dev_err_probe(dev, ret, "Failed to get COM voltage\n");
855 
856 	st->com_mv = ret == -ENODEV ? 0 : ret / 1000;
857 
858 	/*
859 	 * Reset the device using hardware reset if available or fall back to
860 	 * software reset.
861 	 */
862 
863 	st->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH);
864 	if (IS_ERR(st->reset_gpio))
865 		return PTR_ERR(st->reset_gpio);
866 
867 	if (st->reset_gpio) {
868 		gpiod_set_value(st->reset_gpio, 0);
869 		msleep(AD4695_T_WAKEUP_HW_MS);
870 	} else {
871 		ret = regmap_write(st->regmap, AD4695_REG_SPI_CONFIG_A,
872 				   AD4695_REG_SPI_CONFIG_A_SW_RST);
873 		if (ret)
874 			return ret;
875 
876 		msleep(AD4695_T_WAKEUP_SW_MS);
877 	}
878 
879 	/* Needed for debugfs since it only access registers 1 byte at a time. */
880 	ret = regmap_set_bits(st->regmap, AD4695_REG_SPI_CONFIG_C,
881 			      AD4695_REG_SPI_CONFIG_C_MB_STRICT);
882 	if (ret)
883 		return ret;
884 
885 	/* Disable internal LDO if it isn't needed. */
886 	ret = regmap_update_bits(st->regmap, AD4695_REG_SETUP,
887 				 AD4695_REG_SETUP_LDO_EN,
888 				 FIELD_PREP(AD4695_REG_SETUP_LDO_EN,
889 					    use_internal_ldo_supply ? 1 : 0));
890 	if (ret)
891 		return ret;
892 
893 	/* configure reference supply */
894 
895 	if (device_property_present(dev, "adi,no-ref-current-limit")) {
896 		ret = regmap_set_bits(st->regmap, AD4695_REG_REF_CTRL,
897 				      AD4695_REG_REF_CTRL_OV_MODE);
898 		if (ret)
899 			return ret;
900 	}
901 
902 	if (device_property_present(dev, "adi,no-ref-high-z")) {
903 		if (use_internal_ref_buffer)
904 			return dev_err_probe(dev, -EINVAL,
905 				"Cannot disable high-Z mode for internal reference buffer\n");
906 
907 		ret = regmap_clear_bits(st->regmap, AD4695_REG_REF_CTRL,
908 					AD4695_REG_REF_CTRL_REFHIZ_EN);
909 		if (ret)
910 			return ret;
911 	}
912 
913 	ret = ad4695_set_ref_voltage(st, st->vref_mv);
914 	if (ret)
915 		return ret;
916 
917 	if (use_internal_ref_buffer) {
918 		ret = regmap_set_bits(st->regmap, AD4695_REG_REF_CTRL,
919 				      AD4695_REG_REF_CTRL_REFBUF_EN);
920 		if (ret)
921 			return ret;
922 
923 		/* Give the capacitor some time to charge up. */
924 		msleep(AD4695_T_REFBUF_MS);
925 	}
926 
927 	ret = ad4695_parse_channel_cfg(st);
928 	if (ret)
929 		return ret;
930 
931 	indio_dev->name = st->chip_info->name;
932 	indio_dev->info = &ad4695_info;
933 	indio_dev->modes = INDIO_DIRECT_MODE;
934 	indio_dev->channels = st->iio_chan;
935 	indio_dev->num_channels = st->chip_info->num_voltage_inputs + 2;
936 
937 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
938 					      iio_pollfunc_store_time,
939 					      ad4695_trigger_handler,
940 					      &ad4695_buffer_setup_ops);
941 	if (ret)
942 		return ret;
943 
944 	return devm_iio_device_register(dev, indio_dev);
945 }
946 
947 static const struct spi_device_id ad4695_spi_id_table[] = {
948 	{ .name = "ad4695", .driver_data = (kernel_ulong_t)&ad4695_chip_info },
949 	{ .name = "ad4696", .driver_data = (kernel_ulong_t)&ad4696_chip_info },
950 	{ .name = "ad4697", .driver_data = (kernel_ulong_t)&ad4697_chip_info },
951 	{ .name = "ad4698", .driver_data = (kernel_ulong_t)&ad4698_chip_info },
952 	{ }
953 };
954 MODULE_DEVICE_TABLE(spi, ad4695_spi_id_table);
955 
956 static const struct of_device_id ad4695_of_match_table[] = {
957 	{ .compatible = "adi,ad4695", .data = &ad4695_chip_info, },
958 	{ .compatible = "adi,ad4696", .data = &ad4696_chip_info, },
959 	{ .compatible = "adi,ad4697", .data = &ad4697_chip_info, },
960 	{ .compatible = "adi,ad4698", .data = &ad4698_chip_info, },
961 	{ }
962 };
963 MODULE_DEVICE_TABLE(of, ad4695_of_match_table);
964 
965 static struct spi_driver ad4695_driver = {
966 	.driver = {
967 		.name = "ad4695",
968 		.of_match_table = ad4695_of_match_table,
969 	},
970 	.probe = ad4695_probe,
971 	.id_table = ad4695_spi_id_table,
972 };
973 module_spi_driver(ad4695_driver);
974 
975 MODULE_AUTHOR("Ramona Gradinariu <ramona.gradinariu@analog.com>");
976 MODULE_AUTHOR("David Lechner <dlechner@baylibre.com>");
977 MODULE_DESCRIPTION("Analog Devices AD4695 ADC driver");
978 MODULE_LICENSE("GPL");
979