xref: /linux/drivers/iio/adc/ad7380.c (revision cd188e9ef80fd005fd8c8de34ed649bd653d00e5)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Analog Devices AD738x Simultaneous Sampling SAR ADCs
4  *
5  * Copyright 2017 Analog Devices Inc.
6  * Copyright 2024 BayLibre, SAS
7  *
8  * Datasheets of supported parts:
9  * ad7380/1 : https://www.analog.com/media/en/technical-documentation/data-sheets/AD7380-7381.pdf
10  * ad7383/4 : https://www.analog.com/media/en/technical-documentation/data-sheets/ad7383-7384.pdf
11  * ad7386/7/8 : https://www.analog.com/media/en/technical-documentation/data-sheets/AD7386-7387-7388.pdf
12  * ad7380-4 : https://www.analog.com/media/en/technical-documentation/data-sheets/ad7380-4.pdf
13  * ad7381-4 : https://www.analog.com/media/en/technical-documentation/data-sheets/ad7381-4.pdf
14  * ad7383/4-4 : https://www.analog.com/media/en/technical-documentation/data-sheets/ad7383-4-ad7384-4.pdf
15  * ad7386/7/8-4 : https://www.analog.com/media/en/technical-documentation/data-sheets/ad7386-4-7387-4-7388-4.pdf
16  * adaq4370-4 : https://www.analog.com/media/en/technical-documentation/data-sheets/adaq4370-4.pdf
17  * adaq4380-4 : https://www.analog.com/media/en/technical-documentation/data-sheets/adaq4380-4.pdf
18  * adaq4381-4 : https://www.analog.com/media/en/technical-documentation/data-sheets/adaq4381-4.pdf
19  *
20  * HDL ad738x_fmc: https://analogdevicesinc.github.io/hdl/projects/ad738x_fmc/index.html
21  *
22  */
23 
24 #include <linux/align.h>
25 #include <linux/bitfield.h>
26 #include <linux/bitops.h>
27 #include <linux/cleanup.h>
28 #include <linux/device.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/math.h>
32 #include <linux/module.h>
33 #include <linux/regmap.h>
34 #include <linux/regulator/consumer.h>
35 #include <linux/slab.h>
36 #include <linux/spi/offload/consumer.h>
37 #include <linux/spi/spi.h>
38 #include <linux/units.h>
39 #include <linux/util_macros.h>
40 
41 #include <linux/iio/buffer.h>
42 #include <linux/iio/buffer-dmaengine.h>
43 #include <linux/iio/events.h>
44 #include <linux/iio/iio.h>
45 #include <linux/iio/trigger_consumer.h>
46 #include <linux/iio/triggered_buffer.h>
47 
48 #define MAX_NUM_CHANNELS		8
49 /* 2.5V internal reference voltage */
50 #define AD7380_INTERNAL_REF_MV		2500
51 /* 3.3V internal reference voltage for ADAQ */
52 #define ADAQ4380_INTERNAL_REF_MV	3300
53 
54 /* reading and writing registers is more reliable at lower than max speed */
55 #define AD7380_REG_WR_SPEED_HZ		10000000
56 
57 #define AD7380_REG_WR			BIT(15)
58 #define AD7380_REG_REGADDR		GENMASK(14, 12)
59 #define AD7380_REG_DATA			GENMASK(11, 0)
60 
61 #define AD7380_REG_ADDR_NOP		0x0
62 #define AD7380_REG_ADDR_CONFIG1		0x1
63 #define AD7380_REG_ADDR_CONFIG2		0x2
64 #define AD7380_REG_ADDR_ALERT		0x3
65 #define AD7380_REG_ADDR_ALERT_LOW_TH	0x4
66 #define AD7380_REG_ADDR_ALERT_HIGH_TH	0x5
67 
68 #define AD7380_CONFIG1_CH		BIT(11)
69 #define AD7380_CONFIG1_SEQ		BIT(10)
70 #define AD7380_CONFIG1_OS_MODE		BIT(9)
71 #define AD7380_CONFIG1_OSR		GENMASK(8, 6)
72 #define AD7380_CONFIG1_CRC_W		BIT(5)
73 #define AD7380_CONFIG1_CRC_R		BIT(4)
74 #define AD7380_CONFIG1_ALERTEN		BIT(3)
75 #define AD7380_CONFIG1_RES		BIT(2)
76 #define AD7380_CONFIG1_REFSEL		BIT(1)
77 #define AD7380_CONFIG1_PMODE		BIT(0)
78 
79 #define AD7380_CONFIG2_SDO2		GENMASK(9, 8)
80 #define AD7380_CONFIG2_SDO		BIT(8)
81 #define AD7380_CONFIG2_RESET		GENMASK(7, 0)
82 
83 #define AD7380_CONFIG2_RESET_SOFT	0x3C
84 #define AD7380_CONFIG2_RESET_HARD	0xFF
85 
86 #define AD7380_ALERT_LOW_TH		GENMASK(11, 0)
87 #define AD7380_ALERT_HIGH_TH		GENMASK(11, 0)
88 
89 #define T_CONVERT_NS 190		/* conversion time */
90 #define T_CONVERT_0_NS 10		/* 1st conversion start time (oversampling) */
91 #define T_CONVERT_X_NS 500		/* xth conversion start time (oversampling) */
92 #define T_POWERUP_US 5000		/* Power up */
93 
94 /*
95  * AD738x support several SDO lines to increase throughput, but driver currently
96  * supports only 1 SDO line (standard SPI transaction)
97  */
98 #define AD7380_NUM_SDO_LINES		1
99 #define AD7380_DEFAULT_GAIN_MILLI	1000
100 
101 /*
102  * Using SPI offload, storagebits is always 32, so can't be used to compute struct
103  * spi_transfer.len. Using realbits instead.
104  */
105 #define AD7380_SPI_BYTES(scan_type)	((scan_type)->realbits > 16 ? 4 : 2)
106 
107 struct ad7380_timing_specs {
108 	const unsigned int t_csh_ns;	/* CS minimum high time */
109 };
110 
111 struct ad7380_chip_info {
112 	const char *name;
113 	const struct iio_chan_spec *channels;
114 	const struct iio_chan_spec *offload_channels;
115 	unsigned int num_channels;
116 	unsigned int num_simult_channels;
117 	bool has_hardware_gain;
118 	bool has_mux;
119 	const char * const *supplies;
120 	unsigned int num_supplies;
121 	bool external_ref_only;
122 	bool adaq_internal_ref_only;
123 	const char * const *vcm_supplies;
124 	unsigned int num_vcm_supplies;
125 	const unsigned long *available_scan_masks;
126 	const struct ad7380_timing_specs *timing_specs;
127 	u32 max_conversion_rate_hz;
128 };
129 
130 static const struct iio_event_spec ad7380_events[] = {
131 	{
132 		.type = IIO_EV_TYPE_THRESH,
133 		.dir = IIO_EV_DIR_RISING,
134 		.mask_shared_by_dir = BIT(IIO_EV_INFO_VALUE),
135 	},
136 	{
137 		.type = IIO_EV_TYPE_THRESH,
138 		.dir = IIO_EV_DIR_FALLING,
139 		.mask_shared_by_dir = BIT(IIO_EV_INFO_VALUE),
140 	},
141 	{
142 		.type = IIO_EV_TYPE_THRESH,
143 		.dir = IIO_EV_DIR_EITHER,
144 		.mask_shared_by_all = BIT(IIO_EV_INFO_ENABLE),
145 	},
146 };
147 
148 enum {
149 	AD7380_SCAN_TYPE_NORMAL,
150 	AD7380_SCAN_TYPE_RESOLUTION_BOOST,
151 };
152 
153 /* Extended scan types for 12-bit unsigned chips. */
154 static const struct iio_scan_type ad7380_scan_type_12_u[] = {
155 	[AD7380_SCAN_TYPE_NORMAL] = {
156 		.sign = 'u',
157 		.realbits = 12,
158 		.storagebits = 16,
159 		.endianness = IIO_CPU,
160 	},
161 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
162 		.sign = 'u',
163 		.realbits = 14,
164 		.storagebits = 16,
165 		.endianness = IIO_CPU,
166 	},
167 };
168 
169 /* Extended scan types for 14-bit signed chips. */
170 static const struct iio_scan_type ad7380_scan_type_14_s[] = {
171 	[AD7380_SCAN_TYPE_NORMAL] = {
172 		.sign = 's',
173 		.realbits = 14,
174 		.storagebits = 16,
175 		.endianness = IIO_CPU,
176 	},
177 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
178 		.sign = 's',
179 		.realbits = 16,
180 		.storagebits = 16,
181 		.endianness = IIO_CPU,
182 	},
183 };
184 
185 /* Extended scan types for 14-bit unsigned chips. */
186 static const struct iio_scan_type ad7380_scan_type_14_u[] = {
187 	[AD7380_SCAN_TYPE_NORMAL] = {
188 		.sign = 'u',
189 		.realbits = 14,
190 		.storagebits = 16,
191 		.endianness = IIO_CPU,
192 	},
193 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
194 		.sign = 'u',
195 		.realbits = 16,
196 		.storagebits = 16,
197 		.endianness = IIO_CPU,
198 	},
199 };
200 
201 /* Extended scan types for 16-bit signed_chips. */
202 static const struct iio_scan_type ad7380_scan_type_16_s[] = {
203 	[AD7380_SCAN_TYPE_NORMAL] = {
204 		.sign = 's',
205 		.realbits = 16,
206 		.storagebits = 16,
207 		.endianness = IIO_CPU,
208 	},
209 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
210 		.sign = 's',
211 		.realbits = 18,
212 		.storagebits = 32,
213 		.endianness = IIO_CPU,
214 	},
215 };
216 
217 /* Extended scan types for 16-bit unsigned chips. */
218 static const struct iio_scan_type ad7380_scan_type_16_u[] = {
219 	[AD7380_SCAN_TYPE_NORMAL] = {
220 		.sign = 'u',
221 		.realbits = 16,
222 		.storagebits = 16,
223 		.endianness = IIO_CPU,
224 	},
225 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
226 		.sign = 'u',
227 		.realbits = 18,
228 		.storagebits = 32,
229 		.endianness = IIO_CPU,
230 	},
231 };
232 
233 /*
234  * Defining here scan types for offload mode, since with current available HDL
235  * only a value of 32 for storagebits is supported.
236  */
237 
238 /* Extended scan types for 12-bit unsigned chips, offload support. */
239 static const struct iio_scan_type ad7380_scan_type_12_u_offload[] = {
240 	[AD7380_SCAN_TYPE_NORMAL] = {
241 		.sign = 'u',
242 		.realbits = 12,
243 		.storagebits = 32,
244 		.endianness = IIO_CPU,
245 	},
246 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
247 		.sign = 'u',
248 		.realbits = 14,
249 		.storagebits = 32,
250 		.endianness = IIO_CPU,
251 	},
252 };
253 
254 /* Extended scan types for 14-bit signed chips, offload support. */
255 static const struct iio_scan_type ad7380_scan_type_14_s_offload[] = {
256 	[AD7380_SCAN_TYPE_NORMAL] = {
257 		.sign = 's',
258 		.realbits = 14,
259 		.storagebits = 32,
260 		.endianness = IIO_CPU,
261 	},
262 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
263 		.sign = 's',
264 		.realbits = 16,
265 		.storagebits = 32,
266 		.endianness = IIO_CPU,
267 	},
268 };
269 
270 /* Extended scan types for 14-bit unsigned chips, offload support. */
271 static const struct iio_scan_type ad7380_scan_type_14_u_offload[] = {
272 	[AD7380_SCAN_TYPE_NORMAL] = {
273 		.sign = 'u',
274 		.realbits = 14,
275 		.storagebits = 32,
276 		.endianness = IIO_CPU,
277 	},
278 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
279 		.sign = 'u',
280 		.realbits = 16,
281 		.storagebits = 32,
282 		.endianness = IIO_CPU,
283 	},
284 };
285 
286 /* Extended scan types for 16-bit signed_chips, offload support. */
287 static const struct iio_scan_type ad7380_scan_type_16_s_offload[] = {
288 	[AD7380_SCAN_TYPE_NORMAL] = {
289 		.sign = 's',
290 		.realbits = 16,
291 		.storagebits = 32,
292 		.endianness = IIO_CPU,
293 	},
294 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
295 		.sign = 's',
296 		.realbits = 18,
297 		.storagebits = 32,
298 		.endianness = IIO_CPU,
299 	},
300 };
301 
302 /* Extended scan types for 16-bit unsigned chips, offload support. */
303 static const struct iio_scan_type ad7380_scan_type_16_u_offload[] = {
304 	[AD7380_SCAN_TYPE_NORMAL] = {
305 		.sign = 'u',
306 		.realbits = 16,
307 		.storagebits = 32,
308 		.endianness = IIO_CPU,
309 	},
310 	[AD7380_SCAN_TYPE_RESOLUTION_BOOST] = {
311 		.sign = 'u',
312 		.realbits = 18,
313 		.storagebits = 32,
314 		.endianness = IIO_CPU,
315 	},
316 };
317 
318 #define _AD7380_CHANNEL(index, bits, diff, sign, gain) {			\
319 	.type = IIO_VOLTAGE,							\
320 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |				\
321 		((gain) ? BIT(IIO_CHAN_INFO_SCALE) : 0) |			\
322 		((diff) ? 0 : BIT(IIO_CHAN_INFO_OFFSET)),			\
323 	.info_mask_shared_by_type = ((gain) ? 0 : BIT(IIO_CHAN_INFO_SCALE)) |	\
324 		BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),				\
325 	.info_mask_shared_by_type_available =					\
326 		BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),				\
327 	.indexed = 1,								\
328 	.differential = (diff),							\
329 	.channel = (diff) ? (2 * (index)) : (index),				\
330 	.channel2 = (diff) ? (2 * (index) + 1) : 0,				\
331 	.scan_index = (index),							\
332 	.has_ext_scan_type = 1,							\
333 	.ext_scan_type = ad7380_scan_type_##bits##_##sign,			\
334 	.num_ext_scan_type = ARRAY_SIZE(ad7380_scan_type_##bits##_##sign),	\
335 	.event_spec = ad7380_events,						\
336 	.num_event_specs = ARRAY_SIZE(ad7380_events),				\
337 }
338 
339 #define _AD7380_OFFLOAD_CHANNEL(index, bits, diff, sign, gain) {		\
340 	.type = IIO_VOLTAGE,							\
341 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |                          \
342 		((gain) ? BIT(IIO_CHAN_INFO_SCALE) : 0) |			\
343 		((diff) ? 0 : BIT(IIO_CHAN_INFO_OFFSET)),			\
344 	.info_mask_shared_by_type = ((gain) ? 0 : BIT(IIO_CHAN_INFO_SCALE)) |   \
345 		BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |				\
346 		BIT(IIO_CHAN_INFO_SAMP_FREQ),					\
347 	.info_mask_shared_by_type_available =					\
348 		BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO) |				\
349 		BIT(IIO_CHAN_INFO_SAMP_FREQ),					\
350 	.indexed = 1,                                                           \
351 	.differential = (diff),                                                 \
352 	.channel = (diff) ? (2 * (index)) : (index),                            \
353 	.channel2 = (diff) ? (2 * (index) + 1) : 0,                             \
354 	.scan_index = (index),                                                  \
355 	.has_ext_scan_type = 1,                                                 \
356 	.ext_scan_type = ad7380_scan_type_##bits##_##sign##_offload,            \
357 	.num_ext_scan_type =                                                    \
358 		ARRAY_SIZE(ad7380_scan_type_##bits##_##sign##_offload),		\
359 	.event_spec = ad7380_events,                                            \
360 	.num_event_specs = ARRAY_SIZE(ad7380_events),                           \
361 }
362 
363 /*
364  * Notes on the offload channels:
365  * - There is no soft timestamp since everything is done in hardware.
366  * - There is a sampling frequency attribute added. This controls the SPI
367  *   offload trigger.
368  * - The storagebits value depends on the SPI offload provider. Currently there
369  *   is only one supported provider, namely the ADI PULSAR ADC HDL project,
370  *   which always uses 32-bit words for data values, even for <= 16-bit ADCs.
371  *   So the value is just hardcoded to 32 for now.
372  */
373 
374 #define AD7380_CHANNEL(index, bits, diff, sign)		\
375 	_AD7380_CHANNEL(index, bits, diff, sign, false)
376 
377 #define ADAQ4380_CHANNEL(index, bits, diff, sign)	\
378 	_AD7380_CHANNEL(index, bits, diff, sign, true)
379 
380 #define DEFINE_AD7380_2_CHANNEL(name, bits, diff, sign) \
381 static const struct iio_chan_spec name[] = {	\
382 	AD7380_CHANNEL(0, bits, diff, sign),	\
383 	AD7380_CHANNEL(1, bits, diff, sign),	\
384 	IIO_CHAN_SOFT_TIMESTAMP(2),		\
385 }
386 
387 #define DEFINE_AD7380_4_CHANNEL(name, bits, diff, sign) \
388 static const struct iio_chan_spec name[] = {	\
389 	 AD7380_CHANNEL(0, bits, diff, sign),	\
390 	 AD7380_CHANNEL(1, bits, diff, sign),	\
391 	 AD7380_CHANNEL(2, bits, diff, sign),	\
392 	 AD7380_CHANNEL(3, bits, diff, sign),	\
393 	 IIO_CHAN_SOFT_TIMESTAMP(4),		\
394 }
395 
396 #define DEFINE_ADAQ4380_4_CHANNEL(name, bits, diff, sign) \
397 static const struct iio_chan_spec name[] = {	\
398 	 ADAQ4380_CHANNEL(0, bits, diff, sign),	\
399 	 ADAQ4380_CHANNEL(1, bits, diff, sign),	\
400 	 ADAQ4380_CHANNEL(2, bits, diff, sign),	\
401 	 ADAQ4380_CHANNEL(3, bits, diff, sign),	\
402 	 IIO_CHAN_SOFT_TIMESTAMP(4),		\
403 }
404 
405 #define DEFINE_AD7380_8_CHANNEL(name, bits, diff, sign) \
406 static const struct iio_chan_spec name[] = {	\
407 	 AD7380_CHANNEL(0, bits, diff, sign),	\
408 	 AD7380_CHANNEL(1, bits, diff, sign),	\
409 	 AD7380_CHANNEL(2, bits, diff, sign),	\
410 	 AD7380_CHANNEL(3, bits, diff, sign),	\
411 	 AD7380_CHANNEL(4, bits, diff, sign),	\
412 	 AD7380_CHANNEL(5, bits, diff, sign),	\
413 	 AD7380_CHANNEL(6, bits, diff, sign),	\
414 	 AD7380_CHANNEL(7, bits, diff, sign),	\
415 	 IIO_CHAN_SOFT_TIMESTAMP(8),		\
416 }
417 
418 #define AD7380_OFFLOAD_CHANNEL(index, bits, diff, sign) \
419 _AD7380_OFFLOAD_CHANNEL(index, bits, diff, sign, false)
420 
421 #define ADAQ4380_OFFLOAD_CHANNEL(index, bits, diff, sign) \
422 _AD7380_OFFLOAD_CHANNEL(index, bits, diff, sign, true)
423 
424 #define DEFINE_AD7380_2_OFFLOAD_CHANNEL(name, bits, diff, sign) \
425 static const struct iio_chan_spec name[] = {		\
426 	AD7380_OFFLOAD_CHANNEL(0, bits, diff, sign),	\
427 	AD7380_OFFLOAD_CHANNEL(1, bits, diff, sign),	\
428 }
429 
430 #define DEFINE_AD7380_4_OFFLOAD_CHANNEL(name, bits, diff, sign) \
431 static const struct iio_chan_spec name[] = {		\
432 	AD7380_OFFLOAD_CHANNEL(0, bits, diff, sign),	\
433 	AD7380_OFFLOAD_CHANNEL(1, bits, diff, sign),	\
434 	AD7380_OFFLOAD_CHANNEL(2, bits, diff, sign),	\
435 	AD7380_OFFLOAD_CHANNEL(3, bits, diff, sign),	\
436 }
437 
438 #define DEFINE_ADAQ4380_4_OFFLOAD_CHANNEL(name, bits, diff, sign) \
439 static const struct iio_chan_spec name[] = {		\
440 	AD7380_OFFLOAD_CHANNEL(0, bits, diff, sign),	\
441 	AD7380_OFFLOAD_CHANNEL(1, bits, diff, sign),	\
442 	AD7380_OFFLOAD_CHANNEL(2, bits, diff, sign),	\
443 	AD7380_OFFLOAD_CHANNEL(3, bits, diff, sign),	\
444 }
445 
446 #define DEFINE_AD7380_8_OFFLOAD_CHANNEL(name, bits, diff, sign) \
447 static const struct iio_chan_spec name[] = {		\
448 	AD7380_OFFLOAD_CHANNEL(0, bits, diff, sign),	\
449 	AD7380_OFFLOAD_CHANNEL(1, bits, diff, sign),	\
450 	AD7380_OFFLOAD_CHANNEL(2, bits, diff, sign),	\
451 	AD7380_OFFLOAD_CHANNEL(3, bits, diff, sign),	\
452 	AD7380_OFFLOAD_CHANNEL(4, bits, diff, sign),	\
453 	AD7380_OFFLOAD_CHANNEL(5, bits, diff, sign),	\
454 	AD7380_OFFLOAD_CHANNEL(6, bits, diff, sign),	\
455 	AD7380_OFFLOAD_CHANNEL(7, bits, diff, sign),	\
456 }
457 
458 /* fully differential */
459 DEFINE_AD7380_2_CHANNEL(ad7380_channels, 16, 1, s);
460 DEFINE_AD7380_2_CHANNEL(ad7381_channels, 14, 1, s);
461 DEFINE_AD7380_4_CHANNEL(ad7380_4_channels, 16, 1, s);
462 DEFINE_AD7380_4_CHANNEL(ad7381_4_channels, 14, 1, s);
463 DEFINE_ADAQ4380_4_CHANNEL(adaq4380_4_channels, 16, 1, s);
464 DEFINE_ADAQ4380_4_CHANNEL(adaq4381_4_channels, 14, 1, s);
465 /* pseudo differential */
466 DEFINE_AD7380_2_CHANNEL(ad7383_channels, 16, 0, s);
467 DEFINE_AD7380_2_CHANNEL(ad7384_channels, 14, 0, s);
468 DEFINE_AD7380_4_CHANNEL(ad7383_4_channels, 16, 0, s);
469 DEFINE_AD7380_4_CHANNEL(ad7384_4_channels, 14, 0, s);
470 
471 /* Single ended */
472 DEFINE_AD7380_4_CHANNEL(ad7386_channels, 16, 0, u);
473 DEFINE_AD7380_4_CHANNEL(ad7387_channels, 14, 0, u);
474 DEFINE_AD7380_4_CHANNEL(ad7388_channels, 12, 0, u);
475 DEFINE_AD7380_8_CHANNEL(ad7386_4_channels, 16, 0, u);
476 DEFINE_AD7380_8_CHANNEL(ad7387_4_channels, 14, 0, u);
477 DEFINE_AD7380_8_CHANNEL(ad7388_4_channels, 12, 0, u);
478 
479 /* offload channels */
480 DEFINE_AD7380_2_OFFLOAD_CHANNEL(ad7380_offload_channels, 16, 1, s);
481 DEFINE_AD7380_2_OFFLOAD_CHANNEL(ad7381_offload_channels, 14, 1, s);
482 DEFINE_AD7380_4_OFFLOAD_CHANNEL(ad7380_4_offload_channels, 16, 1, s);
483 DEFINE_AD7380_4_OFFLOAD_CHANNEL(ad7381_4_offload_channels, 14, 1, s);
484 DEFINE_ADAQ4380_4_OFFLOAD_CHANNEL(adaq4380_4_offload_channels, 16, 1, s);
485 DEFINE_ADAQ4380_4_OFFLOAD_CHANNEL(adaq4381_4_offload_channels, 14, 1, s);
486 
487 /* pseudo differential */
488 DEFINE_AD7380_2_OFFLOAD_CHANNEL(ad7383_offload_channels, 16, 0, s);
489 DEFINE_AD7380_2_OFFLOAD_CHANNEL(ad7384_offload_channels, 14, 0, s);
490 DEFINE_AD7380_4_OFFLOAD_CHANNEL(ad7383_4_offload_channels, 16, 0, s);
491 DEFINE_AD7380_4_OFFLOAD_CHANNEL(ad7384_4_offload_channels, 14, 0, s);
492 
493 /* Single ended */
494 DEFINE_AD7380_4_OFFLOAD_CHANNEL(ad7386_offload_channels, 16, 0, u);
495 DEFINE_AD7380_4_OFFLOAD_CHANNEL(ad7387_offload_channels, 14, 0, u);
496 DEFINE_AD7380_4_OFFLOAD_CHANNEL(ad7388_offload_channels, 12, 0, u);
497 DEFINE_AD7380_8_OFFLOAD_CHANNEL(ad7386_4_offload_channels, 16, 0, u);
498 DEFINE_AD7380_8_OFFLOAD_CHANNEL(ad7387_4_offload_channels, 14, 0, u);
499 DEFINE_AD7380_8_OFFLOAD_CHANNEL(ad7388_4_offload_channels, 12, 0, u);
500 
501 static const char * const ad7380_supplies[] = {
502 	"vcc", "vlogic",
503 };
504 
505 static const char * const adaq4380_supplies[] = {
506 	"ldo", "vcc", "vlogic", "vs-p", "vs-n", "refin",
507 };
508 
509 static const char * const ad7380_2_channel_vcm_supplies[] = {
510 	"aina", "ainb",
511 };
512 
513 static const char * const ad7380_4_channel_vcm_supplies[] = {
514 	"aina", "ainb", "ainc", "aind",
515 };
516 
517 /* Since this is simultaneous sampling, we don't allow individual channels. */
518 static const unsigned long ad7380_2_channel_scan_masks[] = {
519 	GENMASK(1, 0),
520 	0
521 };
522 
523 static const unsigned long ad7380_4_channel_scan_masks[] = {
524 	GENMASK(3, 0),
525 	0
526 };
527 
528 /*
529  * Single ended parts have a 2:1 multiplexer in front of each ADC.
530  *
531  * From an IIO point of view, all inputs are exported, i.e ad7386/7/8
532  * export 4 channels and ad7386-4/7-4/8-4 export 8 channels.
533  *
534  * Inputs AinX0 of multiplexers correspond to the first half of IIO channels
535  * (i.e 0-1 or 0-3) and inputs AinX1 correspond to second half (i.e 2-3 or
536  * 4-7). Example for AD7386/7/8 (2 channels parts):
537  *
538  *           IIO   | AD7386/7/8
539  *                 |         +----------------------------
540  *                 |         |     _____        ______
541  *                 |         |    |     |      |      |
542  *        voltage0 | AinA0 --|--->|     |      |      |
543  *                 |         |    | mux |----->| ADCA |---
544  *        voltage2 | AinA1 --|--->|     |      |      |
545  *                 |         |    |_____|      |_____ |
546  *                 |         |     _____        ______
547  *                 |         |    |     |      |      |
548  *        voltage1 | AinB0 --|--->|     |      |      |
549  *                 |         |    | mux |----->| ADCB |---
550  *        voltage3 | AinB1 --|--->|     |      |      |
551  *                 |         |    |_____|      |______|
552  *                 |         |
553  *                 |         +----------------------------
554  *
555  * Since this is simultaneous sampling for AinX0 OR AinX1 we have two separate
556  * scan masks.
557  * When sequencer mode is enabled, chip automatically cycles through
558  * AinX0 and AinX1 channels. From an IIO point of view, we ca enable all
559  * channels, at the cost of an extra read, thus dividing the maximum rate by
560  * two.
561  */
562 enum {
563 	AD7380_SCAN_MASK_CH_0,
564 	AD7380_SCAN_MASK_CH_1,
565 	AD7380_SCAN_MASK_SEQ,
566 };
567 
568 static const unsigned long ad7380_2x2_channel_scan_masks[] = {
569 	[AD7380_SCAN_MASK_CH_0] = GENMASK(1, 0),
570 	[AD7380_SCAN_MASK_CH_1] = GENMASK(3, 2),
571 	[AD7380_SCAN_MASK_SEQ] = GENMASK(3, 0),
572 	0
573 };
574 
575 static const unsigned long ad7380_2x4_channel_scan_masks[] = {
576 	[AD7380_SCAN_MASK_CH_0] = GENMASK(3, 0),
577 	[AD7380_SCAN_MASK_CH_1] = GENMASK(7, 4),
578 	[AD7380_SCAN_MASK_SEQ] = GENMASK(7, 0),
579 	0
580 };
581 
582 static const struct ad7380_timing_specs ad7380_timing = {
583 	.t_csh_ns = 10,
584 };
585 
586 static const struct ad7380_timing_specs ad7380_4_timing = {
587 	.t_csh_ns = 20,
588 };
589 
590 /*
591  * Available oversampling ratios. The indices correspond with the bit value
592  * expected by the chip.  The available ratios depend on the averaging mode,
593  * only normal averaging is supported for now.
594  */
595 static const int ad7380_oversampling_ratios[] = {
596 	1, 2, 4, 8, 16, 32,
597 };
598 
599 /* Gains stored as fractions of 1000 so they can be expressed by integers. */
600 static const int ad7380_gains[] = {
601 	300, 600, 1000, 1600,
602 };
603 
604 static const struct ad7380_chip_info ad7380_chip_info = {
605 	.name = "ad7380",
606 	.channels = ad7380_channels,
607 	.offload_channels = ad7380_offload_channels,
608 	.num_channels = ARRAY_SIZE(ad7380_channels),
609 	.num_simult_channels = 2,
610 	.supplies = ad7380_supplies,
611 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
612 	.available_scan_masks = ad7380_2_channel_scan_masks,
613 	.timing_specs = &ad7380_timing,
614 	.max_conversion_rate_hz = 4 * MEGA,
615 };
616 
617 static const struct ad7380_chip_info ad7381_chip_info = {
618 	.name = "ad7381",
619 	.channels = ad7381_channels,
620 	.offload_channels = ad7381_offload_channels,
621 	.num_channels = ARRAY_SIZE(ad7381_channels),
622 	.num_simult_channels = 2,
623 	.supplies = ad7380_supplies,
624 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
625 	.available_scan_masks = ad7380_2_channel_scan_masks,
626 	.timing_specs = &ad7380_timing,
627 	.max_conversion_rate_hz = 4 * MEGA,
628 };
629 
630 static const struct ad7380_chip_info ad7383_chip_info = {
631 	.name = "ad7383",
632 	.channels = ad7383_channels,
633 	.offload_channels = ad7383_offload_channels,
634 	.num_channels = ARRAY_SIZE(ad7383_channels),
635 	.num_simult_channels = 2,
636 	.supplies = ad7380_supplies,
637 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
638 	.vcm_supplies = ad7380_2_channel_vcm_supplies,
639 	.num_vcm_supplies = ARRAY_SIZE(ad7380_2_channel_vcm_supplies),
640 	.available_scan_masks = ad7380_2_channel_scan_masks,
641 	.timing_specs = &ad7380_timing,
642 	.max_conversion_rate_hz = 4 * MEGA,
643 };
644 
645 static const struct ad7380_chip_info ad7384_chip_info = {
646 	.name = "ad7384",
647 	.channels = ad7384_channels,
648 	.offload_channels = ad7384_offload_channels,
649 	.num_channels = ARRAY_SIZE(ad7384_channels),
650 	.num_simult_channels = 2,
651 	.supplies = ad7380_supplies,
652 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
653 	.vcm_supplies = ad7380_2_channel_vcm_supplies,
654 	.num_vcm_supplies = ARRAY_SIZE(ad7380_2_channel_vcm_supplies),
655 	.available_scan_masks = ad7380_2_channel_scan_masks,
656 	.timing_specs = &ad7380_timing,
657 	.max_conversion_rate_hz = 4 * MEGA,
658 };
659 
660 static const struct ad7380_chip_info ad7386_chip_info = {
661 	.name = "ad7386",
662 	.channels = ad7386_channels,
663 	.offload_channels = ad7386_offload_channels,
664 	.num_channels = ARRAY_SIZE(ad7386_channels),
665 	.num_simult_channels = 2,
666 	.supplies = ad7380_supplies,
667 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
668 	.has_mux = true,
669 	.available_scan_masks = ad7380_2x2_channel_scan_masks,
670 	.timing_specs = &ad7380_timing,
671 	.max_conversion_rate_hz = 4 * MEGA,
672 };
673 
674 static const struct ad7380_chip_info ad7387_chip_info = {
675 	.name = "ad7387",
676 	.channels = ad7387_channels,
677 	.offload_channels = ad7387_offload_channels,
678 	.num_channels = ARRAY_SIZE(ad7387_channels),
679 	.num_simult_channels = 2,
680 	.supplies = ad7380_supplies,
681 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
682 	.has_mux = true,
683 	.available_scan_masks = ad7380_2x2_channel_scan_masks,
684 	.timing_specs = &ad7380_timing,
685 	.max_conversion_rate_hz = 4 * MEGA,
686 };
687 
688 static const struct ad7380_chip_info ad7388_chip_info = {
689 	.name = "ad7388",
690 	.channels = ad7388_channels,
691 	.offload_channels = ad7388_offload_channels,
692 	.num_channels = ARRAY_SIZE(ad7388_channels),
693 	.num_simult_channels = 2,
694 	.supplies = ad7380_supplies,
695 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
696 	.has_mux = true,
697 	.available_scan_masks = ad7380_2x2_channel_scan_masks,
698 	.timing_specs = &ad7380_timing,
699 	.max_conversion_rate_hz = 4 * MEGA,
700 };
701 
702 static const struct ad7380_chip_info ad7380_4_chip_info = {
703 	.name = "ad7380-4",
704 	.channels = ad7380_4_channels,
705 	.offload_channels = ad7380_4_offload_channels,
706 	.num_channels = ARRAY_SIZE(ad7380_4_channels),
707 	.num_simult_channels = 4,
708 	.supplies = ad7380_supplies,
709 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
710 	.external_ref_only = true,
711 	.available_scan_masks = ad7380_4_channel_scan_masks,
712 	.timing_specs = &ad7380_4_timing,
713 	.max_conversion_rate_hz = 4 * MEGA,
714 };
715 
716 static const struct ad7380_chip_info ad7381_4_chip_info = {
717 	.name = "ad7381-4",
718 	.channels = ad7381_4_channels,
719 	.offload_channels = ad7381_4_offload_channels,
720 	.num_channels = ARRAY_SIZE(ad7381_4_channels),
721 	.num_simult_channels = 4,
722 	.supplies = ad7380_supplies,
723 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
724 	.available_scan_masks = ad7380_4_channel_scan_masks,
725 	.timing_specs = &ad7380_4_timing,
726 	.max_conversion_rate_hz = 4 * MEGA,
727 };
728 
729 static const struct ad7380_chip_info ad7383_4_chip_info = {
730 	.name = "ad7383-4",
731 	.channels = ad7383_4_channels,
732 	.offload_channels = ad7383_4_offload_channels,
733 	.num_channels = ARRAY_SIZE(ad7383_4_channels),
734 	.num_simult_channels = 4,
735 	.supplies = ad7380_supplies,
736 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
737 	.vcm_supplies = ad7380_4_channel_vcm_supplies,
738 	.num_vcm_supplies = ARRAY_SIZE(ad7380_4_channel_vcm_supplies),
739 	.available_scan_masks = ad7380_4_channel_scan_masks,
740 	.timing_specs = &ad7380_4_timing,
741 	.max_conversion_rate_hz = 4 * MEGA,
742 };
743 
744 static const struct ad7380_chip_info ad7384_4_chip_info = {
745 	.name = "ad7384-4",
746 	.channels = ad7384_4_channels,
747 	.offload_channels = ad7384_4_offload_channels,
748 	.num_channels = ARRAY_SIZE(ad7384_4_channels),
749 	.num_simult_channels = 4,
750 	.supplies = ad7380_supplies,
751 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
752 	.vcm_supplies = ad7380_4_channel_vcm_supplies,
753 	.num_vcm_supplies = ARRAY_SIZE(ad7380_4_channel_vcm_supplies),
754 	.available_scan_masks = ad7380_4_channel_scan_masks,
755 	.timing_specs = &ad7380_4_timing,
756 	.max_conversion_rate_hz = 4 * MEGA,
757 };
758 
759 static const struct ad7380_chip_info ad7386_4_chip_info = {
760 	.name = "ad7386-4",
761 	.channels = ad7386_4_channels,
762 	.offload_channels = ad7386_4_offload_channels,
763 	.num_channels = ARRAY_SIZE(ad7386_4_channels),
764 	.num_simult_channels = 4,
765 	.supplies = ad7380_supplies,
766 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
767 	.has_mux = true,
768 	.available_scan_masks = ad7380_2x4_channel_scan_masks,
769 	.timing_specs = &ad7380_4_timing,
770 	.max_conversion_rate_hz = 4 * MEGA,
771 };
772 
773 static const struct ad7380_chip_info ad7387_4_chip_info = {
774 	.name = "ad7387-4",
775 	.channels = ad7387_4_channels,
776 	.offload_channels = ad7387_4_offload_channels,
777 	.num_channels = ARRAY_SIZE(ad7387_4_channels),
778 	.num_simult_channels = 4,
779 	.supplies = ad7380_supplies,
780 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
781 	.has_mux = true,
782 	.available_scan_masks = ad7380_2x4_channel_scan_masks,
783 	.timing_specs = &ad7380_4_timing,
784 	.max_conversion_rate_hz = 4 * MEGA,
785 };
786 
787 static const struct ad7380_chip_info ad7388_4_chip_info = {
788 	.name = "ad7388-4",
789 	.channels = ad7388_4_channels,
790 	.offload_channels = ad7388_4_offload_channels,
791 	.num_channels = ARRAY_SIZE(ad7388_4_channels),
792 	.num_simult_channels = 4,
793 	.supplies = ad7380_supplies,
794 	.num_supplies = ARRAY_SIZE(ad7380_supplies),
795 	.has_mux = true,
796 	.available_scan_masks = ad7380_2x4_channel_scan_masks,
797 	.timing_specs = &ad7380_4_timing,
798 	.max_conversion_rate_hz = 4 * MEGA,
799 };
800 
801 static const struct ad7380_chip_info adaq4370_4_chip_info = {
802 	.name = "adaq4370-4",
803 	.channels = adaq4380_4_channels,
804 	.offload_channels = adaq4380_4_offload_channels,
805 	.num_channels = ARRAY_SIZE(adaq4380_4_channels),
806 	.num_simult_channels = 4,
807 	.supplies = adaq4380_supplies,
808 	.num_supplies = ARRAY_SIZE(adaq4380_supplies),
809 	.adaq_internal_ref_only = true,
810 	.has_hardware_gain = true,
811 	.available_scan_masks = ad7380_4_channel_scan_masks,
812 	.timing_specs = &ad7380_4_timing,
813 	.max_conversion_rate_hz = 2 * MEGA,
814 };
815 
816 static const struct ad7380_chip_info adaq4380_4_chip_info = {
817 	.name = "adaq4380-4",
818 	.channels = adaq4380_4_channels,
819 	.offload_channels = adaq4380_4_offload_channels,
820 	.num_channels = ARRAY_SIZE(adaq4380_4_channels),
821 	.num_simult_channels = 4,
822 	.supplies = adaq4380_supplies,
823 	.num_supplies = ARRAY_SIZE(adaq4380_supplies),
824 	.adaq_internal_ref_only = true,
825 	.has_hardware_gain = true,
826 	.available_scan_masks = ad7380_4_channel_scan_masks,
827 	.timing_specs = &ad7380_4_timing,
828 	.max_conversion_rate_hz = 4 * MEGA,
829 };
830 
831 static const struct ad7380_chip_info adaq4381_4_chip_info = {
832 	.name = "adaq4381-4",
833 	.channels = adaq4381_4_channels,
834 	.offload_channels = adaq4381_4_offload_channels,
835 	.num_channels = ARRAY_SIZE(adaq4381_4_channels),
836 	.num_simult_channels = 4,
837 	.supplies = adaq4380_supplies,
838 	.num_supplies = ARRAY_SIZE(adaq4380_supplies),
839 	.adaq_internal_ref_only = true,
840 	.has_hardware_gain = true,
841 	.available_scan_masks = ad7380_4_channel_scan_masks,
842 	.timing_specs = &ad7380_4_timing,
843 };
844 
845 static const struct spi_offload_config ad7380_offload_config = {
846 	.capability_flags = SPI_OFFLOAD_CAP_TRIGGER |
847 			    SPI_OFFLOAD_CAP_RX_STREAM_DMA,
848 };
849 
850 struct ad7380_state {
851 	const struct ad7380_chip_info *chip_info;
852 	struct spi_device *spi;
853 	struct regmap *regmap;
854 	bool resolution_boost_enabled;
855 	unsigned int ch;
856 	bool seq;
857 	unsigned int vref_mv;
858 	unsigned int vcm_mv[MAX_NUM_CHANNELS];
859 	unsigned int gain_milli[MAX_NUM_CHANNELS];
860 	/* xfers, message an buffer for reading sample data */
861 	struct spi_transfer normal_xfer[2];
862 	struct spi_message normal_msg;
863 	struct spi_transfer seq_xfer[4];
864 	struct spi_message seq_msg;
865 	struct spi_transfer offload_xfer;
866 	struct spi_message offload_msg;
867 	struct spi_offload *offload;
868 	struct spi_offload_trigger *offload_trigger;
869 	unsigned long offload_trigger_hz;
870 
871 	int sample_freq_range[3];
872 	/*
873 	 * DMA (thus cache coherency maintenance) requires the transfer buffers
874 	 * to live in their own cache lines.
875 	 *
876 	 * Make the buffer large enough for MAX_NUM_CHANNELS 32-bit samples and
877 	 * one 64-bit aligned 64-bit timestamp.
878 	 */
879 	u8 scan_data[ALIGN(MAX_NUM_CHANNELS * sizeof(u32), sizeof(s64))
880 			   + sizeof(s64)] __aligned(IIO_DMA_MINALIGN);
881 	/* buffers for reading/writing registers */
882 	u16 tx;
883 	u16 rx;
884 };
885 
886 static int ad7380_regmap_reg_write(void *context, unsigned int reg,
887 				   unsigned int val)
888 {
889 	struct ad7380_state *st = context;
890 	struct spi_transfer xfer = {
891 		.speed_hz = AD7380_REG_WR_SPEED_HZ,
892 		.bits_per_word = 16,
893 		.len = 2,
894 		.tx_buf = &st->tx,
895 	};
896 
897 	st->tx = FIELD_PREP(AD7380_REG_WR, 1) |
898 		 FIELD_PREP(AD7380_REG_REGADDR, reg) |
899 		 FIELD_PREP(AD7380_REG_DATA, val);
900 
901 	return spi_sync_transfer(st->spi, &xfer, 1);
902 }
903 
904 static int ad7380_regmap_reg_read(void *context, unsigned int reg,
905 				  unsigned int *val)
906 {
907 	struct ad7380_state *st = context;
908 	struct spi_transfer xfers[] = {
909 		{
910 			.speed_hz = AD7380_REG_WR_SPEED_HZ,
911 			.bits_per_word = 16,
912 			.len = 2,
913 			.tx_buf = &st->tx,
914 			.cs_change = 1,
915 			.cs_change_delay = {
916 				.value = st->chip_info->timing_specs->t_csh_ns,
917 				.unit = SPI_DELAY_UNIT_NSECS,
918 			},
919 		}, {
920 			.speed_hz = AD7380_REG_WR_SPEED_HZ,
921 			.bits_per_word = 16,
922 			.len = 2,
923 			.rx_buf = &st->rx,
924 		},
925 	};
926 	int ret;
927 
928 	st->tx = FIELD_PREP(AD7380_REG_WR, 0) |
929 		 FIELD_PREP(AD7380_REG_REGADDR, reg) |
930 		 FIELD_PREP(AD7380_REG_DATA, 0);
931 
932 	ret = spi_sync_transfer(st->spi, xfers, ARRAY_SIZE(xfers));
933 	if (ret < 0)
934 		return ret;
935 
936 	*val = FIELD_GET(AD7380_REG_DATA, st->rx);
937 
938 	return 0;
939 }
940 
941 static const struct reg_default ad7380_reg_defaults[] = {
942 	{ AD7380_REG_ADDR_ALERT_LOW_TH, 0x800 },
943 	{ AD7380_REG_ADDR_ALERT_HIGH_TH, 0x7FF },
944 };
945 
946 static const struct regmap_range ad7380_volatile_reg_ranges[] = {
947 	regmap_reg_range(AD7380_REG_ADDR_CONFIG2, AD7380_REG_ADDR_ALERT),
948 };
949 
950 static const struct regmap_access_table ad7380_volatile_regs = {
951 	.yes_ranges = ad7380_volatile_reg_ranges,
952 	.n_yes_ranges = ARRAY_SIZE(ad7380_volatile_reg_ranges),
953 };
954 
955 static const struct regmap_config ad7380_regmap_config = {
956 	.reg_bits = 3,
957 	.val_bits = 12,
958 	.reg_read = ad7380_regmap_reg_read,
959 	.reg_write = ad7380_regmap_reg_write,
960 	.max_register = AD7380_REG_ADDR_ALERT_HIGH_TH,
961 	.can_sleep = true,
962 	.reg_defaults = ad7380_reg_defaults,
963 	.num_reg_defaults = ARRAY_SIZE(ad7380_reg_defaults),
964 	.volatile_table = &ad7380_volatile_regs,
965 	.cache_type = REGCACHE_MAPLE,
966 };
967 
968 static int ad7380_debugfs_reg_access(struct iio_dev *indio_dev, u32 reg,
969 				     u32 writeval, u32 *readval)
970 {
971 	struct ad7380_state *st = iio_priv(indio_dev);
972 	int ret;
973 
974 	if (!iio_device_claim_direct(indio_dev))
975 		return -EBUSY;
976 
977 	if (readval)
978 		ret = regmap_read(st->regmap, reg, readval);
979 	else
980 		ret = regmap_write(st->regmap, reg, writeval);
981 
982 	iio_device_release_direct(indio_dev);
983 
984 	return ret;
985 }
986 
987 /**
988  * ad7380_regval_to_osr - convert OSR register value to ratio
989  * @regval: register value to check
990  *
991  * Returns: the ratio corresponding to the OSR register. If regval is not in
992  * bound, return 1 (oversampling disabled)
993  *
994  */
995 static int ad7380_regval_to_osr(unsigned int regval)
996 {
997 	if (regval >= ARRAY_SIZE(ad7380_oversampling_ratios))
998 		return 1;
999 
1000 	return ad7380_oversampling_ratios[regval];
1001 }
1002 
1003 static int ad7380_get_osr(struct ad7380_state *st, int *val)
1004 {
1005 	u32 tmp;
1006 	int ret;
1007 
1008 	ret = regmap_read(st->regmap, AD7380_REG_ADDR_CONFIG1, &tmp);
1009 	if (ret)
1010 		return ret;
1011 
1012 	*val = ad7380_regval_to_osr(FIELD_GET(AD7380_CONFIG1_OSR, tmp));
1013 
1014 	return 0;
1015 }
1016 
1017 /*
1018  * When switching channel, the ADC require an additional settling time.
1019  * According to the datasheet, data is value on the third CS low. We already
1020  * have an extra toggle before each read (either direct reads or buffered reads)
1021  * to sample correct data, so we just add a single CS toggle at the end of the
1022  * register write.
1023  */
1024 static int ad7380_set_ch(struct ad7380_state *st, unsigned int ch)
1025 {
1026 	struct spi_transfer xfer = {
1027 		.delay = {
1028 			.value = T_CONVERT_NS,
1029 			.unit = SPI_DELAY_UNIT_NSECS,
1030 		}
1031 	};
1032 	int oversampling_ratio, ret;
1033 
1034 	if (st->ch == ch)
1035 		return 0;
1036 
1037 	ret = ad7380_get_osr(st, &oversampling_ratio);
1038 	if (ret)
1039 		return ret;
1040 
1041 	ret = regmap_update_bits(st->regmap,
1042 				 AD7380_REG_ADDR_CONFIG1,
1043 				 AD7380_CONFIG1_CH,
1044 				 FIELD_PREP(AD7380_CONFIG1_CH, ch));
1045 
1046 	if (ret)
1047 		return ret;
1048 
1049 	st->ch = ch;
1050 
1051 	if (oversampling_ratio > 1)
1052 		xfer.delay.value = T_CONVERT_0_NS +
1053 			T_CONVERT_X_NS * (oversampling_ratio - 1) *
1054 			st->chip_info->num_simult_channels / AD7380_NUM_SDO_LINES;
1055 
1056 	return spi_sync_transfer(st->spi, &xfer, 1);
1057 }
1058 
1059 /**
1060  * ad7380_update_xfers - update the SPI transfers base on the current scan type
1061  * @st:		device instance specific state
1062  * @scan_type:	current scan type
1063  */
1064 static int ad7380_update_xfers(struct ad7380_state *st,
1065 				const struct iio_scan_type *scan_type)
1066 {
1067 	struct spi_transfer *xfer = st->seq ? st->seq_xfer : st->normal_xfer;
1068 	unsigned int t_convert = T_CONVERT_NS;
1069 	int oversampling_ratio, ret;
1070 
1071 	/*
1072 	 * In the case of oversampling, conversion time is higher than in normal
1073 	 * mode. Technically T_CONVERT_X_NS is lower for some chips, but we use
1074 	 * the maximum value for simplicity for now.
1075 	 */
1076 	ret = ad7380_get_osr(st, &oversampling_ratio);
1077 	if (ret)
1078 		return ret;
1079 
1080 	if (oversampling_ratio > 1)
1081 		t_convert = T_CONVERT_0_NS + T_CONVERT_X_NS *
1082 			(oversampling_ratio - 1) *
1083 			st->chip_info->num_simult_channels / AD7380_NUM_SDO_LINES;
1084 
1085 	if (st->seq) {
1086 		xfer[0].delay.value = xfer[1].delay.value = t_convert;
1087 		xfer[0].delay.unit = xfer[1].delay.unit = SPI_DELAY_UNIT_NSECS;
1088 		xfer[2].bits_per_word = xfer[3].bits_per_word =
1089 			scan_type->realbits;
1090 		xfer[2].len = xfer[3].len =
1091 			AD7380_SPI_BYTES(scan_type) *
1092 			st->chip_info->num_simult_channels;
1093 		xfer[3].rx_buf = xfer[2].rx_buf + xfer[2].len;
1094 		/* Additional delay required here when oversampling is enabled */
1095 		if (oversampling_ratio > 1)
1096 			xfer[2].delay.value = t_convert;
1097 		else
1098 			xfer[2].delay.value = 0;
1099 		xfer[2].delay.unit = SPI_DELAY_UNIT_NSECS;
1100 	} else {
1101 		xfer[0].delay.value = t_convert;
1102 		xfer[0].delay.unit = SPI_DELAY_UNIT_NSECS;
1103 		xfer[1].bits_per_word = scan_type->realbits;
1104 		xfer[1].len = AD7380_SPI_BYTES(scan_type) *
1105 			st->chip_info->num_simult_channels;
1106 	}
1107 
1108 	return 0;
1109 }
1110 
1111 static int ad7380_set_sample_freq(struct ad7380_state *st, int val)
1112 {
1113 	struct spi_offload_trigger_config config = {
1114 		.type = SPI_OFFLOAD_TRIGGER_PERIODIC,
1115 		.periodic = {
1116 			.frequency_hz = val,
1117 		},
1118 	};
1119 	int ret;
1120 
1121 	ret = spi_offload_trigger_validate(st->offload_trigger, &config);
1122 	if (ret)
1123 		return ret;
1124 
1125 	st->offload_trigger_hz = config.periodic.frequency_hz;
1126 
1127 	return 0;
1128 }
1129 
1130 static int ad7380_init_offload_msg(struct ad7380_state *st,
1131 				   struct iio_dev *indio_dev)
1132 {
1133 	struct spi_transfer *xfer = &st->offload_xfer;
1134 	struct device *dev = &st->spi->dev;
1135 	const struct iio_scan_type *scan_type;
1136 	int oversampling_ratio;
1137 	int ret;
1138 
1139 	scan_type = iio_get_current_scan_type(indio_dev,
1140 					      &indio_dev->channels[0]);
1141 	if (IS_ERR(scan_type))
1142 		return PTR_ERR(scan_type);
1143 
1144 	if (st->chip_info->has_mux) {
1145 		int index;
1146 
1147 		ret = iio_active_scan_mask_index(indio_dev);
1148 		if (ret < 0)
1149 			return ret;
1150 
1151 		index = ret;
1152 		if (index == AD7380_SCAN_MASK_SEQ) {
1153 			ret = regmap_set_bits(st->regmap, AD7380_REG_ADDR_CONFIG1,
1154 					      AD7380_CONFIG1_SEQ);
1155 			if (ret)
1156 				return ret;
1157 
1158 			st->seq = true;
1159 		} else {
1160 			ret = ad7380_set_ch(st, index);
1161 			if (ret)
1162 				return ret;
1163 		}
1164 	}
1165 
1166 	ret = ad7380_get_osr(st, &oversampling_ratio);
1167 	if (ret)
1168 		return ret;
1169 
1170 	xfer->bits_per_word = scan_type->realbits;
1171 	xfer->offload_flags = SPI_OFFLOAD_XFER_RX_STREAM;
1172 	xfer->len = AD7380_SPI_BYTES(scan_type) * st->chip_info->num_simult_channels;
1173 
1174 	spi_message_init_with_transfers(&st->offload_msg, xfer, 1);
1175 	st->offload_msg.offload = st->offload;
1176 
1177 	ret = spi_optimize_message(st->spi, &st->offload_msg);
1178 	if (ret) {
1179 		dev_err(dev, "failed to prepare offload msg, err: %d\n",
1180 			ret);
1181 		return ret;
1182 	}
1183 
1184 	return 0;
1185 }
1186 
1187 static int ad7380_offload_buffer_postenable(struct iio_dev *indio_dev)
1188 {
1189 	struct ad7380_state *st = iio_priv(indio_dev);
1190 	struct spi_offload_trigger_config config = {
1191 		.type = SPI_OFFLOAD_TRIGGER_PERIODIC,
1192 		.periodic = {
1193 			.frequency_hz = st->offload_trigger_hz,
1194 		},
1195 	};
1196 	int ret;
1197 
1198 	ret = ad7380_init_offload_msg(st, indio_dev);
1199 	if (ret)
1200 		return ret;
1201 
1202 	ret = spi_offload_trigger_enable(st->offload, st->offload_trigger, &config);
1203 	if (ret)
1204 		spi_unoptimize_message(&st->offload_msg);
1205 
1206 	return ret;
1207 }
1208 
1209 static int ad7380_offload_buffer_predisable(struct iio_dev *indio_dev)
1210 {
1211 	struct ad7380_state *st = iio_priv(indio_dev);
1212 	int ret;
1213 
1214 	if (st->seq) {
1215 		ret = regmap_update_bits(st->regmap,
1216 					 AD7380_REG_ADDR_CONFIG1,
1217 					 AD7380_CONFIG1_SEQ,
1218 					 FIELD_PREP(AD7380_CONFIG1_SEQ, 0));
1219 		if (ret)
1220 			return ret;
1221 
1222 		st->seq = false;
1223 	}
1224 
1225 	spi_offload_trigger_disable(st->offload, st->offload_trigger);
1226 
1227 	spi_unoptimize_message(&st->offload_msg);
1228 
1229 	return 0;
1230 }
1231 
1232 static const struct iio_buffer_setup_ops ad7380_offload_buffer_setup_ops = {
1233 	.postenable = ad7380_offload_buffer_postenable,
1234 	.predisable = ad7380_offload_buffer_predisable,
1235 };
1236 
1237 static int ad7380_triggered_buffer_preenable(struct iio_dev *indio_dev)
1238 {
1239 	struct ad7380_state *st = iio_priv(indio_dev);
1240 	const struct iio_scan_type *scan_type;
1241 	struct spi_message *msg = &st->normal_msg;
1242 	int ret;
1243 
1244 	/*
1245 	 * Currently, we always read all channels at the same time. The scan_type
1246 	 * is the same for all channels, so we just pass the first channel.
1247 	 */
1248 	scan_type = iio_get_current_scan_type(indio_dev, &indio_dev->channels[0]);
1249 	if (IS_ERR(scan_type))
1250 		return PTR_ERR(scan_type);
1251 
1252 	if (st->chip_info->has_mux) {
1253 		unsigned int index;
1254 
1255 		/*
1256 		 * Depending on the requested scan_mask and current state,
1257 		 * we need to either change CH bit, or enable sequencer mode
1258 		 * to sample correct data.
1259 		 * Sequencer mode is enabled if active mask corresponds to all
1260 		 * IIO channels enabled. Otherwise, CH bit is set.
1261 		 */
1262 		ret = iio_active_scan_mask_index(indio_dev);
1263 		if (ret < 0)
1264 			return ret;
1265 
1266 		index = ret;
1267 		if (index == AD7380_SCAN_MASK_SEQ) {
1268 			ret = regmap_update_bits(st->regmap,
1269 						 AD7380_REG_ADDR_CONFIG1,
1270 						 AD7380_CONFIG1_SEQ,
1271 						 FIELD_PREP(AD7380_CONFIG1_SEQ, 1));
1272 			if (ret)
1273 				return ret;
1274 			msg = &st->seq_msg;
1275 			st->seq = true;
1276 		} else {
1277 			ret = ad7380_set_ch(st, index);
1278 			if (ret)
1279 				return ret;
1280 		}
1281 
1282 	}
1283 
1284 	ret = ad7380_update_xfers(st, scan_type);
1285 	if (ret)
1286 		return ret;
1287 
1288 	return spi_optimize_message(st->spi, msg);
1289 }
1290 
1291 static int ad7380_triggered_buffer_postdisable(struct iio_dev *indio_dev)
1292 {
1293 	struct ad7380_state *st = iio_priv(indio_dev);
1294 	struct spi_message *msg = &st->normal_msg;
1295 	int ret;
1296 
1297 	if (st->seq) {
1298 		ret = regmap_update_bits(st->regmap,
1299 					 AD7380_REG_ADDR_CONFIG1,
1300 					 AD7380_CONFIG1_SEQ,
1301 					 FIELD_PREP(AD7380_CONFIG1_SEQ, 0));
1302 		if (ret)
1303 			return ret;
1304 
1305 		msg = &st->seq_msg;
1306 		st->seq = false;
1307 	}
1308 
1309 	spi_unoptimize_message(msg);
1310 
1311 	return 0;
1312 }
1313 
1314 static const struct iio_buffer_setup_ops ad7380_buffer_setup_ops = {
1315 	.preenable = ad7380_triggered_buffer_preenable,
1316 	.postdisable = ad7380_triggered_buffer_postdisable,
1317 };
1318 
1319 static irqreturn_t ad7380_trigger_handler(int irq, void *p)
1320 {
1321 	struct iio_poll_func *pf = p;
1322 	struct iio_dev *indio_dev = pf->indio_dev;
1323 	struct ad7380_state *st = iio_priv(indio_dev);
1324 	struct spi_message *msg = st->seq ? &st->seq_msg : &st->normal_msg;
1325 	int ret;
1326 
1327 	ret = spi_sync(st->spi, msg);
1328 	if (ret)
1329 		goto out;
1330 
1331 	iio_push_to_buffers_with_timestamp(indio_dev, &st->scan_data,
1332 					   pf->timestamp);
1333 
1334 out:
1335 	iio_trigger_notify_done(indio_dev->trig);
1336 
1337 	return IRQ_HANDLED;
1338 }
1339 
1340 static int ad7380_read_direct(struct ad7380_state *st, unsigned int scan_index,
1341 			      const struct iio_scan_type *scan_type, int *val)
1342 {
1343 	unsigned int index = scan_index;
1344 	int ret;
1345 
1346 	if (st->chip_info->has_mux) {
1347 		unsigned int ch = 0;
1348 
1349 		if (index >= st->chip_info->num_simult_channels) {
1350 			index -= st->chip_info->num_simult_channels;
1351 			ch = 1;
1352 		}
1353 
1354 		ret = ad7380_set_ch(st, ch);
1355 		if (ret)
1356 			return ret;
1357 	}
1358 
1359 	ret = ad7380_update_xfers(st, scan_type);
1360 	if (ret)
1361 		return ret;
1362 
1363 	ret = spi_sync(st->spi, &st->normal_msg);
1364 	if (ret < 0)
1365 		return ret;
1366 
1367 	if (scan_type->realbits > 16) {
1368 		if (scan_type->sign == 's')
1369 			*val = sign_extend32(*(u32 *)(st->scan_data + 4 * index),
1370 					     scan_type->realbits - 1);
1371 		else
1372 			*val = *(u32 *)(st->scan_data + 4 * index) &
1373 				GENMASK(scan_type->realbits - 1, 0);
1374 	} else {
1375 		if (scan_type->sign == 's')
1376 			*val = sign_extend32(*(u16 *)(st->scan_data + 2 * index),
1377 					     scan_type->realbits - 1);
1378 		else
1379 			*val = *(u16 *)(st->scan_data + 2 * index) &
1380 				GENMASK(scan_type->realbits - 1, 0);
1381 	}
1382 
1383 	return IIO_VAL_INT;
1384 }
1385 
1386 static int ad7380_read_raw(struct iio_dev *indio_dev,
1387 			   struct iio_chan_spec const *chan,
1388 			   int *val, int *val2, long info)
1389 {
1390 	struct ad7380_state *st = iio_priv(indio_dev);
1391 	const struct iio_scan_type *scan_type;
1392 	int ret;
1393 
1394 	scan_type = iio_get_current_scan_type(indio_dev, chan);
1395 
1396 	if (IS_ERR(scan_type))
1397 		return PTR_ERR(scan_type);
1398 
1399 	switch (info) {
1400 	case IIO_CHAN_INFO_RAW:
1401 		if (!iio_device_claim_direct(indio_dev))
1402 			return -EBUSY;
1403 
1404 		ret = ad7380_read_direct(st, chan->scan_index,
1405 					 scan_type, val);
1406 
1407 		iio_device_release_direct(indio_dev);
1408 
1409 		return ret;
1410 	case IIO_CHAN_INFO_SCALE:
1411 		/*
1412 		 * According to the datasheet, the LSB size is:
1413 		 *    * (2 × VREF) / 2^N, for differential chips
1414 		 *    * VREF / 2^N, for pseudo-differential chips
1415 		 * where N is the ADC resolution (i.e realbits)
1416 		 *
1417 		 * The gain is stored as a fraction of 1000 and, as we need to
1418 		 * divide vref_mv by the gain, we invert the gain/1000 fraction.
1419 		 */
1420 		if (st->chip_info->has_hardware_gain)
1421 			*val = mult_frac(st->vref_mv, MILLI,
1422 					 st->gain_milli[chan->scan_index]);
1423 		else
1424 			*val = st->vref_mv;
1425 		*val2 = scan_type->realbits - chan->differential;
1426 
1427 		return IIO_VAL_FRACTIONAL_LOG2;
1428 	case IIO_CHAN_INFO_OFFSET:
1429 		/*
1430 		 * According to IIO ABI, offset is applied before scale,
1431 		 * so offset is: vcm_mv / scale
1432 		 */
1433 		*val = st->vcm_mv[chan->channel] * (1 << scan_type->realbits)
1434 			/ st->vref_mv;
1435 
1436 		return IIO_VAL_INT;
1437 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1438 		if (!iio_device_claim_direct(indio_dev))
1439 			return -EBUSY;
1440 
1441 		ret = ad7380_get_osr(st, val);
1442 
1443 		iio_device_release_direct(indio_dev);
1444 
1445 		if (ret)
1446 			return ret;
1447 
1448 		return IIO_VAL_INT;
1449 	case IIO_CHAN_INFO_SAMP_FREQ:
1450 		*val = st->offload_trigger_hz;
1451 		return IIO_VAL_INT;
1452 	default:
1453 		return -EINVAL;
1454 	}
1455 }
1456 
1457 static int ad7380_read_avail(struct iio_dev *indio_dev,
1458 			     struct iio_chan_spec const *chan,
1459 			     const int **vals, int *type, int *length,
1460 			     long mask)
1461 {
1462 	struct ad7380_state *st = iio_priv(indio_dev);
1463 
1464 	switch (mask) {
1465 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1466 		*vals = ad7380_oversampling_ratios;
1467 		*length = ARRAY_SIZE(ad7380_oversampling_ratios);
1468 		*type = IIO_VAL_INT;
1469 
1470 		return IIO_AVAIL_LIST;
1471 	case IIO_CHAN_INFO_SAMP_FREQ:
1472 		*vals = st->sample_freq_range;
1473 		*type = IIO_VAL_INT;
1474 		return IIO_AVAIL_RANGE;
1475 	default:
1476 		return -EINVAL;
1477 	}
1478 }
1479 
1480 /**
1481  * ad7380_osr_to_regval - convert ratio to OSR register value
1482  * @ratio: ratio to check
1483  *
1484  * Check if ratio is present in the list of available ratios and return the
1485  * corresponding value that needs to be written to the register to select that
1486  * ratio.
1487  *
1488  * Returns: register value (0 to 7) or -EINVAL if there is not an exact match
1489  */
1490 static int ad7380_osr_to_regval(int ratio)
1491 {
1492 	int i;
1493 
1494 	for (i = 0; i < ARRAY_SIZE(ad7380_oversampling_ratios); i++) {
1495 		if (ratio == ad7380_oversampling_ratios[i])
1496 			return i;
1497 	}
1498 
1499 	return -EINVAL;
1500 }
1501 
1502 static int ad7380_set_oversampling_ratio(struct ad7380_state *st, int val)
1503 {
1504 	int ret, osr, boost;
1505 
1506 	osr = ad7380_osr_to_regval(val);
1507 	if (osr < 0)
1508 		return osr;
1509 
1510 	/* always enable resolution boost when oversampling is enabled */
1511 	boost = osr > 0 ? 1 : 0;
1512 
1513 	ret = regmap_update_bits(st->regmap,
1514 				 AD7380_REG_ADDR_CONFIG1,
1515 				 AD7380_CONFIG1_OSR | AD7380_CONFIG1_RES,
1516 				 FIELD_PREP(AD7380_CONFIG1_OSR, osr) |
1517 				 FIELD_PREP(AD7380_CONFIG1_RES, boost));
1518 
1519 	if (ret)
1520 		return ret;
1521 
1522 	st->resolution_boost_enabled = boost;
1523 
1524 	/*
1525 	 * Perform a soft reset. This will flush the oversampling
1526 	 * block and FIFO but will maintain the content of the
1527 	 * configurable registers.
1528 	 */
1529 	ret = regmap_update_bits(st->regmap,
1530 				 AD7380_REG_ADDR_CONFIG2,
1531 				 AD7380_CONFIG2_RESET,
1532 				 FIELD_PREP(AD7380_CONFIG2_RESET,
1533 					    AD7380_CONFIG2_RESET_SOFT));
1534 	return ret;
1535 }
1536 static int ad7380_write_raw(struct iio_dev *indio_dev,
1537 			    struct iio_chan_spec const *chan, int val,
1538 			    int val2, long mask)
1539 {
1540 	struct ad7380_state *st = iio_priv(indio_dev);
1541 	int ret;
1542 
1543 	switch (mask) {
1544 	case IIO_CHAN_INFO_SAMP_FREQ:
1545 		if (val < 1)
1546 			return -EINVAL;
1547 		return ad7380_set_sample_freq(st, val);
1548 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1549 		if (!iio_device_claim_direct(indio_dev))
1550 			return -EBUSY;
1551 
1552 		ret = ad7380_set_oversampling_ratio(st, val);
1553 
1554 		iio_device_release_direct(indio_dev);
1555 
1556 		return ret;
1557 	default:
1558 		return -EINVAL;
1559 	}
1560 }
1561 
1562 static int ad7380_get_current_scan_type(const struct iio_dev *indio_dev,
1563 					const struct iio_chan_spec *chan)
1564 {
1565 	struct ad7380_state *st = iio_priv(indio_dev);
1566 
1567 	return st->resolution_boost_enabled ? AD7380_SCAN_TYPE_RESOLUTION_BOOST
1568 					    : AD7380_SCAN_TYPE_NORMAL;
1569 }
1570 
1571 static int ad7380_read_event_config(struct iio_dev *indio_dev,
1572 				    const struct iio_chan_spec *chan,
1573 				    enum iio_event_type type,
1574 				    enum iio_event_direction dir)
1575 {
1576 	struct ad7380_state *st = iio_priv(indio_dev);
1577 	int tmp, ret;
1578 
1579 	if (!iio_device_claim_direct(indio_dev))
1580 		return -EBUSY;
1581 
1582 	ret = regmap_read(st->regmap, AD7380_REG_ADDR_CONFIG1, &tmp);
1583 
1584 	iio_device_release_direct(indio_dev);
1585 
1586 	if (ret)
1587 		return ret;
1588 
1589 	return FIELD_GET(AD7380_CONFIG1_ALERTEN, tmp);
1590 }
1591 
1592 static int ad7380_write_event_config(struct iio_dev *indio_dev,
1593 				     const struct iio_chan_spec *chan,
1594 				     enum iio_event_type type,
1595 				     enum iio_event_direction dir,
1596 				     bool state)
1597 {
1598 	struct ad7380_state *st = iio_priv(indio_dev);
1599 	int ret;
1600 
1601 	if (!iio_device_claim_direct(indio_dev))
1602 		return -EBUSY;
1603 
1604 	ret = regmap_update_bits(st->regmap,
1605 				 AD7380_REG_ADDR_CONFIG1,
1606 				 AD7380_CONFIG1_ALERTEN,
1607 				 FIELD_PREP(AD7380_CONFIG1_ALERTEN, state));
1608 
1609 	iio_device_release_direct(indio_dev);
1610 
1611 	return ret;
1612 }
1613 
1614 static int ad7380_get_alert_th(struct ad7380_state *st,
1615 			       enum iio_event_direction dir,
1616 			       int *val)
1617 {
1618 	int ret, tmp;
1619 
1620 	switch (dir) {
1621 	case IIO_EV_DIR_RISING:
1622 		ret = regmap_read(st->regmap,
1623 				  AD7380_REG_ADDR_ALERT_HIGH_TH,
1624 				  &tmp);
1625 		if (ret)
1626 			return ret;
1627 
1628 		*val = FIELD_GET(AD7380_ALERT_HIGH_TH, tmp);
1629 		return IIO_VAL_INT;
1630 	case IIO_EV_DIR_FALLING:
1631 		ret = regmap_read(st->regmap,
1632 				  AD7380_REG_ADDR_ALERT_LOW_TH,
1633 				  &tmp);
1634 		if (ret)
1635 			return ret;
1636 
1637 		*val = FIELD_GET(AD7380_ALERT_LOW_TH, tmp);
1638 		return IIO_VAL_INT;
1639 	default:
1640 		return -EINVAL;
1641 	}
1642 }
1643 
1644 static int ad7380_read_event_value(struct iio_dev *indio_dev,
1645 				   const struct iio_chan_spec *chan,
1646 				   enum iio_event_type type,
1647 				   enum iio_event_direction dir,
1648 				   enum iio_event_info info,
1649 				   int *val, int *val2)
1650 {
1651 	struct ad7380_state *st = iio_priv(indio_dev);
1652 	int ret;
1653 
1654 	switch (info) {
1655 	case IIO_EV_INFO_VALUE:
1656 		if (!iio_device_claim_direct(indio_dev))
1657 			return -EBUSY;
1658 
1659 		ret = ad7380_get_alert_th(st, dir, val);
1660 
1661 		iio_device_release_direct(indio_dev);
1662 		return ret;
1663 	default:
1664 		return -EINVAL;
1665 	}
1666 }
1667 
1668 static int ad7380_set_alert_th(struct iio_dev *indio_dev,
1669 			       const struct iio_chan_spec *chan,
1670 			       enum iio_event_direction dir,
1671 			       int val)
1672 {
1673 	struct ad7380_state *st = iio_priv(indio_dev);
1674 	const struct iio_scan_type *scan_type;
1675 	u16 th;
1676 
1677 	/*
1678 	 * According to the datasheet,
1679 	 * AD7380_REG_ADDR_ALERT_HIGH_TH[11:0] are the 12 MSB of the
1680 	 * 16-bits internal alert high register. LSB are set to 0xf.
1681 	 * AD7380_REG_ADDR_ALERT_LOW_TH[11:0] are the 12 MSB of the
1682 	 * 16 bits internal alert low register. LSB are set to 0x0.
1683 	 *
1684 	 * When alert is enabled the conversion from the adc is compared
1685 	 * immediately to the alert high/low thresholds, before any
1686 	 * oversampling. This means that the thresholds are the same for
1687 	 * normal mode and oversampling mode.
1688 	 */
1689 
1690 	/* Extract the 12 MSB of val */
1691 	scan_type = iio_get_current_scan_type(indio_dev, chan);
1692 	if (IS_ERR(scan_type))
1693 		return PTR_ERR(scan_type);
1694 
1695 	th = val >> (scan_type->realbits - 12);
1696 
1697 	switch (dir) {
1698 	case IIO_EV_DIR_RISING:
1699 		return regmap_write(st->regmap,
1700 				    AD7380_REG_ADDR_ALERT_HIGH_TH,
1701 				    th);
1702 	case IIO_EV_DIR_FALLING:
1703 		return regmap_write(st->regmap,
1704 				    AD7380_REG_ADDR_ALERT_LOW_TH,
1705 				    th);
1706 	default:
1707 		return -EINVAL;
1708 	}
1709 }
1710 
1711 static int ad7380_write_event_value(struct iio_dev *indio_dev,
1712 				    const struct iio_chan_spec *chan,
1713 				    enum iio_event_type type,
1714 				    enum iio_event_direction dir,
1715 				    enum iio_event_info info,
1716 				    int val, int val2)
1717 {
1718 	int ret;
1719 
1720 	switch (info) {
1721 	case IIO_EV_INFO_VALUE:
1722 		if (!iio_device_claim_direct(indio_dev))
1723 			return -EBUSY;
1724 
1725 		ret = ad7380_set_alert_th(indio_dev, chan, dir, val);
1726 
1727 		iio_device_release_direct(indio_dev);
1728 		return ret;
1729 	default:
1730 		return -EINVAL;
1731 	}
1732 }
1733 
1734 static const struct iio_info ad7380_info = {
1735 	.read_raw = &ad7380_read_raw,
1736 	.read_avail = &ad7380_read_avail,
1737 	.write_raw = &ad7380_write_raw,
1738 	.get_current_scan_type = &ad7380_get_current_scan_type,
1739 	.debugfs_reg_access = &ad7380_debugfs_reg_access,
1740 	.read_event_config = &ad7380_read_event_config,
1741 	.write_event_config = &ad7380_write_event_config,
1742 	.read_event_value = &ad7380_read_event_value,
1743 	.write_event_value = &ad7380_write_event_value,
1744 };
1745 
1746 static int ad7380_init(struct ad7380_state *st, bool external_ref_en)
1747 {
1748 	int ret;
1749 
1750 	/* perform hard reset */
1751 	ret = regmap_update_bits(st->regmap, AD7380_REG_ADDR_CONFIG2,
1752 				 AD7380_CONFIG2_RESET,
1753 				 FIELD_PREP(AD7380_CONFIG2_RESET,
1754 					    AD7380_CONFIG2_RESET_HARD));
1755 	if (ret < 0)
1756 		return ret;
1757 
1758 	if (external_ref_en) {
1759 		/* select external reference voltage */
1760 		ret = regmap_set_bits(st->regmap, AD7380_REG_ADDR_CONFIG1,
1761 				      AD7380_CONFIG1_REFSEL);
1762 		if (ret < 0)
1763 			return ret;
1764 	}
1765 
1766 	/* This is the default value after reset. */
1767 	st->ch = 0;
1768 	st->seq = false;
1769 
1770 	/* SPI 1-wire mode */
1771 	return regmap_update_bits(st->regmap, AD7380_REG_ADDR_CONFIG2,
1772 				  AD7380_CONFIG2_SDO,
1773 				  FIELD_PREP(AD7380_CONFIG2_SDO,
1774 					     AD7380_NUM_SDO_LINES));
1775 }
1776 
1777 static int ad7380_probe_spi_offload(struct iio_dev *indio_dev,
1778 				    struct ad7380_state *st)
1779 {
1780 	struct spi_device *spi = st->spi;
1781 	struct device *dev = &spi->dev;
1782 	struct dma_chan *rx_dma;
1783 	int sample_rate, ret;
1784 
1785 	indio_dev->setup_ops = &ad7380_offload_buffer_setup_ops;
1786 	indio_dev->channels = st->chip_info->offload_channels;
1787 	/* Just removing the timestamp channel. */
1788 	indio_dev->num_channels--;
1789 
1790 	st->offload_trigger = devm_spi_offload_trigger_get(dev, st->offload,
1791 		SPI_OFFLOAD_TRIGGER_PERIODIC);
1792 	if (IS_ERR(st->offload_trigger))
1793 		return dev_err_probe(dev, PTR_ERR(st->offload_trigger),
1794 				     "failed to get offload trigger\n");
1795 
1796 	sample_rate = st->chip_info->max_conversion_rate_hz *
1797 		      AD7380_NUM_SDO_LINES / st->chip_info->num_simult_channels;
1798 
1799 	st->sample_freq_range[0] = 1; /* min */
1800 	st->sample_freq_range[1] = 1; /* step */
1801 	st->sample_freq_range[2] = sample_rate; /* max */
1802 
1803 	/*
1804 	 * Starting with a quite low frequency, to allow oversampling x32,
1805 	 * user is then reponsible to adjust the frequency for the specific case.
1806 	 */
1807 	ret = ad7380_set_sample_freq(st, sample_rate / 32);
1808 	if (ret)
1809 		return ret;
1810 
1811 	rx_dma = devm_spi_offload_rx_stream_request_dma_chan(dev, st->offload);
1812 	if (IS_ERR(rx_dma))
1813 		return dev_err_probe(dev, PTR_ERR(rx_dma),
1814 				     "failed to get offload RX DMA\n");
1815 
1816 	ret = devm_iio_dmaengine_buffer_setup_with_handle(dev, indio_dev,
1817 		rx_dma, IIO_BUFFER_DIRECTION_IN);
1818 	if (ret)
1819 		return dev_err_probe(dev, ret, "cannot setup dma buffer\n");
1820 
1821 	return 0;
1822 }
1823 
1824 static int ad7380_probe(struct spi_device *spi)
1825 {
1826 	struct device *dev = &spi->dev;
1827 	struct iio_dev *indio_dev;
1828 	struct ad7380_state *st;
1829 	bool external_ref_en;
1830 	int ret, i;
1831 
1832 	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
1833 	if (!indio_dev)
1834 		return -ENOMEM;
1835 
1836 	st = iio_priv(indio_dev);
1837 	st->spi = spi;
1838 	st->chip_info = spi_get_device_match_data(spi);
1839 	if (!st->chip_info)
1840 		return dev_err_probe(dev, -EINVAL, "missing match data\n");
1841 
1842 	ret = devm_regulator_bulk_get_enable(dev, st->chip_info->num_supplies,
1843 					     st->chip_info->supplies);
1844 
1845 	if (ret)
1846 		return dev_err_probe(dev, ret,
1847 				     "Failed to enable power supplies\n");
1848 	fsleep(T_POWERUP_US);
1849 
1850 	if (st->chip_info->adaq_internal_ref_only) {
1851 		/*
1852 		 * ADAQ chips use fixed internal reference but still
1853 		 * require a specific reference supply to power it.
1854 		 * "refin" is already enabled with other power supplies
1855 		 * in bulk_get_enable().
1856 		 */
1857 
1858 		st->vref_mv = ADAQ4380_INTERNAL_REF_MV;
1859 
1860 		/* these chips don't have a register bit for this */
1861 		external_ref_en = false;
1862 	} else if (st->chip_info->external_ref_only) {
1863 		ret = devm_regulator_get_enable_read_voltage(dev, "refin");
1864 		if (ret < 0)
1865 			return dev_err_probe(dev, ret,
1866 					     "Failed to get refin regulator\n");
1867 
1868 		st->vref_mv = ret / 1000;
1869 
1870 		/* these chips don't have a register bit for this */
1871 		external_ref_en = false;
1872 	} else {
1873 		/*
1874 		 * If there is no REFIO supply, then it means that we are using
1875 		 * the internal reference, otherwise REFIO is reference voltage.
1876 		 */
1877 		ret = devm_regulator_get_enable_read_voltage(dev, "refio");
1878 		if (ret < 0 && ret != -ENODEV)
1879 			return dev_err_probe(dev, ret,
1880 					     "Failed to get refio regulator\n");
1881 
1882 		external_ref_en = ret != -ENODEV;
1883 		st->vref_mv = external_ref_en ? ret / 1000 : AD7380_INTERNAL_REF_MV;
1884 	}
1885 
1886 	if (st->chip_info->num_vcm_supplies > ARRAY_SIZE(st->vcm_mv))
1887 		return dev_err_probe(dev, -EINVAL,
1888 				     "invalid number of VCM supplies\n");
1889 
1890 	/*
1891 	 * pseudo-differential chips have common mode supplies for the negative
1892 	 * input pin.
1893 	 */
1894 	for (i = 0; i < st->chip_info->num_vcm_supplies; i++) {
1895 		const char *vcm = st->chip_info->vcm_supplies[i];
1896 
1897 		ret = devm_regulator_get_enable_read_voltage(dev, vcm);
1898 		if (ret < 0)
1899 			return dev_err_probe(dev, ret,
1900 					     "Failed to get %s regulator\n",
1901 					     vcm);
1902 
1903 		st->vcm_mv[i] = ret / 1000;
1904 	}
1905 
1906 	for (i = 0; i < MAX_NUM_CHANNELS; i++)
1907 		st->gain_milli[i] = AD7380_DEFAULT_GAIN_MILLI;
1908 
1909 	if (st->chip_info->has_hardware_gain) {
1910 		device_for_each_child_node_scoped(dev, node) {
1911 			unsigned int channel, gain;
1912 			int gain_idx;
1913 
1914 			ret = fwnode_property_read_u32(node, "reg", &channel);
1915 			if (ret)
1916 				return dev_err_probe(dev, ret,
1917 						     "Failed to read reg property\n");
1918 
1919 			if (channel >= st->chip_info->num_channels - 1)
1920 				return dev_err_probe(dev, -EINVAL,
1921 						     "Invalid channel number %i\n",
1922 						     channel);
1923 
1924 			ret = fwnode_property_read_u32(node, "adi,gain-milli",
1925 						       &gain);
1926 			if (ret && ret != -EINVAL)
1927 				return dev_err_probe(dev, ret,
1928 						     "Failed to read gain for channel %i\n",
1929 						     channel);
1930 			if (ret != -EINVAL) {
1931 				/*
1932 				 * Match gain value from dt to one of supported
1933 				 * gains
1934 				 */
1935 				gain_idx = find_closest(gain, ad7380_gains,
1936 							ARRAY_SIZE(ad7380_gains));
1937 				st->gain_milli[channel] = ad7380_gains[gain_idx];
1938 			}
1939 		}
1940 	}
1941 
1942 	st->regmap = devm_regmap_init(dev, NULL, st, &ad7380_regmap_config);
1943 	if (IS_ERR(st->regmap))
1944 		return dev_err_probe(dev, PTR_ERR(st->regmap),
1945 				     "failed to allocate register map\n");
1946 
1947 	/*
1948 	 * Setting up xfer structures for both normal and sequence mode. These
1949 	 * struct are used for both direct read and triggered buffer. Additional
1950 	 * fields will be set up in ad7380_update_xfers() based on the current
1951 	 * state of the driver at the time of the read.
1952 	 */
1953 
1954 	/*
1955 	 * In normal mode a read is composed of two steps:
1956 	 *   - first, toggle CS (no data xfer) to trigger a conversion
1957 	 *   - then, read data
1958 	 */
1959 	st->normal_xfer[0].cs_change = 1;
1960 	st->normal_xfer[0].cs_change_delay.value = st->chip_info->timing_specs->t_csh_ns;
1961 	st->normal_xfer[0].cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
1962 	st->normal_xfer[1].rx_buf = st->scan_data;
1963 
1964 	spi_message_init_with_transfers(&st->normal_msg, st->normal_xfer,
1965 					ARRAY_SIZE(st->normal_xfer));
1966 	/*
1967 	 * In sequencer mode a read is composed of four steps:
1968 	 *   - CS toggle (no data xfer) to get the right point in the sequence
1969 	 *   - CS toggle (no data xfer) to trigger a conversion of AinX0 and
1970 	 *   acquisition of AinX1
1971 	 *   - 2 data reads, to read AinX0 and AinX1
1972 	 */
1973 	st->seq_xfer[0].cs_change = 1;
1974 	st->seq_xfer[0].cs_change_delay.value = st->chip_info->timing_specs->t_csh_ns;
1975 	st->seq_xfer[0].cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
1976 	st->seq_xfer[1].cs_change = 1;
1977 	st->seq_xfer[1].cs_change_delay.value = st->chip_info->timing_specs->t_csh_ns;
1978 	st->seq_xfer[1].cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
1979 
1980 	st->seq_xfer[2].rx_buf = st->scan_data;
1981 	st->seq_xfer[2].cs_change = 1;
1982 	st->seq_xfer[2].cs_change_delay.value = st->chip_info->timing_specs->t_csh_ns;
1983 	st->seq_xfer[2].cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
1984 
1985 	spi_message_init_with_transfers(&st->seq_msg, st->seq_xfer,
1986 					ARRAY_SIZE(st->seq_xfer));
1987 
1988 	indio_dev->channels = st->chip_info->channels;
1989 	indio_dev->num_channels = st->chip_info->num_channels;
1990 	indio_dev->name = st->chip_info->name;
1991 	indio_dev->info = &ad7380_info;
1992 	indio_dev->modes = INDIO_DIRECT_MODE;
1993 	indio_dev->available_scan_masks = st->chip_info->available_scan_masks;
1994 
1995 	st->offload = devm_spi_offload_get(dev, spi, &ad7380_offload_config);
1996 	ret = PTR_ERR_OR_ZERO(st->offload);
1997 	if (ret && ret != -ENODEV)
1998 		return dev_err_probe(dev, ret, "failed to get offload\n");
1999 
2000 	/* If no SPI offload, fall back to low speed usage. */
2001 	if (ret == -ENODEV) {
2002 		ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
2003 						      iio_pollfunc_store_time,
2004 						      ad7380_trigger_handler,
2005 						      &ad7380_buffer_setup_ops);
2006 		if (ret)
2007 			return ret;
2008 	} else {
2009 		ret = ad7380_probe_spi_offload(indio_dev, st);
2010 		if (ret)
2011 			return ret;
2012 	}
2013 
2014 	ret = ad7380_init(st, external_ref_en);
2015 	if (ret)
2016 		return ret;
2017 
2018 	return devm_iio_device_register(dev, indio_dev);
2019 }
2020 
2021 static const struct of_device_id ad7380_of_match_table[] = {
2022 	{ .compatible = "adi,ad7380", .data = &ad7380_chip_info },
2023 	{ .compatible = "adi,ad7381", .data = &ad7381_chip_info },
2024 	{ .compatible = "adi,ad7383", .data = &ad7383_chip_info },
2025 	{ .compatible = "adi,ad7384", .data = &ad7384_chip_info },
2026 	{ .compatible = "adi,ad7386", .data = &ad7386_chip_info },
2027 	{ .compatible = "adi,ad7387", .data = &ad7387_chip_info },
2028 	{ .compatible = "adi,ad7388", .data = &ad7388_chip_info },
2029 	{ .compatible = "adi,ad7380-4", .data = &ad7380_4_chip_info },
2030 	{ .compatible = "adi,ad7381-4", .data = &ad7381_4_chip_info },
2031 	{ .compatible = "adi,ad7383-4", .data = &ad7383_4_chip_info },
2032 	{ .compatible = "adi,ad7384-4", .data = &ad7384_4_chip_info },
2033 	{ .compatible = "adi,ad7386-4", .data = &ad7386_4_chip_info },
2034 	{ .compatible = "adi,ad7387-4", .data = &ad7387_4_chip_info },
2035 	{ .compatible = "adi,ad7388-4", .data = &ad7388_4_chip_info },
2036 	{ .compatible = "adi,adaq4370-4", .data = &adaq4370_4_chip_info },
2037 	{ .compatible = "adi,adaq4380-4", .data = &adaq4380_4_chip_info },
2038 	{ .compatible = "adi,adaq4381-4", .data = &adaq4381_4_chip_info },
2039 	{ }
2040 };
2041 
2042 static const struct spi_device_id ad7380_id_table[] = {
2043 	{ "ad7380", (kernel_ulong_t)&ad7380_chip_info },
2044 	{ "ad7381", (kernel_ulong_t)&ad7381_chip_info },
2045 	{ "ad7383", (kernel_ulong_t)&ad7383_chip_info },
2046 	{ "ad7384", (kernel_ulong_t)&ad7384_chip_info },
2047 	{ "ad7386", (kernel_ulong_t)&ad7386_chip_info },
2048 	{ "ad7387", (kernel_ulong_t)&ad7387_chip_info },
2049 	{ "ad7388", (kernel_ulong_t)&ad7388_chip_info },
2050 	{ "ad7380-4", (kernel_ulong_t)&ad7380_4_chip_info },
2051 	{ "ad7381-4", (kernel_ulong_t)&ad7381_4_chip_info },
2052 	{ "ad7383-4", (kernel_ulong_t)&ad7383_4_chip_info },
2053 	{ "ad7384-4", (kernel_ulong_t)&ad7384_4_chip_info },
2054 	{ "ad7386-4", (kernel_ulong_t)&ad7386_4_chip_info },
2055 	{ "ad7387-4", (kernel_ulong_t)&ad7387_4_chip_info },
2056 	{ "ad7388-4", (kernel_ulong_t)&ad7388_4_chip_info },
2057 	{ "adaq4370-4", (kernel_ulong_t)&adaq4370_4_chip_info },
2058 	{ "adaq4380-4", (kernel_ulong_t)&adaq4380_4_chip_info },
2059 	{ "adaq4381-4", (kernel_ulong_t)&adaq4381_4_chip_info },
2060 	{ }
2061 };
2062 MODULE_DEVICE_TABLE(spi, ad7380_id_table);
2063 
2064 static struct spi_driver ad7380_driver = {
2065 	.driver = {
2066 		.name = "ad7380",
2067 		.of_match_table = ad7380_of_match_table,
2068 	},
2069 	.probe = ad7380_probe,
2070 	.id_table = ad7380_id_table,
2071 };
2072 module_spi_driver(ad7380_driver);
2073 
2074 MODULE_AUTHOR("Stefan Popa <stefan.popa@analog.com>");
2075 MODULE_DESCRIPTION("Analog Devices AD738x ADC driver");
2076 MODULE_LICENSE("GPL");
2077 MODULE_IMPORT_NS("IIO_DMAENGINE_BUFFER");
2078