xref: /linux/drivers/iio/adc/ad7173.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * AD717x and AD411x family SPI ADC driver
4  *
5  * Supported devices:
6  *  AD4111/AD4112/AD4113/AD4114/AD4115/AD4116
7  *  AD7172-2/AD7172-4/AD7173-8/AD7175-2
8  *  AD7175-8/AD7176-2/AD7177-2
9  *
10  * Copyright (C) 2015, 2024 Analog Devices, Inc.
11  * Copyright (C) 2025 BayLibre, SAS
12  */
13 
14 #include <linux/array_size.h>
15 #include <linux/bitfield.h>
16 #include <linux/bitmap.h>
17 #include <linux/container_of.h>
18 #include <linux/clk.h>
19 #include <linux/clk-provider.h>
20 #include <linux/delay.h>
21 #include <linux/device.h>
22 #include <linux/err.h>
23 #include <linux/gpio/driver.h>
24 #include <linux/gpio/regmap.h>
25 #include <linux/idr.h>
26 #include <linux/interrupt.h>
27 #include <linux/math64.h>
28 #include <linux/module.h>
29 #include <linux/property.h>
30 #include <linux/regmap.h>
31 #include <linux/regulator/consumer.h>
32 #include <linux/slab.h>
33 #include <linux/spi/spi.h>
34 #include <linux/types.h>
35 #include <linux/units.h>
36 
37 #include <linux/iio/buffer.h>
38 #include <linux/iio/events.h>
39 #include <linux/iio/iio.h>
40 #include <linux/iio/trigger_consumer.h>
41 #include <linux/iio/triggered_buffer.h>
42 
43 #include <linux/iio/adc/ad_sigma_delta.h>
44 
45 #define AD7173_REG_COMMS		0x00
46 #define AD7173_REG_ADC_MODE		0x01
47 #define AD7173_REG_INTERFACE_MODE	0x02
48 #define AD7173_REG_CRC			0x03
49 #define AD7173_REG_DATA			0x04
50 #define AD7173_REG_GPIO			0x06
51 #define AD7173_REG_ID			0x07
52 #define AD7173_REG_CH(x)		(0x10 + (x))
53 #define AD7173_REG_SETUP(x)		(0x20 + (x))
54 #define AD7173_REG_FILTER(x)		(0x28 + (x))
55 #define AD7173_REG_OFFSET(x)		(0x30 + (x))
56 #define AD7173_REG_GAIN(x)		(0x38 + (x))
57 
58 #define AD7173_RESET_LENGTH		BITS_TO_BYTES(64)
59 
60 #define AD7173_CH_ENABLE		BIT(15)
61 #define AD7173_CH_SETUP_SEL_MASK	GENMASK(14, 12)
62 #define AD7173_CH_SETUP_AINPOS_MASK	GENMASK(9, 5)
63 #define AD7173_CH_SETUP_AINNEG_MASK	GENMASK(4, 0)
64 
65 #define AD7173_NO_AINS_PER_CHANNEL	2
66 #define AD7173_CH_ADDRESS(pos, neg) \
67 	(FIELD_PREP(AD7173_CH_SETUP_AINPOS_MASK, pos) | \
68 	 FIELD_PREP(AD7173_CH_SETUP_AINNEG_MASK, neg))
69 #define AD7173_AIN_TEMP_POS	17
70 #define AD7173_AIN_TEMP_NEG	18
71 #define AD7173_AIN_POW_MON_POS	19
72 #define AD7173_AIN_POW_MON_NEG	20
73 #define AD7173_AIN_REF_POS	21
74 #define AD7173_AIN_REF_NEG	22
75 
76 #define AD7173_IS_REF_INPUT(x)		((x) == AD7173_AIN_REF_POS || \
77 					(x) == AD7173_AIN_REF_NEG)
78 
79 #define AD7172_2_ID			0x00d0
80 #define AD7176_ID			0x0c90
81 #define AD7175_ID			0x0cd0
82 #define AD7175_2_ID			0x0cd0
83 #define AD7172_4_ID			0x2050
84 #define AD7173_ID			0x30d0
85 #define AD4111_ID			AD7173_ID
86 #define AD4112_ID			AD7173_ID
87 #define AD4114_ID			AD7173_ID
88 #define AD4113_ID			0x31d0
89 #define AD4116_ID			0x34d0
90 #define AD4115_ID			0x38d0
91 #define AD7175_8_ID			0x3cd0
92 #define AD7177_ID			0x4fd0
93 #define AD7173_ID_MASK			GENMASK(15, 4)
94 
95 #define AD7173_ADC_MODE_REF_EN		BIT(15)
96 #define AD7173_ADC_MODE_SING_CYC	BIT(13)
97 #define AD7173_ADC_MODE_MODE_MASK	GENMASK(6, 4)
98 #define AD7173_ADC_MODE_CLOCKSEL_MASK	GENMASK(3, 2)
99 #define AD7173_ADC_MODE_CLOCKSEL_INT		0x0
100 #define AD7173_ADC_MODE_CLOCKSEL_INT_OUTPUT	0x1
101 #define AD7173_ADC_MODE_CLOCKSEL_EXT		0x2
102 #define AD7173_ADC_MODE_CLOCKSEL_XTAL		0x3
103 
104 #define AD7173_GPIO_PDSW	BIT(14)
105 #define AD7173_GPIO_OP_EN2_3	BIT(13)
106 #define AD4111_GPIO_GP_OW_EN	BIT(12)
107 #define AD7173_GPIO_MUX_IO	BIT(12)
108 #define AD7173_GPIO_SYNC_EN	BIT(11)
109 #define AD7173_GPIO_ERR_EN	BIT(10)
110 #define AD7173_GPIO_ERR_DAT	BIT(9)
111 #define AD7173_GPIO_GP_DATA3	BIT(7)
112 #define AD7173_GPIO_GP_DATA2	BIT(6)
113 #define AD7173_GPIO_IP_EN1	BIT(5)
114 #define AD7173_GPIO_IP_EN0	BIT(4)
115 #define AD7173_GPIO_OP_EN1	BIT(3)
116 #define AD7173_GPIO_OP_EN0	BIT(2)
117 #define AD7173_GPIO_GP_DATA1	BIT(1)
118 #define AD7173_GPIO_GP_DATA0	BIT(0)
119 
120 #define AD7173_GPO12_DATA(x)	BIT((x) + 0)
121 #define AD7173_GPO23_DATA(x)	BIT((x) + 4)
122 #define AD4111_GPO01_DATA(x)	BIT((x) + 6)
123 #define AD7173_GPO_DATA(x)	((x) < 2 ? AD7173_GPO12_DATA(x) : AD7173_GPO23_DATA(x))
124 
125 #define AD7173_INTERFACE_DATA_STAT	BIT(6)
126 #define AD7173_INTERFACE_DATA_STAT_EN(x) \
127 	FIELD_PREP(AD7173_INTERFACE_DATA_STAT, x)
128 
129 #define AD7173_SETUP_BIPOLAR		BIT(12)
130 #define AD7173_SETUP_AREF_BUF_MASK	GENMASK(11, 10)
131 #define AD7173_SETUP_AIN_BUF_MASK	GENMASK(9, 8)
132 
133 #define AD7173_SETUP_REF_SEL_MASK	GENMASK(5, 4)
134 #define AD7173_SETUP_REF_SEL_AVDD1_AVSS	0x3
135 #define AD7173_SETUP_REF_SEL_INT_REF	0x2
136 #define AD7173_SETUP_REF_SEL_EXT_REF2	0x1
137 #define AD7173_SETUP_REF_SEL_EXT_REF	0x0
138 #define AD7173_VOLTAGE_INT_REF_uV	2500000
139 #define AD7173_TEMP_SENSIIVITY_uV_per_C	477
140 #define AD7177_ODR_START_VALUE		0x07
141 #define AD4111_SHUNT_RESISTOR_OHM	50
142 #define AD4111_DIVIDER_RATIO		10
143 #define AD4111_CURRENT_CHAN_CUTOFF	16
144 #define AD4111_VINCOM_INPUT		0x10
145 
146 /* pin <  num_voltage_in is a normal voltage input */
147 /* pin >= num_voltage_in_div is a voltage input without a divider */
148 #define AD4111_IS_VINCOM_MISMATCH(pin1, pin2) ((pin1) == AD4111_VINCOM_INPUT && \
149 					       (pin2) < st->info->num_voltage_in && \
150 					       (pin2) >= st->info->num_voltage_in_div)
151 
152 #define AD7173_FILTER_SINC3_MAP		BIT(15)
153 #define AD7173_FILTER_SINC3_MAP_DIV	GENMASK(14, 0)
154 #define AD7173_FILTER_ENHFILTEN		BIT(11)
155 #define AD7173_FILTER_ENHFILT_MASK	GENMASK(10, 8)
156 #define AD7173_FILTER_ORDER		BIT(6)
157 #define AD7173_FILTER_ODR_MASK		GENMASK(5, 0)
158 #define AD7173_MAX_CONFIGS		8
159 #define AD4111_OW_DET_THRSH_MV		300
160 
161 #define AD7173_MODE_CAL_INT_ZERO		0x4 /* Internal Zero-Scale Calibration */
162 #define AD7173_MODE_CAL_INT_FULL		0x5 /* Internal Full-Scale Calibration */
163 #define AD7173_MODE_CAL_SYS_ZERO		0x6 /* System Zero-Scale Calibration */
164 #define AD7173_MODE_CAL_SYS_FULL		0x7 /* System Full-Scale Calibration */
165 
166 struct ad7173_device_info {
167 	const unsigned int *sinc5_data_rates;
168 	unsigned int num_sinc5_data_rates;
169 	unsigned int odr_start_value;
170 	/*
171 	 * AD4116 has both inputs with a voltage divider and without.
172 	 * These inputs cannot be mixed in the channel configuration.
173 	 * Does not include the VINCOM input.
174 	 */
175 	unsigned int num_voltage_in_div;
176 	unsigned int num_channels;
177 	unsigned int num_configs;
178 	unsigned int num_voltage_in;
179 	unsigned int clock;
180 	unsigned int id;
181 	char *name;
182 	const struct ad_sigma_delta_info *sd_info;
183 	bool has_current_inputs;
184 	bool has_vincom_input;
185 	bool has_temp;
186 	/* ((AVDD1 − AVSS)/5) */
187 	bool has_pow_supply_monitoring;
188 	bool data_reg_only_16bit;
189 	bool has_input_buf;
190 	bool has_int_ref;
191 	bool has_ref2;
192 	bool has_internal_fs_calibration;
193 	bool has_openwire_det;
194 	bool higher_gpio_bits;
195 	u8 num_gpios;
196 };
197 
198 enum ad7173_filter_type {
199 	AD7173_FILTER_SINC3,
200 	AD7173_FILTER_SINC5_SINC1,
201 	AD7173_FILTER_SINC5_SINC1_PF1,
202 	AD7173_FILTER_SINC5_SINC1_PF2,
203 	AD7173_FILTER_SINC5_SINC1_PF3,
204 	AD7173_FILTER_SINC5_SINC1_PF4,
205 };
206 
207 struct ad7173_channel_config {
208 	/* Openwire detection threshold */
209 	unsigned int openwire_thrsh_raw;
210 	int openwire_comp_chan;
211 	u8 cfg_slot;
212 	bool live;
213 
214 	/*
215 	 * Following fields are used to compare equality. If you
216 	 * make adaptations in it, you most likely also have to adapt
217 	 * ad7173_is_setup_equal(), too.
218 	 */
219 	struct_group(config_props,
220 		bool bipolar;
221 		bool input_buf;
222 		u16 sinc3_odr_div;
223 		u8 sinc5_odr_index;
224 		u8 ref_sel;
225 		enum ad7173_filter_type filter_type;
226 	);
227 };
228 
229 struct ad7173_channel {
230 	unsigned int ain;
231 	struct ad7173_channel_config cfg;
232 	u8 syscalib_mode;
233 	bool openwire_det_en;
234 };
235 
236 struct ad7173_state {
237 	struct ad_sigma_delta sd;
238 	const struct ad7173_device_info *info;
239 	struct ad7173_channel *channels;
240 	struct regulator_bulk_data regulators[3];
241 	unsigned int adc_mode;
242 	unsigned int interface_mode;
243 	unsigned int num_channels;
244 	struct ida cfg_slots_status;
245 	unsigned long long config_usage_counter;
246 	unsigned long long *config_cnts;
247 	struct clk_hw int_clk_hw;
248 	struct regmap *reg_gpiocon_regmap;
249 	struct gpio_regmap *gpio_regmap;
250 };
251 
252 static unsigned int ad4115_sinc5_data_rates[] = {
253 	24845000, 24845000, 20725000, 20725000,	/*  0-3  */
254 	15564000, 13841000, 10390000, 10390000,	/*  4-7  */
255 	4994000,  2499000,  1000000,  500000,	/*  8-11 */
256 	395500,   200000,   100000,   59890,	/* 12-15 */
257 	49920,    20000,    16660,    10000,	/* 16-19 */
258 	5000,	  2500,     2500,		/* 20-22 */
259 };
260 
261 static unsigned int ad4116_sinc5_data_rates[] = {
262 	12422360, 12422360, 12422360, 12422360,	/*  0-3  */
263 	10362690, 10362690, 7782100,  6290530,	/*  4-7  */
264 	5194800,  2496900,  1007600,  499900,	/*  8-11 */
265 	390600,	  200300,   100000,   59750,	/* 12-15 */
266 	49840,	  20000,    16650,    10000,	/* 16-19 */
267 	5000,	  2500,	    1250,		/* 20-22 */
268 };
269 
270 static const unsigned int ad7173_sinc5_data_rates[] = {
271 	6211000, 6211000, 6211000, 6211000, 6211000, 6211000, 5181000, 4444000,	/*  0-7  */
272 	3115000, 2597000, 1007000, 503800,  381000,  200300,  100500,  59520,	/*  8-15 */
273 	49680,	 20010,	  16333,   10000,   5000,    2500,    1250,		/* 16-22 */
274 };
275 
276 static const unsigned int ad7175_sinc5_data_rates[] = {
277 	50000000, 41667000, 31250000, 27778000,	/*  0-3  */
278 	20833000, 17857000, 12500000, 10000000,	/*  4-7  */
279 	5000000,  2500000,  1000000,  500000,	/*  8-11 */
280 	397500,   200000,   100000,   59920,	/* 12-15 */
281 	49960,    20000,    16666,    10000,	/* 16-19 */
282 	5000,					/* 20    */
283 };
284 
285 /**
286  * ad7173_sinc3_odr_div_from_odr() - Convert ODR to divider value
287  * @odr_millihz: ODR (sampling_frequency) in milliHz
288  * Returns: Divider value for SINC3 filter to pass.
289  */
290 static u16 ad7173_sinc3_odr_div_from_odr(u32 odr_millihz)
291 {
292 	/*
293 	 * Divider is f_MOD (1 MHz) / 32 / ODR. ODR freq is in milliHz, so
294 	 * we need to convert f_MOD to the same units. When SING_CYC=1 or
295 	 * multiple channels are enabled (currently always the case), there
296 	 * is an additional factor of 3.
297 	 */
298 	u32 div = DIV_ROUND_CLOSEST(MEGA * MILLI, odr_millihz * 32 * 3);
299 	/* Avoid divide by 0 and limit to register field size. */
300 	return clamp(div, 1U, AD7173_FILTER_SINC3_MAP_DIV);
301 }
302 
303 static unsigned int ad4111_current_channel_config[] = {
304 	/* Ain sel: pos        neg    */
305 	0x1E8, /* 15:IIN0+    8:IIN0− */
306 	0x1C9, /* 14:IIN1+    9:IIN1− */
307 	0x1AA, /* 13:IIN2+   10:IIN2− */
308 	0x18B, /* 12:IIN3+   11:IIN3− */
309 };
310 
311 static const char *const ad7173_ref_sel_str[] = {
312 	[AD7173_SETUP_REF_SEL_EXT_REF]    = "vref",
313 	[AD7173_SETUP_REF_SEL_EXT_REF2]   = "vref2",
314 	[AD7173_SETUP_REF_SEL_INT_REF]    = "refout-avss",
315 	[AD7173_SETUP_REF_SEL_AVDD1_AVSS] = "avdd",
316 };
317 
318 static const char *const ad7173_clk_sel[] = {
319 	"ext-clk", "xtal"
320 };
321 
322 static const struct regmap_range ad7173_range_gpio[] = {
323 	regmap_reg_range(AD7173_REG_GPIO, AD7173_REG_GPIO),
324 };
325 
326 static const struct regmap_access_table ad7173_access_table = {
327 	.yes_ranges = ad7173_range_gpio,
328 	.n_yes_ranges = ARRAY_SIZE(ad7173_range_gpio),
329 };
330 
331 static const struct regmap_config ad7173_regmap_config = {
332 	.reg_bits = 8,
333 	.val_bits = 16,
334 	.rd_table = &ad7173_access_table,
335 	.wr_table = &ad7173_access_table,
336 	.read_flag_mask = BIT(6),
337 };
338 
339 enum {
340 	AD7173_SYSCALIB_ZERO_SCALE,
341 	AD7173_SYSCALIB_FULL_SCALE,
342 };
343 
344 static const char * const ad7173_syscalib_modes[] = {
345 	[AD7173_SYSCALIB_ZERO_SCALE] = "zero_scale",
346 	[AD7173_SYSCALIB_FULL_SCALE] = "full_scale",
347 };
348 
349 static int ad7173_set_syscalib_mode(struct iio_dev *indio_dev,
350 				    const struct iio_chan_spec *chan,
351 				    unsigned int mode)
352 {
353 	struct ad7173_state *st = iio_priv(indio_dev);
354 
355 	st->channels[chan->address].syscalib_mode = mode;
356 
357 	return 0;
358 }
359 
360 static int ad7173_get_syscalib_mode(struct iio_dev *indio_dev,
361 				    const struct iio_chan_spec *chan)
362 {
363 	struct ad7173_state *st = iio_priv(indio_dev);
364 
365 	return st->channels[chan->address].syscalib_mode;
366 }
367 
368 static ssize_t ad7173_write_syscalib(struct iio_dev *indio_dev,
369 				     uintptr_t private,
370 				     const struct iio_chan_spec *chan,
371 				     const char *buf, size_t len)
372 {
373 	struct ad7173_state *st = iio_priv(indio_dev);
374 	bool sys_calib;
375 	int ret, mode;
376 
377 	ret = kstrtobool(buf, &sys_calib);
378 	if (ret)
379 		return ret;
380 
381 	if (!iio_device_claim_direct(indio_dev))
382 		return -EBUSY;
383 
384 	mode = st->channels[chan->address].syscalib_mode;
385 	if (sys_calib) {
386 		if (mode == AD7173_SYSCALIB_ZERO_SCALE)
387 			ret = ad_sd_calibrate(&st->sd, AD7173_MODE_CAL_SYS_ZERO,
388 					      chan->address);
389 		else
390 			ret = ad_sd_calibrate(&st->sd, AD7173_MODE_CAL_SYS_FULL,
391 					      chan->address);
392 	}
393 
394 	iio_device_release_direct(indio_dev);
395 
396 	return ret ? : len;
397 }
398 
399 static const struct iio_enum ad7173_syscalib_mode_enum = {
400 	.items = ad7173_syscalib_modes,
401 	.num_items = ARRAY_SIZE(ad7173_syscalib_modes),
402 	.set = ad7173_set_syscalib_mode,
403 	.get = ad7173_get_syscalib_mode
404 };
405 
406 static const char * const ad7173_filter_types_str[] = {
407 	[AD7173_FILTER_SINC3] = "sinc3",
408 	[AD7173_FILTER_SINC5_SINC1] = "sinc5+sinc1",
409 	[AD7173_FILTER_SINC5_SINC1_PF1] = "sinc5+sinc1+pf1",
410 	[AD7173_FILTER_SINC5_SINC1_PF2] = "sinc5+sinc1+pf2",
411 	[AD7173_FILTER_SINC5_SINC1_PF3] = "sinc5+sinc1+pf3",
412 	[AD7173_FILTER_SINC5_SINC1_PF4] = "sinc5+sinc1+pf4",
413 };
414 
415 static int ad7173_set_filter_type(struct iio_dev *indio_dev,
416 				  const struct iio_chan_spec *chan,
417 				  unsigned int val)
418 {
419 	struct ad7173_state *st = iio_priv(indio_dev);
420 
421 	if (!iio_device_claim_direct(indio_dev))
422 		return -EBUSY;
423 
424 	st->channels[chan->address].cfg.filter_type = val;
425 	st->channels[chan->address].cfg.live = false;
426 
427 	iio_device_release_direct(indio_dev);
428 
429 	return 0;
430 }
431 
432 static int ad7173_get_filter_type(struct iio_dev *indio_dev,
433 				  const struct iio_chan_spec *chan)
434 {
435 	struct ad7173_state *st = iio_priv(indio_dev);
436 
437 	return st->channels[chan->address].cfg.filter_type;
438 }
439 
440 static const struct iio_enum ad7173_filter_type_enum = {
441 	.items = ad7173_filter_types_str,
442 	.num_items = ARRAY_SIZE(ad7173_filter_types_str),
443 	.set = ad7173_set_filter_type,
444 	.get = ad7173_get_filter_type,
445 };
446 
447 static const struct iio_chan_spec_ext_info ad7173_chan_spec_ext_info[] = {
448 	{
449 		.name = "sys_calibration",
450 		.write = ad7173_write_syscalib,
451 		.shared = IIO_SEPARATE,
452 	},
453 	IIO_ENUM("sys_calibration_mode", IIO_SEPARATE,
454 		 &ad7173_syscalib_mode_enum),
455 	IIO_ENUM_AVAILABLE("sys_calibration_mode", IIO_SHARED_BY_TYPE,
456 			   &ad7173_syscalib_mode_enum),
457 	IIO_ENUM("filter_type", IIO_SEPARATE, &ad7173_filter_type_enum),
458 	IIO_ENUM_AVAILABLE("filter_type", IIO_SHARED_BY_TYPE,
459 			   &ad7173_filter_type_enum),
460 	{ }
461 };
462 
463 static const struct iio_chan_spec_ext_info ad7173_temp_chan_spec_ext_info[] = {
464 	IIO_ENUM("filter_type", IIO_SEPARATE, &ad7173_filter_type_enum),
465 	IIO_ENUM_AVAILABLE("filter_type", IIO_SHARED_BY_TYPE,
466 			   &ad7173_filter_type_enum),
467 	{ }
468 };
469 
470 static int ad7173_calibrate_all(struct ad7173_state *st, struct iio_dev *indio_dev)
471 {
472 	int ret;
473 	int i;
474 
475 	for (i = 0; i < st->num_channels; i++) {
476 		if (indio_dev->channels[i].type != IIO_VOLTAGE)
477 			continue;
478 
479 		ret = ad_sd_calibrate(&st->sd, AD7173_MODE_CAL_INT_ZERO, i);
480 		if (ret < 0)
481 			return ret;
482 
483 		if (st->info->has_internal_fs_calibration) {
484 			ret = ad_sd_calibrate(&st->sd, AD7173_MODE_CAL_INT_FULL, i);
485 			if (ret < 0)
486 				return ret;
487 		}
488 	}
489 
490 	return 0;
491 }
492 
493 /*
494  * Associative array of channel pairs for open wire detection
495  * The array is indexed by ain and gives the associated channel pair
496  * to perform the open wire detection with
497  * the channel pair [0] is for non differential and pair [1]
498  * is for differential inputs
499  */
500 static int openwire_ain_to_channel_pair[][2][2] = {
501 /*	AIN      Single      Differential */
502 	[0] = { { 0, 15 },  { 1, 2 }   },
503 	[1] = { { 1, 2 },   { 2, 1 }   },
504 	[2] = { { 3, 4 },   { 5, 6 }   },
505 	[3] = { { 5, 6 },   { 6, 5 }   },
506 	[4] = { { 7, 8 },   { 9, 10 }  },
507 	[5] = { { 9, 10 },  { 10, 9 }  },
508 	[6] = { { 11, 12 }, { 13, 14 } },
509 	[7] = { { 13, 14 }, { 14, 13 } },
510 };
511 
512 /*
513  * Openwire detection on ad4111 works by running the same input measurement
514  * on two different channels and compare if the difference between the two
515  * measurements exceeds a certain value (typical 300mV)
516  */
517 static int ad4111_openwire_event(struct iio_dev *indio_dev,
518 				 const struct iio_chan_spec *chan)
519 {
520 	struct ad7173_state *st = iio_priv(indio_dev);
521 	struct ad7173_channel *adchan = &st->channels[chan->address];
522 	struct ad7173_channel_config *cfg = &adchan->cfg;
523 	int ret, val1, val2;
524 
525 	ret = regmap_set_bits(st->reg_gpiocon_regmap, AD7173_REG_GPIO,
526 			      AD4111_GPIO_GP_OW_EN);
527 	if (ret)
528 		return ret;
529 
530 	adchan->cfg.openwire_comp_chan =
531 		openwire_ain_to_channel_pair[chan->channel][chan->differential][0];
532 
533 	ret = ad_sigma_delta_single_conversion(indio_dev, chan, &val1);
534 	if (ret < 0) {
535 		dev_err(&indio_dev->dev,
536 			"Error running ad_sigma_delta single conversion: %d", ret);
537 		goto out;
538 	}
539 
540 	adchan->cfg.openwire_comp_chan =
541 		openwire_ain_to_channel_pair[chan->channel][chan->differential][1];
542 
543 	ret = ad_sigma_delta_single_conversion(indio_dev, chan, &val2);
544 	if (ret < 0) {
545 		dev_err(&indio_dev->dev,
546 			"Error running ad_sigma_delta single conversion: %d", ret);
547 		goto out;
548 	}
549 
550 	if (abs(val1 - val2) > cfg->openwire_thrsh_raw)
551 		iio_push_event(indio_dev,
552 			       IIO_UNMOD_EVENT_CODE(IIO_VOLTAGE, chan->address,
553 						    IIO_EV_TYPE_FAULT, IIO_EV_DIR_FAULT_OPENWIRE),
554 			       iio_get_time_ns(indio_dev));
555 
556 out:
557 	adchan->cfg.openwire_comp_chan = -1;
558 	regmap_clear_bits(st->reg_gpiocon_regmap, AD7173_REG_GPIO,
559 			  AD4111_GPIO_GP_OW_EN);
560 	return ret;
561 }
562 
563 static int ad7173_mask_xlate(struct gpio_regmap *gpio, enum gpio_regmap_operation op,
564 			     unsigned int base, unsigned int offset, unsigned int *reg,
565 			     unsigned int *mask)
566 {
567 	*mask = AD7173_GPO_DATA(offset);
568 	*reg = base;
569 	return 0;
570 }
571 
572 static int ad4111_mask_xlate(struct gpio_regmap *gpio, enum gpio_regmap_operation op,
573 			     unsigned int base, unsigned int offset, unsigned int *reg,
574 			     unsigned int *mask)
575 {
576 	*mask = AD4111_GPO01_DATA(offset);
577 	*reg = base;
578 	return 0;
579 }
580 
581 static void ad7173_gpio_disable(void *data)
582 {
583 	struct ad7173_state *st = data;
584 	unsigned int mask;
585 
586 	mask = AD7173_GPIO_OP_EN0 | AD7173_GPIO_OP_EN1 | AD7173_GPIO_OP_EN2_3;
587 	regmap_update_bits(st->reg_gpiocon_regmap, AD7173_REG_GPIO, mask, ~mask);
588 }
589 
590 static int ad7173_gpio_init(struct ad7173_state *st)
591 {
592 	struct gpio_regmap_config gpio_regmap = {};
593 	struct device *dev = &st->sd.spi->dev;
594 	unsigned int mask;
595 	int ret;
596 
597 	st->reg_gpiocon_regmap = devm_regmap_init_spi(st->sd.spi, &ad7173_regmap_config);
598 	ret = PTR_ERR_OR_ZERO(st->reg_gpiocon_regmap);
599 	if (ret)
600 		return dev_err_probe(dev, ret, "Unable to init regmap\n");
601 
602 	mask = AD7173_GPIO_OP_EN0 | AD7173_GPIO_OP_EN1 | AD7173_GPIO_OP_EN2_3;
603 	regmap_update_bits(st->reg_gpiocon_regmap, AD7173_REG_GPIO, mask, mask);
604 
605 	ret = devm_add_action_or_reset(dev, ad7173_gpio_disable, st);
606 	if (ret)
607 		return ret;
608 
609 	gpio_regmap.parent = dev;
610 	gpio_regmap.regmap = st->reg_gpiocon_regmap;
611 	gpio_regmap.ngpio = st->info->num_gpios;
612 	gpio_regmap.reg_set_base = AD7173_REG_GPIO;
613 	if (st->info->higher_gpio_bits)
614 		gpio_regmap.reg_mask_xlate = ad4111_mask_xlate;
615 	else
616 		gpio_regmap.reg_mask_xlate = ad7173_mask_xlate;
617 
618 	st->gpio_regmap = devm_gpio_regmap_register(dev, &gpio_regmap);
619 	ret = PTR_ERR_OR_ZERO(st->gpio_regmap);
620 	if (ret)
621 		return dev_err_probe(dev, ret, "Unable to init gpio-regmap\n");
622 
623 	return 0;
624 }
625 
626 static struct ad7173_state *ad_sigma_delta_to_ad7173(struct ad_sigma_delta *sd)
627 {
628 	return container_of(sd, struct ad7173_state, sd);
629 }
630 
631 static struct ad7173_state *clk_hw_to_ad7173(struct clk_hw *hw)
632 {
633 	return container_of(hw, struct ad7173_state, int_clk_hw);
634 }
635 
636 static void ad7173_ida_destroy(void *data)
637 {
638 	struct ad7173_state *st = data;
639 
640 	ida_destroy(&st->cfg_slots_status);
641 }
642 
643 static void ad7173_reset_usage_cnts(struct ad7173_state *st)
644 {
645 	memset64(st->config_cnts, 0, st->info->num_configs);
646 	st->config_usage_counter = 0;
647 }
648 
649 /**
650  * ad7173_is_setup_equal - Compare two channel setups
651  * @cfg1: First channel configuration
652  * @cfg2: Second channel configuration
653  *
654  * Compares all configuration options that affect the registers connected to
655  * SETUP_SEL, namely CONFIGx, FILTERx, GAINx and OFFSETx.
656  *
657  * Returns: true if the setups are identical, false otherwise
658  */
659 static bool ad7173_is_setup_equal(const struct ad7173_channel_config *cfg1,
660 				  const struct ad7173_channel_config *cfg2)
661 {
662 	/*
663 	 * This is just to make sure that the comparison is adapted after
664 	 * struct ad7173_channel_config was changed.
665 	 */
666 	static_assert(sizeof_field(struct ad7173_channel_config, config_props) ==
667 		      sizeof(struct {
668 				     bool bipolar;
669 				     bool input_buf;
670 				     u16 sinc3_odr_div;
671 				     u8 sinc5_odr_index;
672 				     u8 ref_sel;
673 				     enum ad7173_filter_type filter_type;
674 			     }));
675 
676 	return cfg1->bipolar == cfg2->bipolar &&
677 	       cfg1->input_buf == cfg2->input_buf &&
678 	       cfg1->sinc3_odr_div == cfg2->sinc3_odr_div &&
679 	       cfg1->sinc5_odr_index == cfg2->sinc5_odr_index &&
680 	       cfg1->ref_sel == cfg2->ref_sel &&
681 	       cfg1->filter_type == cfg2->filter_type;
682 }
683 
684 static struct ad7173_channel_config *
685 ad7173_find_live_config(struct ad7173_state *st, struct ad7173_channel_config *cfg)
686 {
687 	struct ad7173_channel_config *cfg_aux;
688 	int i;
689 
690 	for (i = 0; i < st->num_channels; i++) {
691 		cfg_aux = &st->channels[i].cfg;
692 
693 		if (cfg_aux->live && ad7173_is_setup_equal(cfg, cfg_aux))
694 			return cfg_aux;
695 	}
696 	return NULL;
697 }
698 
699 /* Could be replaced with a generic LRU implementation */
700 static int ad7173_free_config_slot_lru(struct ad7173_state *st)
701 {
702 	int i, lru_position = 0;
703 
704 	for (i = 1; i < st->info->num_configs; i++)
705 		if (st->config_cnts[i] < st->config_cnts[lru_position])
706 			lru_position = i;
707 
708 	for (i = 0; i < st->num_channels; i++)
709 		if (st->channels[i].cfg.cfg_slot == lru_position)
710 			st->channels[i].cfg.live = false;
711 
712 	ida_free(&st->cfg_slots_status, lru_position);
713 	return ida_alloc(&st->cfg_slots_status, GFP_KERNEL);
714 }
715 
716 /* Could be replaced with a generic LRU implementation */
717 static int ad7173_load_config(struct ad7173_state *st,
718 			      struct ad7173_channel_config *cfg)
719 {
720 	unsigned int config;
721 	int free_cfg_slot, ret;
722 	u8 post_filter_enable, post_filter_select;
723 
724 	free_cfg_slot = ida_alloc_range(&st->cfg_slots_status, 0,
725 					st->info->num_configs - 1, GFP_KERNEL);
726 	if (free_cfg_slot < 0)
727 		free_cfg_slot = ad7173_free_config_slot_lru(st);
728 
729 	cfg->cfg_slot = free_cfg_slot;
730 	config = FIELD_PREP(AD7173_SETUP_REF_SEL_MASK, cfg->ref_sel);
731 
732 	if (cfg->bipolar)
733 		config |= AD7173_SETUP_BIPOLAR;
734 
735 	if (cfg->input_buf)
736 		config |= AD7173_SETUP_AIN_BUF_MASK;
737 
738 	ret = ad_sd_write_reg(&st->sd, AD7173_REG_SETUP(free_cfg_slot), 2, config);
739 	if (ret)
740 		return ret;
741 
742 	/*
743 	 * When SINC3_MAP flag is enabled, the rest of the register has a
744 	 * different meaning. We are using this option to allow the most
745 	 * possible sampling frequencies with SINC3 filter.
746 	 */
747 	if (cfg->filter_type == AD7173_FILTER_SINC3)
748 		return ad_sd_write_reg(&st->sd, AD7173_REG_FILTER(free_cfg_slot), 2,
749 				       FIELD_PREP(AD7173_FILTER_SINC3_MAP, 1) |
750 				       FIELD_PREP(AD7173_FILTER_SINC3_MAP_DIV,
751 						  cfg->sinc3_odr_div));
752 
753 	switch (cfg->filter_type) {
754 	case AD7173_FILTER_SINC5_SINC1_PF1:
755 		post_filter_enable = 1;
756 		post_filter_select = 2;
757 		break;
758 	case AD7173_FILTER_SINC5_SINC1_PF2:
759 		post_filter_enable = 1;
760 		post_filter_select = 3;
761 		break;
762 	case AD7173_FILTER_SINC5_SINC1_PF3:
763 		post_filter_enable = 1;
764 		post_filter_select = 5;
765 		break;
766 	case AD7173_FILTER_SINC5_SINC1_PF4:
767 		post_filter_enable = 1;
768 		post_filter_select = 6;
769 		break;
770 	default:
771 		post_filter_enable = 0;
772 		post_filter_select = 0;
773 		break;
774 	}
775 
776 	return ad_sd_write_reg(&st->sd, AD7173_REG_FILTER(free_cfg_slot), 2,
777 			       FIELD_PREP(AD7173_FILTER_SINC3_MAP, 0) |
778 			       FIELD_PREP(AD7173_FILTER_ENHFILT_MASK,
779 					  post_filter_enable) |
780 			       FIELD_PREP(AD7173_FILTER_ENHFILTEN,
781 					  post_filter_select) |
782 			       FIELD_PREP(AD7173_FILTER_ORDER, 0) |
783 			       FIELD_PREP(AD7173_FILTER_ODR_MASK,
784 					  cfg->sinc5_odr_index));
785 }
786 
787 static int ad7173_config_channel(struct ad7173_state *st, int addr)
788 {
789 	struct ad7173_channel_config *cfg = &st->channels[addr].cfg;
790 	struct ad7173_channel_config *live_cfg;
791 	int ret;
792 
793 	if (!cfg->live) {
794 		live_cfg = ad7173_find_live_config(st, cfg);
795 		if (live_cfg) {
796 			cfg->cfg_slot = live_cfg->cfg_slot;
797 		} else {
798 			ret = ad7173_load_config(st, cfg);
799 			if (ret)
800 				return ret;
801 			cfg->live = true;
802 		}
803 	}
804 
805 	if (st->config_usage_counter == U64_MAX)
806 		ad7173_reset_usage_cnts(st);
807 
808 	st->config_usage_counter++;
809 	st->config_cnts[cfg->cfg_slot] = st->config_usage_counter;
810 
811 	return 0;
812 }
813 
814 static int ad7173_set_channel(struct ad_sigma_delta *sd, unsigned int channel)
815 {
816 	struct ad7173_state *st = ad_sigma_delta_to_ad7173(sd);
817 	unsigned int val;
818 	int ret;
819 
820 	ret = ad7173_config_channel(st, channel);
821 	if (ret)
822 		return ret;
823 
824 	val = AD7173_CH_ENABLE |
825 	      FIELD_PREP(AD7173_CH_SETUP_SEL_MASK, st->channels[channel].cfg.cfg_slot) |
826 	      st->channels[channel].ain;
827 
828 	if (st->channels[channel].cfg.openwire_comp_chan >= 0)
829 		channel = st->channels[channel].cfg.openwire_comp_chan;
830 
831 	return ad_sd_write_reg(&st->sd, AD7173_REG_CH(channel), 2, val);
832 }
833 
834 static int ad7173_set_mode(struct ad_sigma_delta *sd,
835 			   enum ad_sigma_delta_mode mode)
836 {
837 	struct ad7173_state *st = ad_sigma_delta_to_ad7173(sd);
838 
839 	st->adc_mode &= ~AD7173_ADC_MODE_MODE_MASK;
840 	st->adc_mode |= FIELD_PREP(AD7173_ADC_MODE_MODE_MASK, mode);
841 
842 	return ad_sd_write_reg(&st->sd, AD7173_REG_ADC_MODE, 2, st->adc_mode);
843 }
844 
845 static int ad7173_append_status(struct ad_sigma_delta *sd, bool append)
846 {
847 	struct ad7173_state *st = ad_sigma_delta_to_ad7173(sd);
848 	unsigned int interface_mode = st->interface_mode;
849 	int ret;
850 
851 	interface_mode &= ~AD7173_INTERFACE_DATA_STAT;
852 	interface_mode |= AD7173_INTERFACE_DATA_STAT_EN(append);
853 	ret = ad_sd_write_reg(&st->sd, AD7173_REG_INTERFACE_MODE, 2, interface_mode);
854 	if (ret)
855 		return ret;
856 
857 	st->interface_mode = interface_mode;
858 
859 	return 0;
860 }
861 
862 static int ad7173_disable_all(struct ad_sigma_delta *sd)
863 {
864 	struct ad7173_state *st = ad_sigma_delta_to_ad7173(sd);
865 	int ret;
866 	int i;
867 
868 	for (i = 0; i < st->num_channels; i++) {
869 		ret = ad_sd_write_reg(sd, AD7173_REG_CH(i), 2, 0);
870 		if (ret < 0)
871 			return ret;
872 	}
873 
874 	return 0;
875 }
876 
877 static int ad7173_disable_one(struct ad_sigma_delta *sd, unsigned int chan)
878 {
879 	struct ad7173_state *st = ad_sigma_delta_to_ad7173(sd);
880 
881 	if (st->channels[chan].cfg.openwire_comp_chan >= 0)
882 		chan = st->channels[chan].cfg.openwire_comp_chan;
883 
884 	return ad_sd_write_reg(sd, AD7173_REG_CH(chan), 2, 0);
885 }
886 
887 static const struct ad_sigma_delta_info ad7173_sigma_delta_info_4_slots = {
888 	.set_channel = ad7173_set_channel,
889 	.append_status = ad7173_append_status,
890 	.disable_all = ad7173_disable_all,
891 	.disable_one = ad7173_disable_one,
892 	.set_mode = ad7173_set_mode,
893 	.has_registers = true,
894 	.has_named_irqs = true,
895 	.supports_spi_offload = true,
896 	.addr_shift = 0,
897 	.read_mask = BIT(6),
898 	.status_ch_mask = GENMASK(3, 0),
899 	.data_reg = AD7173_REG_DATA,
900 	.num_resetclks = 64,
901 	.num_slots = 4,
902 };
903 
904 static const struct ad_sigma_delta_info ad7173_sigma_delta_info_8_slots = {
905 	.set_channel = ad7173_set_channel,
906 	.append_status = ad7173_append_status,
907 	.disable_all = ad7173_disable_all,
908 	.disable_one = ad7173_disable_one,
909 	.set_mode = ad7173_set_mode,
910 	.has_registers = true,
911 	.has_named_irqs = true,
912 	.supports_spi_offload = true,
913 	.addr_shift = 0,
914 	.read_mask = BIT(6),
915 	.status_ch_mask = GENMASK(3, 0),
916 	.data_reg = AD7173_REG_DATA,
917 	.num_resetclks = 64,
918 	.num_slots = 8,
919 };
920 
921 static const struct ad_sigma_delta_info ad7173_sigma_delta_info_16_slots = {
922 	.set_channel = ad7173_set_channel,
923 	.append_status = ad7173_append_status,
924 	.disable_all = ad7173_disable_all,
925 	.disable_one = ad7173_disable_one,
926 	.set_mode = ad7173_set_mode,
927 	.has_registers = true,
928 	.has_named_irqs = true,
929 	.supports_spi_offload = true,
930 	.addr_shift = 0,
931 	.read_mask = BIT(6),
932 	.status_ch_mask = GENMASK(3, 0),
933 	.data_reg = AD7173_REG_DATA,
934 	.num_resetclks = 64,
935 	.num_slots = 16,
936 };
937 
938 static const struct ad7173_device_info ad4111_device_info = {
939 	.name = "ad4111",
940 	.id = AD4111_ID,
941 	.sd_info = &ad7173_sigma_delta_info_16_slots,
942 	.num_voltage_in_div = 8,
943 	.num_channels = 16,
944 	.num_configs = 8,
945 	.num_voltage_in = 8,
946 	.num_gpios = 2,
947 	.higher_gpio_bits = true,
948 	.has_temp = true,
949 	.has_vincom_input = true,
950 	.has_input_buf = true,
951 	.has_current_inputs = true,
952 	.has_int_ref = true,
953 	.has_internal_fs_calibration = true,
954 	.has_openwire_det = true,
955 	.clock = 2 * HZ_PER_MHZ,
956 	.sinc5_data_rates = ad7173_sinc5_data_rates,
957 	.num_sinc5_data_rates = ARRAY_SIZE(ad7173_sinc5_data_rates),
958 };
959 
960 static const struct ad7173_device_info ad4112_device_info = {
961 	.name = "ad4112",
962 	.id = AD4112_ID,
963 	.sd_info = &ad7173_sigma_delta_info_16_slots,
964 	.num_voltage_in_div = 8,
965 	.num_channels = 16,
966 	.num_configs = 8,
967 	.num_voltage_in = 8,
968 	.num_gpios = 2,
969 	.higher_gpio_bits = true,
970 	.has_vincom_input = true,
971 	.has_temp = true,
972 	.has_input_buf = true,
973 	.has_current_inputs = true,
974 	.has_int_ref = true,
975 	.has_internal_fs_calibration = true,
976 	.clock = 2 * HZ_PER_MHZ,
977 	.sinc5_data_rates = ad7173_sinc5_data_rates,
978 	.num_sinc5_data_rates = ARRAY_SIZE(ad7173_sinc5_data_rates),
979 };
980 
981 static const struct ad7173_device_info ad4113_device_info = {
982 	.name = "ad4113",
983 	.id = AD4113_ID,
984 	.sd_info = &ad7173_sigma_delta_info_16_slots,
985 	.num_voltage_in_div = 8,
986 	.num_channels = 16,
987 	.num_configs = 8,
988 	.num_voltage_in = 8,
989 	.num_gpios = 2,
990 	.data_reg_only_16bit = true,
991 	.higher_gpio_bits = true,
992 	.has_vincom_input = true,
993 	.has_input_buf = true,
994 	.has_int_ref = true,
995 	.clock = 2 * HZ_PER_MHZ,
996 	.sinc5_data_rates = ad7173_sinc5_data_rates,
997 	.num_sinc5_data_rates = ARRAY_SIZE(ad7173_sinc5_data_rates),
998 };
999 
1000 static const struct ad7173_device_info ad4114_device_info = {
1001 	.name = "ad4114",
1002 	.id = AD4114_ID,
1003 	.sd_info = &ad7173_sigma_delta_info_16_slots,
1004 	.num_voltage_in_div = 16,
1005 	.num_channels = 16,
1006 	.num_configs = 8,
1007 	.num_voltage_in = 16,
1008 	.num_gpios = 4,
1009 	.has_vincom_input = true,
1010 	.has_temp = true,
1011 	.has_input_buf = true,
1012 	.has_int_ref = true,
1013 	.has_internal_fs_calibration = true,
1014 	.clock = 2 * HZ_PER_MHZ,
1015 	.sinc5_data_rates = ad7173_sinc5_data_rates,
1016 	.num_sinc5_data_rates = ARRAY_SIZE(ad7173_sinc5_data_rates),
1017 };
1018 
1019 static const struct ad7173_device_info ad4115_device_info = {
1020 	.name = "ad4115",
1021 	.id = AD4115_ID,
1022 	.sd_info = &ad7173_sigma_delta_info_16_slots,
1023 	.num_voltage_in_div = 16,
1024 	.num_channels = 16,
1025 	.num_configs = 8,
1026 	.num_voltage_in = 16,
1027 	.num_gpios = 4,
1028 	.has_vincom_input = true,
1029 	.has_temp = true,
1030 	.has_input_buf = true,
1031 	.has_int_ref = true,
1032 	.has_internal_fs_calibration = true,
1033 	.clock = 8 * HZ_PER_MHZ,
1034 	.sinc5_data_rates = ad4115_sinc5_data_rates,
1035 	.num_sinc5_data_rates = ARRAY_SIZE(ad4115_sinc5_data_rates),
1036 };
1037 
1038 static const struct ad7173_device_info ad4116_device_info = {
1039 	.name = "ad4116",
1040 	.id = AD4116_ID,
1041 	.sd_info = &ad7173_sigma_delta_info_16_slots,
1042 	.num_voltage_in_div = 11,
1043 	.num_channels = 16,
1044 	.num_configs = 8,
1045 	.num_voltage_in = 16,
1046 	.num_gpios = 4,
1047 	.has_vincom_input = true,
1048 	.has_temp = true,
1049 	.has_input_buf = true,
1050 	.has_int_ref = true,
1051 	.has_internal_fs_calibration = true,
1052 	.clock = 4 * HZ_PER_MHZ,
1053 	.sinc5_data_rates = ad4116_sinc5_data_rates,
1054 	.num_sinc5_data_rates = ARRAY_SIZE(ad4116_sinc5_data_rates),
1055 };
1056 
1057 static const struct ad7173_device_info ad7172_2_device_info = {
1058 	.name = "ad7172-2",
1059 	.id = AD7172_2_ID,
1060 	.sd_info = &ad7173_sigma_delta_info_4_slots,
1061 	.num_voltage_in = 5,
1062 	.num_channels = 4,
1063 	.num_configs = 4,
1064 	.num_gpios = 2,
1065 	.has_temp = true,
1066 	.has_input_buf = true,
1067 	.has_int_ref = true,
1068 	.has_pow_supply_monitoring = true,
1069 	.clock = 2 * HZ_PER_MHZ,
1070 	.sinc5_data_rates = ad7173_sinc5_data_rates,
1071 	.num_sinc5_data_rates = ARRAY_SIZE(ad7173_sinc5_data_rates),
1072 };
1073 
1074 static const struct ad7173_device_info ad7172_4_device_info = {
1075 	.name = "ad7172-4",
1076 	.id = AD7172_4_ID,
1077 	.sd_info = &ad7173_sigma_delta_info_8_slots,
1078 	.num_voltage_in = 9,
1079 	.num_channels = 8,
1080 	.num_configs = 8,
1081 	.num_gpios = 4,
1082 	.has_input_buf = true,
1083 	.has_ref2 = true,
1084 	.has_pow_supply_monitoring = true,
1085 	.clock = 2 * HZ_PER_MHZ,
1086 	.sinc5_data_rates = ad7173_sinc5_data_rates,
1087 	.num_sinc5_data_rates = ARRAY_SIZE(ad7173_sinc5_data_rates),
1088 };
1089 
1090 static const struct ad7173_device_info ad7173_8_device_info = {
1091 	.name = "ad7173-8",
1092 	.id = AD7173_ID,
1093 	.sd_info = &ad7173_sigma_delta_info_16_slots,
1094 	.num_voltage_in = 17,
1095 	.num_channels = 16,
1096 	.num_configs = 8,
1097 	.num_gpios = 4,
1098 	.has_temp = true,
1099 	.has_input_buf = true,
1100 	.has_int_ref = true,
1101 	.has_ref2 = true,
1102 	.clock = 2 * HZ_PER_MHZ,
1103 	.sinc5_data_rates = ad7173_sinc5_data_rates,
1104 	.num_sinc5_data_rates = ARRAY_SIZE(ad7173_sinc5_data_rates),
1105 };
1106 
1107 static const struct ad7173_device_info ad7175_2_device_info = {
1108 	.name = "ad7175-2",
1109 	.id = AD7175_2_ID,
1110 	.sd_info = &ad7173_sigma_delta_info_4_slots,
1111 	.num_voltage_in = 5,
1112 	.num_channels = 4,
1113 	.num_configs = 4,
1114 	.num_gpios = 2,
1115 	.has_temp = true,
1116 	.has_input_buf = true,
1117 	.has_int_ref = true,
1118 	.has_pow_supply_monitoring = true,
1119 	.clock = 16 * HZ_PER_MHZ,
1120 	.sinc5_data_rates = ad7175_sinc5_data_rates,
1121 	.num_sinc5_data_rates = ARRAY_SIZE(ad7175_sinc5_data_rates),
1122 };
1123 
1124 static const struct ad7173_device_info ad7175_8_device_info = {
1125 	.name = "ad7175-8",
1126 	.id = AD7175_8_ID,
1127 	.sd_info = &ad7173_sigma_delta_info_16_slots,
1128 	.num_voltage_in = 17,
1129 	.num_channels = 16,
1130 	.num_configs = 8,
1131 	.num_gpios = 4,
1132 	.has_temp = true,
1133 	.has_input_buf = true,
1134 	.has_int_ref = true,
1135 	.has_ref2 = true,
1136 	.has_pow_supply_monitoring = true,
1137 	.clock = 16 * HZ_PER_MHZ,
1138 	.sinc5_data_rates = ad7175_sinc5_data_rates,
1139 	.num_sinc5_data_rates = ARRAY_SIZE(ad7175_sinc5_data_rates),
1140 };
1141 
1142 static const struct ad7173_device_info ad7176_2_device_info = {
1143 	.name = "ad7176-2",
1144 	.id = AD7176_ID,
1145 	.sd_info = &ad7173_sigma_delta_info_4_slots,
1146 	.num_voltage_in = 5,
1147 	.num_channels = 4,
1148 	.num_configs = 4,
1149 	.num_gpios = 2,
1150 	.has_int_ref = true,
1151 	.clock = 16 * HZ_PER_MHZ,
1152 	.sinc5_data_rates = ad7175_sinc5_data_rates,
1153 	.num_sinc5_data_rates = ARRAY_SIZE(ad7175_sinc5_data_rates),
1154 };
1155 
1156 static const struct ad7173_device_info ad7177_2_device_info = {
1157 	.name = "ad7177-2",
1158 	.id = AD7177_ID,
1159 	.sd_info = &ad7173_sigma_delta_info_4_slots,
1160 	.num_voltage_in = 5,
1161 	.num_channels = 4,
1162 	.num_configs = 4,
1163 	.num_gpios = 2,
1164 	.has_temp = true,
1165 	.has_input_buf = true,
1166 	.has_int_ref = true,
1167 	.has_pow_supply_monitoring = true,
1168 	.clock = 16 * HZ_PER_MHZ,
1169 	.odr_start_value = AD7177_ODR_START_VALUE,
1170 	.sinc5_data_rates = ad7175_sinc5_data_rates,
1171 	.num_sinc5_data_rates = ARRAY_SIZE(ad7175_sinc5_data_rates),
1172 };
1173 
1174 static int ad7173_setup(struct iio_dev *indio_dev)
1175 {
1176 	struct ad7173_state *st = iio_priv(indio_dev);
1177 	struct device *dev = &st->sd.spi->dev;
1178 	u8 buf[AD7173_RESET_LENGTH];
1179 	unsigned int id;
1180 	int ret;
1181 
1182 	/* reset the serial interface */
1183 	memset(buf, 0xff, AD7173_RESET_LENGTH);
1184 	ret = spi_write_then_read(st->sd.spi, buf, sizeof(buf), NULL, 0);
1185 	if (ret < 0)
1186 		return ret;
1187 
1188 	/* datasheet recommends a delay of at least 500us after reset */
1189 	fsleep(500);
1190 
1191 	ret = ad_sd_read_reg(&st->sd, AD7173_REG_ID, 2, &id);
1192 	if (ret)
1193 		return ret;
1194 
1195 	id &= AD7173_ID_MASK;
1196 	if (id != st->info->id)
1197 		dev_warn(dev, "Unexpected device id: 0x%04X, expected: 0x%04X\n",
1198 			 id, st->info->id);
1199 
1200 	st->adc_mode |= AD7173_ADC_MODE_SING_CYC;
1201 	st->interface_mode = 0x0;
1202 
1203 	st->config_usage_counter = 0;
1204 	st->config_cnts = devm_kcalloc(dev, st->info->num_configs,
1205 				       sizeof(*st->config_cnts), GFP_KERNEL);
1206 	if (!st->config_cnts)
1207 		return -ENOMEM;
1208 
1209 	ret = ad7173_calibrate_all(st, indio_dev);
1210 	if (ret)
1211 		return ret;
1212 
1213 	/* All channels are enabled by default after a reset */
1214 	return ad7173_disable_all(&st->sd);
1215 }
1216 
1217 static unsigned int ad7173_get_ref_voltage_milli(struct ad7173_state *st,
1218 						 u8 reference_select)
1219 {
1220 	int vref;
1221 
1222 	switch (reference_select) {
1223 	case AD7173_SETUP_REF_SEL_EXT_REF:
1224 		vref = regulator_get_voltage(st->regulators[0].consumer);
1225 		break;
1226 
1227 	case AD7173_SETUP_REF_SEL_EXT_REF2:
1228 		vref = regulator_get_voltage(st->regulators[1].consumer);
1229 		break;
1230 
1231 	case AD7173_SETUP_REF_SEL_INT_REF:
1232 		vref = AD7173_VOLTAGE_INT_REF_uV;
1233 		break;
1234 
1235 	case AD7173_SETUP_REF_SEL_AVDD1_AVSS:
1236 		vref = regulator_get_voltage(st->regulators[2].consumer);
1237 		break;
1238 
1239 	default:
1240 		return -EINVAL;
1241 	}
1242 
1243 	if (vref < 0)
1244 		return vref;
1245 
1246 	return vref / (MICRO / MILLI);
1247 }
1248 
1249 static int ad7173_read_raw(struct iio_dev *indio_dev,
1250 			   struct iio_chan_spec const *chan,
1251 			   int *val, int *val2, long info)
1252 {
1253 	struct ad7173_state *st = iio_priv(indio_dev);
1254 	struct ad7173_channel *ch = &st->channels[chan->address];
1255 	unsigned int reg;
1256 	u64 temp;
1257 	int ret;
1258 
1259 	switch (info) {
1260 	case IIO_CHAN_INFO_RAW:
1261 		ret = ad_sigma_delta_single_conversion(indio_dev, chan, val);
1262 		if (ret < 0)
1263 			return ret;
1264 
1265 		if (ch->openwire_det_en) {
1266 			ret = ad4111_openwire_event(indio_dev, chan);
1267 			if (ret < 0)
1268 				return ret;
1269 		}
1270 
1271 		return IIO_VAL_INT;
1272 	case IIO_CHAN_INFO_SCALE:
1273 
1274 		switch (chan->type) {
1275 		case IIO_TEMP:
1276 			temp = AD7173_VOLTAGE_INT_REF_uV * MILLI;
1277 			temp /= AD7173_TEMP_SENSIIVITY_uV_per_C;
1278 			*val = temp;
1279 			*val2 = chan->scan_type.realbits;
1280 			return IIO_VAL_FRACTIONAL_LOG2;
1281 		case IIO_VOLTAGE:
1282 			*val = ad7173_get_ref_voltage_milli(st, ch->cfg.ref_sel);
1283 			*val2 = chan->scan_type.realbits - !!(ch->cfg.bipolar);
1284 
1285 			if (chan->channel < st->info->num_voltage_in_div)
1286 				*val *= AD4111_DIVIDER_RATIO;
1287 			return IIO_VAL_FRACTIONAL_LOG2;
1288 		case IIO_CURRENT:
1289 			*val = ad7173_get_ref_voltage_milli(st, ch->cfg.ref_sel);
1290 			*val /= AD4111_SHUNT_RESISTOR_OHM;
1291 			*val2 = chan->scan_type.realbits - ch->cfg.bipolar;
1292 			return IIO_VAL_FRACTIONAL_LOG2;
1293 		default:
1294 			return -EINVAL;
1295 		}
1296 	case IIO_CHAN_INFO_OFFSET:
1297 
1298 		switch (chan->type) {
1299 		case IIO_TEMP:
1300 			/* 0 Kelvin -> raw sample */
1301 			temp   = -ABSOLUTE_ZERO_MILLICELSIUS;
1302 			temp  *= AD7173_TEMP_SENSIIVITY_uV_per_C;
1303 			temp <<= chan->scan_type.realbits;
1304 			temp   = DIV_U64_ROUND_CLOSEST(temp,
1305 						       AD7173_VOLTAGE_INT_REF_uV *
1306 						       MILLI);
1307 			*val   = -temp;
1308 			return IIO_VAL_INT;
1309 		case IIO_VOLTAGE:
1310 		case IIO_CURRENT:
1311 			*val = -BIT(chan->scan_type.realbits - 1);
1312 			return IIO_VAL_INT;
1313 		default:
1314 			return -EINVAL;
1315 		}
1316 	case IIO_CHAN_INFO_SAMP_FREQ:
1317 		if (st->channels[chan->address].cfg.filter_type == AD7173_FILTER_SINC3) {
1318 			/* Inverse operation of ad7173_sinc3_odr_div_from_odr() */
1319 			*val = MEGA;
1320 			*val2 = 3 * 32 * st->channels[chan->address].cfg.sinc3_odr_div;
1321 			return IIO_VAL_FRACTIONAL;
1322 		}
1323 
1324 		reg = st->channels[chan->address].cfg.sinc5_odr_index;
1325 
1326 		*val = st->info->sinc5_data_rates[reg] / MILLI;
1327 		*val2 = (st->info->sinc5_data_rates[reg] % MILLI) * (MICRO / MILLI);
1328 
1329 		return IIO_VAL_INT_PLUS_MICRO;
1330 	default:
1331 		return -EINVAL;
1332 	}
1333 }
1334 
1335 static int ad7173_write_raw(struct iio_dev *indio_dev,
1336 			    struct iio_chan_spec const *chan,
1337 			    int val, int val2, long info)
1338 {
1339 	struct ad7173_state *st = iio_priv(indio_dev);
1340 	struct ad7173_channel_config *cfg;
1341 	unsigned int freq, i;
1342 	int ret = 0;
1343 
1344 	if (!iio_device_claim_direct(indio_dev))
1345 		return -EBUSY;
1346 
1347 	switch (info) {
1348 	/*
1349 	 * This attribute sets the sampling frequency for each channel individually.
1350 	 * There are no issues for raw or buffered reads of an individual channel.
1351 	 *
1352 	 * When multiple channels are enabled in buffered mode, the effective
1353 	 * sampling rate of a channel is lowered in correlation to the number
1354 	 * of channels enabled and the sampling rate of the other channels.
1355 	 *
1356 	 * Example: 3 channels enabled with rates CH1:6211sps CH2,CH3:10sps
1357 	 * While the reading of CH1 takes only 0.16ms, the reading of CH2 and CH3
1358 	 * will take 100ms each.
1359 	 *
1360 	 * This will cause the reading of CH1 to be actually done once every
1361 	 * 200.16ms, an effective rate of 4.99sps.
1362 	 *
1363 	 * Both the sinc5 and sinc3 rates are set here so that if the filter
1364 	 * type is changed, the requested rate will still be set (aside from
1365 	 * rounding differences).
1366 	 */
1367 	case IIO_CHAN_INFO_SAMP_FREQ:
1368 		freq = val * MILLI + val2 / MILLI;
1369 		for (i = st->info->odr_start_value; i < st->info->num_sinc5_data_rates - 1; i++)
1370 			if (freq >= st->info->sinc5_data_rates[i])
1371 				break;
1372 
1373 		cfg = &st->channels[chan->address].cfg;
1374 		cfg->sinc5_odr_index = i;
1375 		cfg->sinc3_odr_div = ad7173_sinc3_odr_div_from_odr(freq);
1376 		cfg->live = false;
1377 		break;
1378 
1379 	default:
1380 		ret = -EINVAL;
1381 		break;
1382 	}
1383 
1384 	iio_device_release_direct(indio_dev);
1385 	return ret;
1386 }
1387 
1388 static int ad7173_update_scan_mode(struct iio_dev *indio_dev,
1389 				   const unsigned long *scan_mask)
1390 {
1391 	struct ad7173_state *st = iio_priv(indio_dev);
1392 	u16 sinc3_count = 0;
1393 	u16 sinc3_div = 0;
1394 	int i, j, k, ret;
1395 
1396 	for (i = 0; i < indio_dev->num_channels; i++) {
1397 		const struct ad7173_channel_config *cfg = &st->channels[i].cfg;
1398 
1399 		if (test_bit(i, scan_mask)) {
1400 			if (cfg->filter_type == AD7173_FILTER_SINC3) {
1401 				sinc3_count++;
1402 
1403 				if (sinc3_div == 0) {
1404 					sinc3_div = cfg->sinc3_odr_div;
1405 				} else if (sinc3_div != cfg->sinc3_odr_div) {
1406 					dev_err(&st->sd.spi->dev,
1407 						"All enabled channels must have the same sampling_frequency for sinc3 filter_type\n");
1408 					return -EINVAL;
1409 				}
1410 			}
1411 
1412 			ret = ad7173_set_channel(&st->sd, i);
1413 		} else {
1414 			ret = ad_sd_write_reg(&st->sd, AD7173_REG_CH(i), 2, 0);
1415 		}
1416 		if (ret < 0)
1417 			return ret;
1418 	}
1419 
1420 	if (sinc3_count && sinc3_count < bitmap_weight(scan_mask, indio_dev->num_channels)) {
1421 		dev_err(&st->sd.spi->dev,
1422 			"All enabled channels must have sinc3 filter_type\n");
1423 		return -EINVAL;
1424 	}
1425 
1426 	/*
1427 	 * On some chips, there are more channels that setups, so if there were
1428 	 * more unique setups requested than the number of available slots,
1429 	 * ad7173_set_channel() will have written over some of the slots. We
1430 	 * can detect this by making sure each assigned cfg_slot matches the
1431 	 * requested configuration. If it doesn't, we know that the slot was
1432 	 * overwritten by a different channel.
1433 	 */
1434 	for_each_set_bit(i, scan_mask, indio_dev->num_channels) {
1435 		const struct ad7173_channel_config *cfg1, *cfg2;
1436 
1437 		cfg1 = &st->channels[i].cfg;
1438 
1439 		for_each_set_bit(j, scan_mask, indio_dev->num_channels) {
1440 			cfg2 = &st->channels[j].cfg;
1441 
1442 			/*
1443 			 * Only compare configs that are assigned to the same
1444 			 * SETUP_SEL slot and don't compare channel to itself.
1445 			 */
1446 			if (i == j || cfg1->cfg_slot != cfg2->cfg_slot)
1447 				continue;
1448 
1449 			/*
1450 			 * If we find two different configs trying to use the
1451 			 * same SETUP_SEL slot, then we know that the that we
1452 			 * have too many unique configurations requested for
1453 			 * the available slots and at least one was overwritten.
1454 			 */
1455 			if (!ad7173_is_setup_equal(cfg1, cfg2)) {
1456 				/*
1457 				 * At this point, there isn't a way to tell
1458 				 * which setups are actually programmed in the
1459 				 * ADC anymore, so we could read them back to
1460 				 * see, but it is simpler to just turn off all
1461 				 * of the live flags so that everything gets
1462 				 * reprogramed on the next attempt read a sample.
1463 				 */
1464 				for (k = 0; k < st->num_channels; k++)
1465 					st->channels[k].cfg.live = false;
1466 
1467 				dev_err(&st->sd.spi->dev,
1468 					"Too many unique channel configurations requested for scan\n");
1469 				return -EINVAL;
1470 			}
1471 		}
1472 	}
1473 
1474 	return 0;
1475 }
1476 
1477 static int ad7173_debug_reg_access(struct iio_dev *indio_dev, unsigned int reg,
1478 				   unsigned int writeval, unsigned int *readval)
1479 {
1480 	struct ad7173_state *st = iio_priv(indio_dev);
1481 	u8 reg_size;
1482 
1483 	if (reg == AD7173_REG_COMMS)
1484 		reg_size = 1;
1485 	else if (reg == AD7173_REG_CRC || reg == AD7173_REG_DATA ||
1486 		 reg >= AD7173_REG_OFFSET(0))
1487 		reg_size = 3;
1488 	else
1489 		reg_size = 2;
1490 
1491 	if (readval)
1492 		return ad_sd_read_reg(&st->sd, reg, reg_size, readval);
1493 
1494 	return ad_sd_write_reg(&st->sd, reg, reg_size, writeval);
1495 }
1496 
1497 static int ad7173_write_event_config(struct iio_dev *indio_dev,
1498 				     const struct iio_chan_spec *chan,
1499 				     enum iio_event_type type,
1500 				     enum iio_event_direction dir,
1501 				     bool state)
1502 {
1503 	struct ad7173_state *st = iio_priv(indio_dev);
1504 	struct ad7173_channel *adchan = &st->channels[chan->address];
1505 
1506 	switch (type) {
1507 	case IIO_EV_TYPE_FAULT:
1508 		adchan->openwire_det_en = state;
1509 		return 0;
1510 	default:
1511 		return -EINVAL;
1512 	}
1513 }
1514 
1515 static int ad7173_read_event_config(struct iio_dev *indio_dev,
1516 				    const struct iio_chan_spec *chan,
1517 				    enum iio_event_type type,
1518 				    enum iio_event_direction dir)
1519 {
1520 	struct ad7173_state *st = iio_priv(indio_dev);
1521 	struct ad7173_channel *adchan = &st->channels[chan->address];
1522 
1523 	switch (type) {
1524 	case IIO_EV_TYPE_FAULT:
1525 		return adchan->openwire_det_en;
1526 	default:
1527 		return -EINVAL;
1528 	}
1529 }
1530 
1531 static const struct iio_event_spec ad4111_events[] = {
1532 	{
1533 		.type = IIO_EV_TYPE_FAULT,
1534 		.dir = IIO_EV_DIR_FAULT_OPENWIRE,
1535 		.mask_separate = BIT(IIO_EV_INFO_VALUE),
1536 		.mask_shared_by_all = BIT(IIO_EV_INFO_ENABLE),
1537 	},
1538 };
1539 
1540 static const struct iio_info ad7173_info = {
1541 	.read_raw = &ad7173_read_raw,
1542 	.write_raw = &ad7173_write_raw,
1543 	.debugfs_reg_access = &ad7173_debug_reg_access,
1544 	.validate_trigger = ad_sd_validate_trigger,
1545 	.update_scan_mode = ad7173_update_scan_mode,
1546 	.write_event_config = ad7173_write_event_config,
1547 	.read_event_config = ad7173_read_event_config,
1548 };
1549 
1550 static const struct iio_scan_type ad4113_scan_type = {
1551 	.sign = 'u',
1552 	.realbits = 16,
1553 	.storagebits = 16,
1554 	.endianness = IIO_BE,
1555 };
1556 
1557 static const struct iio_chan_spec ad7173_channel_template = {
1558 	.type = IIO_VOLTAGE,
1559 	.indexed = 1,
1560 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
1561 		BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_SAMP_FREQ),
1562 	.scan_type = {
1563 		.sign = 'u',
1564 		.realbits = 24,
1565 		.storagebits = 32,
1566 		.endianness = IIO_BE,
1567 	},
1568 	.ext_info = ad7173_chan_spec_ext_info,
1569 };
1570 
1571 static const struct iio_chan_spec ad7173_temp_iio_channel_template = {
1572 	.type = IIO_TEMP,
1573 	.channel = AD7173_AIN_TEMP_POS,
1574 	.channel2 = AD7173_AIN_TEMP_NEG,
1575 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
1576 		BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_OFFSET) |
1577 		BIT(IIO_CHAN_INFO_SAMP_FREQ),
1578 	.scan_type = {
1579 		.sign = 'u',
1580 		.realbits = 24,
1581 		.storagebits = 32,
1582 		.endianness = IIO_BE,
1583 	},
1584 	.ext_info = ad7173_temp_chan_spec_ext_info,
1585 };
1586 
1587 static void ad7173_disable_regulators(void *data)
1588 {
1589 	struct ad7173_state *st = data;
1590 
1591 	regulator_bulk_disable(ARRAY_SIZE(st->regulators), st->regulators);
1592 }
1593 
1594 static unsigned long ad7173_sel_clk(struct ad7173_state *st,
1595 				    unsigned int clk_sel)
1596 {
1597 	int ret;
1598 
1599 	st->adc_mode &= ~AD7173_ADC_MODE_CLOCKSEL_MASK;
1600 	st->adc_mode |= FIELD_PREP(AD7173_ADC_MODE_CLOCKSEL_MASK, clk_sel);
1601 	ret = ad_sd_write_reg(&st->sd, AD7173_REG_ADC_MODE, 0x2, st->adc_mode);
1602 
1603 	return ret;
1604 }
1605 
1606 static unsigned long ad7173_clk_recalc_rate(struct clk_hw *hw,
1607 					    unsigned long parent_rate)
1608 {
1609 	struct ad7173_state *st = clk_hw_to_ad7173(hw);
1610 
1611 	return st->info->clock / HZ_PER_KHZ;
1612 }
1613 
1614 static int ad7173_clk_output_is_enabled(struct clk_hw *hw)
1615 {
1616 	struct ad7173_state *st = clk_hw_to_ad7173(hw);
1617 	u32 clk_sel;
1618 
1619 	clk_sel = FIELD_GET(AD7173_ADC_MODE_CLOCKSEL_MASK, st->adc_mode);
1620 	return clk_sel == AD7173_ADC_MODE_CLOCKSEL_INT_OUTPUT;
1621 }
1622 
1623 static int ad7173_clk_output_prepare(struct clk_hw *hw)
1624 {
1625 	struct ad7173_state *st = clk_hw_to_ad7173(hw);
1626 
1627 	return ad7173_sel_clk(st, AD7173_ADC_MODE_CLOCKSEL_INT_OUTPUT);
1628 }
1629 
1630 static void ad7173_clk_output_unprepare(struct clk_hw *hw)
1631 {
1632 	struct ad7173_state *st = clk_hw_to_ad7173(hw);
1633 
1634 	ad7173_sel_clk(st, AD7173_ADC_MODE_CLOCKSEL_INT);
1635 }
1636 
1637 static const struct clk_ops ad7173_int_clk_ops = {
1638 	.recalc_rate = ad7173_clk_recalc_rate,
1639 	.is_enabled = ad7173_clk_output_is_enabled,
1640 	.prepare = ad7173_clk_output_prepare,
1641 	.unprepare = ad7173_clk_output_unprepare,
1642 };
1643 
1644 static int ad7173_register_clk_provider(struct iio_dev *indio_dev)
1645 {
1646 	struct ad7173_state *st = iio_priv(indio_dev);
1647 	struct device *dev = indio_dev->dev.parent;
1648 	struct fwnode_handle *fwnode = dev_fwnode(dev);
1649 	struct clk_init_data init = {};
1650 	int ret;
1651 
1652 	if (!IS_ENABLED(CONFIG_COMMON_CLK))
1653 		return 0;
1654 
1655 	init.name = fwnode_get_name(fwnode);
1656 	init.ops = &ad7173_int_clk_ops;
1657 
1658 	st->int_clk_hw.init = &init;
1659 	ret = devm_clk_hw_register(dev, &st->int_clk_hw);
1660 	if (ret)
1661 		return ret;
1662 
1663 	return devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get,
1664 					   &st->int_clk_hw);
1665 }
1666 
1667 static int ad4111_validate_current_ain(struct ad7173_state *st,
1668 				       const unsigned int ain[AD7173_NO_AINS_PER_CHANNEL])
1669 {
1670 	struct device *dev = &st->sd.spi->dev;
1671 
1672 	if (!st->info->has_current_inputs)
1673 		return dev_err_probe(dev, -EINVAL,
1674 			"Model %s does not support current channels\n",
1675 			st->info->name);
1676 
1677 	if (ain[0] >= ARRAY_SIZE(ad4111_current_channel_config))
1678 		return dev_err_probe(dev, -EINVAL,
1679 			"For current channels single-channel must be <[0-3]>\n");
1680 
1681 	return 0;
1682 }
1683 
1684 static int ad7173_validate_voltage_ain_inputs(struct ad7173_state *st,
1685 					      unsigned int ain0, unsigned int ain1)
1686 {
1687 	struct device *dev = &st->sd.spi->dev;
1688 	bool special_input0, special_input1;
1689 
1690 	/* (AVDD1-AVSS)/5 power supply monitoring */
1691 	if (ain0 == AD7173_AIN_POW_MON_POS && ain1 == AD7173_AIN_POW_MON_NEG &&
1692 	    st->info->has_pow_supply_monitoring)
1693 		return 0;
1694 
1695 	special_input0 = AD7173_IS_REF_INPUT(ain0) ||
1696 			 (ain0 == AD4111_VINCOM_INPUT && st->info->has_vincom_input);
1697 	special_input1 = AD7173_IS_REF_INPUT(ain1) ||
1698 			 (ain1 == AD4111_VINCOM_INPUT && st->info->has_vincom_input);
1699 
1700 	if ((ain0 >= st->info->num_voltage_in && !special_input0) ||
1701 	    (ain1 >= st->info->num_voltage_in && !special_input1)) {
1702 		if (ain0 == AD4111_VINCOM_INPUT || ain1 == AD4111_VINCOM_INPUT)
1703 			return dev_err_probe(dev, -EINVAL,
1704 				"VINCOM not supported for %s\n", st->info->name);
1705 
1706 		return dev_err_probe(dev, -EINVAL,
1707 				     "Input pin number out of range for pair (%d %d).\n",
1708 				     ain0, ain1);
1709 	}
1710 
1711 	if (AD4111_IS_VINCOM_MISMATCH(ain0, ain1) ||
1712 	    AD4111_IS_VINCOM_MISMATCH(ain1, ain0))
1713 		return dev_err_probe(dev, -EINVAL,
1714 			"VINCOM must be paired with inputs having divider.\n");
1715 
1716 	if (!special_input0 && !special_input1 &&
1717 	    ((ain0 >= st->info->num_voltage_in_div) !=
1718 	     (ain1 >= st->info->num_voltage_in_div)))
1719 		return dev_err_probe(dev, -EINVAL,
1720 			"Both inputs must either have a voltage divider or not have: (%d %d).\n",
1721 			ain0, ain1);
1722 
1723 	return 0;
1724 }
1725 
1726 static int ad7173_validate_reference(struct ad7173_state *st, int ref_sel)
1727 {
1728 	struct device *dev = &st->sd.spi->dev;
1729 	int ret;
1730 
1731 	if (ref_sel == AD7173_SETUP_REF_SEL_INT_REF && !st->info->has_int_ref)
1732 		return dev_err_probe(dev, -EINVAL,
1733 			"Internal reference is not available on current model.\n");
1734 
1735 	if (ref_sel == AD7173_SETUP_REF_SEL_EXT_REF2 && !st->info->has_ref2)
1736 		return dev_err_probe(dev, -EINVAL,
1737 			"External reference 2 is not available on current model.\n");
1738 
1739 	ret = ad7173_get_ref_voltage_milli(st, ref_sel);
1740 	if (ret < 0)
1741 		return dev_err_probe(dev, ret, "Cannot use reference %u\n",
1742 				     ref_sel);
1743 
1744 	return 0;
1745 }
1746 
1747 static int ad7173_validate_openwire_ain_inputs(struct ad7173_state *st,
1748 					       bool differential,
1749 					       unsigned int ain0,
1750 					       unsigned int ain1)
1751 {
1752 	/*
1753 	 * If the channel is configured as differential,
1754 	 * the ad4111 requires specific ains to be used together
1755 	 */
1756 	if (differential)
1757 		return (ain0 % 2) ? (ain0 - 1) == ain1 : (ain0 + 1) == ain1;
1758 
1759 	return ain1 == AD4111_VINCOM_INPUT;
1760 }
1761 
1762 static unsigned int ad7173_calc_openwire_thrsh_raw(struct ad7173_state *st,
1763 						   struct iio_chan_spec *chan,
1764 						   struct ad7173_channel *chan_st_priv,
1765 						   unsigned int thrsh_mv)
1766 {
1767 	unsigned int thrsh_raw;
1768 
1769 	thrsh_raw =
1770 		BIT(chan->scan_type.realbits - !!(chan_st_priv->cfg.bipolar))
1771 		* thrsh_mv
1772 		/ ad7173_get_ref_voltage_milli(st, chan_st_priv->cfg.ref_sel);
1773 	if (chan->channel < st->info->num_voltage_in_div)
1774 		thrsh_raw /= AD4111_DIVIDER_RATIO;
1775 
1776 	return thrsh_raw;
1777 }
1778 
1779 static int ad7173_fw_parse_channel_config(struct iio_dev *indio_dev)
1780 {
1781 	struct ad7173_channel *chans_st_arr, *chan_st_priv;
1782 	struct ad7173_state *st = iio_priv(indio_dev);
1783 	struct device *dev = indio_dev->dev.parent;
1784 	struct iio_chan_spec *chan_arr, *chan;
1785 	unsigned int ain[AD7173_NO_AINS_PER_CHANNEL], chan_index = 0;
1786 	int ref_sel, ret, num_channels;
1787 
1788 	num_channels = device_get_child_node_count(dev);
1789 
1790 	if (st->info->has_temp)
1791 		num_channels++;
1792 
1793 	if (num_channels == 0)
1794 		return dev_err_probe(dev, -ENODATA, "No channels specified\n");
1795 
1796 	if (num_channels > st->info->num_channels)
1797 		return dev_err_probe(dev, -EINVAL,
1798 			"Too many channels specified. Maximum is %d, not including temperature channel if supported.\n",
1799 			st->info->num_channels);
1800 
1801 	indio_dev->num_channels = num_channels;
1802 	st->num_channels = num_channels;
1803 
1804 	chan_arr = devm_kcalloc(dev, sizeof(*indio_dev->channels),
1805 				st->num_channels, GFP_KERNEL);
1806 	if (!chan_arr)
1807 		return -ENOMEM;
1808 
1809 	chans_st_arr = devm_kcalloc(dev, st->num_channels, sizeof(*st->channels),
1810 				    GFP_KERNEL);
1811 	if (!chans_st_arr)
1812 		return -ENOMEM;
1813 
1814 	indio_dev->channels = chan_arr;
1815 	st->channels = chans_st_arr;
1816 
1817 	if (st->info->has_temp) {
1818 		chan_arr[chan_index] = ad7173_temp_iio_channel_template;
1819 		chan_st_priv = &chans_st_arr[chan_index];
1820 		chan_st_priv->ain =
1821 			AD7173_CH_ADDRESS(chan_arr[chan_index].channel,
1822 					  chan_arr[chan_index].channel2);
1823 		chan_st_priv->cfg.bipolar = false;
1824 		chan_st_priv->cfg.input_buf = st->info->has_input_buf;
1825 		chan_st_priv->cfg.ref_sel = AD7173_SETUP_REF_SEL_INT_REF;
1826 		chan_st_priv->cfg.sinc3_odr_div = ad7173_sinc3_odr_div_from_odr(
1827 			st->info->sinc5_data_rates[st->info->odr_start_value]
1828 		);
1829 		chan_st_priv->cfg.sinc5_odr_index = st->info->odr_start_value;
1830 		chan_st_priv->cfg.filter_type = AD7173_FILTER_SINC5_SINC1;
1831 		chan_st_priv->cfg.openwire_comp_chan = -1;
1832 		st->adc_mode |= AD7173_ADC_MODE_REF_EN;
1833 		if (st->info->data_reg_only_16bit)
1834 			chan_arr[chan_index].scan_type = ad4113_scan_type;
1835 
1836 		if (ad_sigma_delta_has_spi_offload(&st->sd)) {
1837 			chan_arr[chan_index].scan_type.storagebits = 32;
1838 			chan_arr[chan_index].scan_type.endianness = IIO_CPU;
1839 		}
1840 
1841 		chan_index++;
1842 	}
1843 
1844 	device_for_each_child_node_scoped(dev, child) {
1845 		bool is_current_chan = false;
1846 
1847 		chan = &chan_arr[chan_index];
1848 		*chan = ad7173_channel_template;
1849 		chan_st_priv = &chans_st_arr[chan_index];
1850 		ret = fwnode_property_read_u32_array(child, "diff-channels",
1851 						     ain, ARRAY_SIZE(ain));
1852 		if (ret) {
1853 			ret = fwnode_property_read_u32(child, "single-channel",
1854 						       ain);
1855 			if (ret)
1856 				return dev_err_probe(dev, ret,
1857 					"Channel must define one of diff-channels or single-channel.\n");
1858 
1859 			is_current_chan = fwnode_property_read_bool(child, "adi,current-channel");
1860 		} else {
1861 			chan->differential = true;
1862 		}
1863 
1864 		if (is_current_chan) {
1865 			ret = ad4111_validate_current_ain(st, ain);
1866 			if (ret)
1867 				return ret;
1868 		} else {
1869 			if (!chan->differential) {
1870 				ret = fwnode_property_read_u32(child,
1871 					"common-mode-channel", ain + 1);
1872 				if (ret)
1873 					return dev_err_probe(dev, ret,
1874 						"common-mode-channel must be defined for single-ended channels.\n");
1875 			}
1876 			ret = ad7173_validate_voltage_ain_inputs(st, ain[0], ain[1]);
1877 			if (ret)
1878 				return ret;
1879 		}
1880 
1881 		ret = fwnode_property_match_property_string(child,
1882 							    "adi,reference-select",
1883 							    ad7173_ref_sel_str,
1884 							    ARRAY_SIZE(ad7173_ref_sel_str));
1885 		if (ret < 0)
1886 			ref_sel = AD7173_SETUP_REF_SEL_INT_REF;
1887 		else
1888 			ref_sel = ret;
1889 
1890 		ret = ad7173_validate_reference(st, ref_sel);
1891 		if (ret)
1892 			return ret;
1893 
1894 		if (ref_sel == AD7173_SETUP_REF_SEL_INT_REF)
1895 			st->adc_mode |= AD7173_ADC_MODE_REF_EN;
1896 		chan_st_priv->cfg.ref_sel = ref_sel;
1897 
1898 		chan->address = chan_index;
1899 		chan->scan_index = chan_index;
1900 		chan->channel = ain[0];
1901 		chan_st_priv->cfg.input_buf = st->info->has_input_buf;
1902 		chan_st_priv->cfg.sinc3_odr_div = ad7173_sinc3_odr_div_from_odr(
1903 			st->info->sinc5_data_rates[st->info->odr_start_value]
1904 		);
1905 		chan_st_priv->cfg.sinc5_odr_index = st->info->odr_start_value;
1906 		chan_st_priv->cfg.filter_type = AD7173_FILTER_SINC5_SINC1;
1907 		chan_st_priv->cfg.openwire_comp_chan = -1;
1908 
1909 		chan_st_priv->cfg.bipolar = fwnode_property_read_bool(child, "bipolar");
1910 		if (chan_st_priv->cfg.bipolar)
1911 			chan->info_mask_separate |= BIT(IIO_CHAN_INFO_OFFSET);
1912 
1913 		if (is_current_chan) {
1914 			chan->type = IIO_CURRENT;
1915 			chan->differential = false;
1916 			chan->channel2 = 0;
1917 			chan_st_priv->ain = ad4111_current_channel_config[ain[0]];
1918 		} else {
1919 			chan_st_priv->cfg.input_buf = st->info->has_input_buf;
1920 			chan->channel2 = ain[1];
1921 			chan_st_priv->ain = AD7173_CH_ADDRESS(ain[0], ain[1]);
1922 			if (st->info->has_openwire_det &&
1923 			    ad7173_validate_openwire_ain_inputs(st, chan->differential, ain[0], ain[1])) {
1924 				chan->event_spec = ad4111_events;
1925 				chan->num_event_specs = ARRAY_SIZE(ad4111_events);
1926 				chan_st_priv->cfg.openwire_thrsh_raw =
1927 					ad7173_calc_openwire_thrsh_raw(st, chan, chan_st_priv,
1928 								       AD4111_OW_DET_THRSH_MV);
1929 			}
1930 		}
1931 
1932 		if (st->info->data_reg_only_16bit)
1933 			chan_arr[chan_index].scan_type = ad4113_scan_type;
1934 
1935 		/* Assuming SPI offload is ad411x_ad717x HDL project. */
1936 		if (ad_sigma_delta_has_spi_offload(&st->sd)) {
1937 			chan_arr[chan_index].scan_type.storagebits = 32;
1938 			chan_arr[chan_index].scan_type.endianness = IIO_CPU;
1939 		}
1940 
1941 		chan_index++;
1942 	}
1943 	return 0;
1944 }
1945 
1946 static int ad7173_fw_parse_device_config(struct iio_dev *indio_dev)
1947 {
1948 	struct ad7173_state *st = iio_priv(indio_dev);
1949 	struct device *dev = indio_dev->dev.parent;
1950 	int ret;
1951 
1952 	st->regulators[0].supply = ad7173_ref_sel_str[AD7173_SETUP_REF_SEL_EXT_REF];
1953 	st->regulators[1].supply = ad7173_ref_sel_str[AD7173_SETUP_REF_SEL_EXT_REF2];
1954 	st->regulators[2].supply = ad7173_ref_sel_str[AD7173_SETUP_REF_SEL_AVDD1_AVSS];
1955 
1956 	/*
1957 	 * If a regulator is not available, it will be set to a dummy regulator.
1958 	 * Each channel reference is checked with regulator_get_voltage() before
1959 	 * setting attributes so if any channel uses a dummy supply the driver
1960 	 * probe will fail.
1961 	 */
1962 	ret = devm_regulator_bulk_get(dev, ARRAY_SIZE(st->regulators),
1963 				      st->regulators);
1964 	if (ret)
1965 		return dev_err_probe(dev, ret, "Failed to get regulators\n");
1966 
1967 	ret = regulator_bulk_enable(ARRAY_SIZE(st->regulators), st->regulators);
1968 	if (ret)
1969 		return dev_err_probe(dev, ret, "Failed to enable regulators\n");
1970 
1971 	ret = devm_add_action_or_reset(dev, ad7173_disable_regulators, st);
1972 	if (ret)
1973 		return ret;
1974 
1975 	ret = device_property_match_property_string(dev, "clock-names",
1976 						    ad7173_clk_sel,
1977 						    ARRAY_SIZE(ad7173_clk_sel));
1978 	if (ret < 0) {
1979 		st->adc_mode |= FIELD_PREP(AD7173_ADC_MODE_CLOCKSEL_MASK,
1980 					   AD7173_ADC_MODE_CLOCKSEL_INT);
1981 		ad7173_register_clk_provider(indio_dev);
1982 	} else {
1983 		struct clk *clk;
1984 
1985 		st->adc_mode |= FIELD_PREP(AD7173_ADC_MODE_CLOCKSEL_MASK,
1986 					   AD7173_ADC_MODE_CLOCKSEL_EXT + ret);
1987 		clk = devm_clk_get_enabled(dev, ad7173_clk_sel[ret]);
1988 		if (IS_ERR(clk))
1989 			return dev_err_probe(dev, PTR_ERR(clk),
1990 					     "Failed to get external clock\n");
1991 	}
1992 
1993 	return ad7173_fw_parse_channel_config(indio_dev);
1994 }
1995 
1996 static int ad7173_probe(struct spi_device *spi)
1997 {
1998 	struct device *dev = &spi->dev;
1999 	struct ad7173_state *st;
2000 	struct iio_dev *indio_dev;
2001 	int ret;
2002 
2003 	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
2004 	if (!indio_dev)
2005 		return -ENOMEM;
2006 
2007 	st = iio_priv(indio_dev);
2008 	st->info = spi_get_device_match_data(spi);
2009 	if (!st->info)
2010 		return -ENODEV;
2011 
2012 	ida_init(&st->cfg_slots_status);
2013 	ret = devm_add_action_or_reset(dev, ad7173_ida_destroy, st);
2014 	if (ret)
2015 		return ret;
2016 
2017 	indio_dev->name = st->info->name;
2018 	indio_dev->modes = INDIO_DIRECT_MODE;
2019 	indio_dev->info = &ad7173_info;
2020 
2021 	spi->mode = SPI_MODE_3;
2022 	ret = spi_setup(spi);
2023 	if (ret)
2024 		return ret;
2025 
2026 	ret = ad_sd_init(&st->sd, indio_dev, spi, st->info->sd_info);
2027 	if (ret)
2028 		return ret;
2029 
2030 	ret = ad7173_fw_parse_device_config(indio_dev);
2031 	if (ret)
2032 		return ret;
2033 
2034 	ret = devm_ad_sd_setup_buffer_and_trigger(dev, indio_dev);
2035 	if (ret)
2036 		return ret;
2037 
2038 	ret = ad7173_setup(indio_dev);
2039 	if (ret)
2040 		return ret;
2041 
2042 	ret = devm_iio_device_register(dev, indio_dev);
2043 	if (ret)
2044 		return ret;
2045 
2046 	return ad7173_gpio_init(st);
2047 }
2048 
2049 static const struct of_device_id ad7173_of_match[] = {
2050 	{ .compatible = "adi,ad4111",	.data = &ad4111_device_info },
2051 	{ .compatible = "adi,ad4112",	.data = &ad4112_device_info },
2052 	{ .compatible = "adi,ad4113",	.data = &ad4113_device_info },
2053 	{ .compatible = "adi,ad4114",	.data = &ad4114_device_info },
2054 	{ .compatible = "adi,ad4115",	.data = &ad4115_device_info },
2055 	{ .compatible = "adi,ad4116",	.data = &ad4116_device_info },
2056 	{ .compatible = "adi,ad7172-2", .data = &ad7172_2_device_info },
2057 	{ .compatible = "adi,ad7172-4", .data = &ad7172_4_device_info },
2058 	{ .compatible = "adi,ad7173-8", .data = &ad7173_8_device_info },
2059 	{ .compatible = "adi,ad7175-2", .data = &ad7175_2_device_info },
2060 	{ .compatible = "adi,ad7175-8", .data = &ad7175_8_device_info },
2061 	{ .compatible = "adi,ad7176-2", .data = &ad7176_2_device_info },
2062 	{ .compatible = "adi,ad7177-2", .data = &ad7177_2_device_info },
2063 	{ }
2064 };
2065 MODULE_DEVICE_TABLE(of, ad7173_of_match);
2066 
2067 static const struct spi_device_id ad7173_id_table[] = {
2068 	{ .name = "ad4111",   .driver_data = (kernel_ulong_t)&ad4111_device_info },
2069 	{ .name = "ad4112",   .driver_data = (kernel_ulong_t)&ad4112_device_info },
2070 	{ .name = "ad4113",   .driver_data = (kernel_ulong_t)&ad4113_device_info },
2071 	{ .name = "ad4114",   .driver_data = (kernel_ulong_t)&ad4114_device_info },
2072 	{ .name = "ad4115",   .driver_data = (kernel_ulong_t)&ad4115_device_info },
2073 	{ .name = "ad4116",   .driver_data = (kernel_ulong_t)&ad4116_device_info },
2074 	{ .name = "ad7172-2", .driver_data = (kernel_ulong_t)&ad7172_2_device_info },
2075 	{ .name = "ad7172-4", .driver_data = (kernel_ulong_t)&ad7172_4_device_info },
2076 	{ .name = "ad7173-8", .driver_data = (kernel_ulong_t)&ad7173_8_device_info },
2077 	{ .name = "ad7175-2", .driver_data = (kernel_ulong_t)&ad7175_2_device_info },
2078 	{ .name = "ad7175-8", .driver_data = (kernel_ulong_t)&ad7175_8_device_info },
2079 	{ .name = "ad7176-2", .driver_data = (kernel_ulong_t)&ad7176_2_device_info },
2080 	{ .name = "ad7177-2", .driver_data = (kernel_ulong_t)&ad7177_2_device_info },
2081 	{ }
2082 };
2083 MODULE_DEVICE_TABLE(spi, ad7173_id_table);
2084 
2085 static struct spi_driver ad7173_driver = {
2086 	.driver = {
2087 		.name	= "ad7173",
2088 		.of_match_table = ad7173_of_match,
2089 	},
2090 	.probe		= ad7173_probe,
2091 	.id_table	= ad7173_id_table,
2092 };
2093 module_spi_driver(ad7173_driver);
2094 
2095 MODULE_IMPORT_NS("IIO_AD_SIGMA_DELTA");
2096 MODULE_AUTHOR("Lars-Peter Clausen <lars@metafo.de>");
2097 MODULE_AUTHOR("Dumitru Ceclan <dumitru.ceclan@analog.com>");
2098 MODULE_DESCRIPTION("Analog Devices AD7173 and similar ADC driver");
2099 MODULE_LICENSE("GPL");
2100