xref: /linux/drivers/iio/adc/ad4170-4.c (revision 0227b49b50276657243e54f5609e65c4f0eaaf4d) !
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Analog Devices AD4170-4 ADC driver
4  *
5  * Copyright (C) 2025 Analog Devices, Inc.
6  * Author: Ana-Maria Cusco <ana-maria.cusco@analog.com>
7  * Author: Marcelo Schmitt <marcelo.schmitt@analog.com>
8  */
9 
10 #include <linux/array_size.h>
11 #include <linux/bitfield.h>
12 #include <linux/bitmap.h>
13 #include <linux/bitops.h>
14 #include <linux/bits.h>
15 #include <linux/cleanup.h>
16 #include <linux/clk.h>
17 #include <linux/clk-provider.h>
18 #include <linux/delay.h>
19 #include <linux/device.h>
20 #include <linux/err.h>
21 #include <linux/gpio/driver.h>
22 #include <linux/iio/buffer.h>
23 #include <linux/iio/iio.h>
24 #include <linux/iio/trigger.h>
25 #include <linux/iio/trigger_consumer.h>
26 #include <linux/iio/triggered_buffer.h>
27 #include <linux/interrupt.h>
28 #include <linux/irq.h>
29 #include <linux/math64.h>
30 #include <linux/minmax.h>
31 #include <linux/module.h>
32 #include <linux/property.h>
33 #include <linux/regmap.h>
34 #include <linux/regulator/consumer.h>
35 #include <linux/spi/spi.h>
36 #include <linux/time.h>
37 #include <linux/types.h>
38 #include <linux/unaligned.h>
39 #include <linux/units.h>
40 #include <linux/util_macros.h>
41 
42 /*
43  * AD4170 registers
44  * Multibyte register addresses point to the most significant byte which is the
45  * address to use to get the most significant byte first (address accessed is
46  * decremented by one for each data byte)
47  *
48  * Each register address define follows the AD4170_<REG_NAME>_REG format.
49  * Each mask follows the AD4170_<REG_NAME>_<FIELD_NAME> format.
50  * E.g. AD4170_PIN_MUXING_DIG_AUX1_CTRL_MSK is for accessing DIG_AUX1_CTRL field
51  * of PIN_MUXING_REG.
52  * Each constant follows the AD4170_<REG_NAME>_<FIELD_NAME>_<FUNCTION> format.
53  * E.g. AD4170_PIN_MUXING_DIG_AUX1_DISABLED is the value written to
54  * DIG_AUX1_CTRL field of PIN_MUXING register to disable DIG_AUX1 pin.
55  * Some register names and register field names are shortened versions of
56  * their datasheet counterpart names to provide better code readability.
57  */
58 #define AD4170_CONFIG_A_REG				0x00
59 #define AD4170_DATA_24B_REG				0x1E
60 #define AD4170_PIN_MUXING_REG				0x69
61 #define AD4170_CLOCK_CTRL_REG				0x6B
62 #define AD4170_ADC_CTRL_REG				0x71
63 #define AD4170_CHAN_EN_REG				0x79
64 #define AD4170_CHAN_SETUP_REG(x)			(0x81 + 4 * (x))
65 #define AD4170_CHAN_MAP_REG(x)				(0x83 + 4 * (x))
66 #define AD4170_MISC_REG(x)				(0xC1 + 14 * (x))
67 #define AD4170_AFE_REG(x)				(0xC3 + 14 * (x))
68 #define AD4170_FILTER_REG(x)				(0xC5 + 14 * (x))
69 #define AD4170_FILTER_FS_REG(x)				(0xC7 + 14 * (x))
70 #define AD4170_OFFSET_REG(x)				(0xCA + 14 * (x))
71 #define AD4170_GAIN_REG(x)				(0xCD + 14 * (x))
72 #define AD4170_V_BIAS_REG				0x135
73 #define AD4170_CURRENT_SRC_REG(x)			(0x139 + 2 * (x))
74 #define AD4170_GPIO_MODE_REG				0x191
75 #define AD4170_GPIO_OUTPUT_REG				0x193
76 #define AD4170_GPIO_INPUT_REG				0x195
77 #define AD4170_ADC_CTRL_CONT_READ_EXIT_REG		0x200 /* virtual reg */
78 
79 #define AD4170_REG_READ_MASK				BIT(14)
80 
81 /* AD4170_CONFIG_A_REG - INTERFACE_CONFIG_A REGISTER */
82 #define AD4170_SW_RESET_MSK				(BIT(7) | BIT(0))
83 
84 /* AD4170_PIN_MUXING_REG */
85 #define AD4170_PIN_MUXING_DIG_AUX1_CTRL_MSK		GENMASK(5, 4)
86 
87 /* AD4170_CLOCK_CTRL_REG */
88 #define AD4170_CLOCK_CTRL_CLOCKSEL_MSK			GENMASK(1, 0)
89 
90 /* AD4170_ADC_CTRL_REG */
91 #define AD4170_ADC_CTRL_MULTI_DATA_REG_SEL_MSK		BIT(7)
92 #define AD4170_ADC_CTRL_CONT_READ_MSK			GENMASK(5, 4)
93 #define AD4170_ADC_CTRL_MODE_MSK			GENMASK(3, 0)
94 
95 /* AD4170_CHAN_EN_REG */
96 #define AD4170_CHAN_EN(ch)				BIT(ch)
97 
98 /* AD4170_CHAN_SETUP_REG */
99 #define AD4170_CHAN_SETUP_SETUP_MSK			GENMASK(2, 0)
100 
101 /* AD4170_CHAN_MAP_REG */
102 #define AD4170_CHAN_MAP_AINP_MSK			GENMASK(12, 8)
103 #define AD4170_CHAN_MAP_AINM_MSK			GENMASK(4, 0)
104 
105 /* AD4170_MISC_REG */
106 #define AD4170_MISC_CHOP_IEXC_MSK			GENMASK(15, 14)
107 #define AD4170_MISC_CHOP_ADC_MSK			GENMASK(9, 8)
108 
109 /* AD4170_AFE_REG */
110 #define AD4170_AFE_REF_BUF_M_MSK			GENMASK(11, 10)
111 #define AD4170_AFE_REF_BUF_P_MSK			GENMASK(9, 8)
112 #define AD4170_AFE_REF_SELECT_MSK			GENMASK(6, 5)
113 #define AD4170_AFE_BIPOLAR_MSK				BIT(4)
114 #define AD4170_AFE_PGA_GAIN_MSK				GENMASK(3, 0)
115 
116 /* AD4170_FILTER_REG */
117 #define AD4170_FILTER_FILTER_TYPE_MSK			GENMASK(3, 0)
118 
119 /* AD4170_CURRENT_SRC_REG */
120 #define AD4170_CURRENT_SRC_I_OUT_PIN_MSK		GENMASK(12, 8)
121 #define AD4170_CURRENT_SRC_I_OUT_VAL_MSK		GENMASK(2, 0)
122 
123 /* AD4170_GPIO_MODE_REG */
124 #define AD4170_GPIO_MODE_GPIO0_MSK			GENMASK(1, 0)
125 #define AD4170_GPIO_MODE_GPIO1_MSK			GENMASK(3, 2)
126 #define AD4170_GPIO_MODE_GPIO2_MSK			GENMASK(5, 4)
127 #define AD4170_GPIO_MODE_GPIO3_MSK			GENMASK(7, 6)
128 
129 /* AD4170_GPIO_OUTPUT_REG */
130 #define AD4170_GPIO_OUTPUT_GPIO_MSK(x)			BIT(x)
131 
132 /* AD4170 register constants */
133 
134 /* AD4170_CLOCK_CTRL_REG constants */
135 #define AD4170_CLOCK_CTRL_CLOCKSEL_INT			0x0
136 #define AD4170_CLOCK_CTRL_CLOCKSEL_INT_OUT		0x1
137 #define AD4170_CLOCK_CTRL_CLOCKSEL_EXT			0x2
138 #define AD4170_CLOCK_CTRL_CLOCKSEL_EXT_XTAL		0x3
139 
140 /* AD4170_CHAN_MAP_REG constants */
141 #define AD4170_CHAN_MAP_AIN(x)			(x)
142 #define AD4170_CHAN_MAP_TEMP_SENSOR		17
143 #define AD4170_CHAN_MAP_AVDD_AVSS_P		18
144 #define AD4170_CHAN_MAP_AVDD_AVSS_N		18
145 #define AD4170_CHAN_MAP_IOVDD_DGND_P		19
146 #define AD4170_CHAN_MAP_IOVDD_DGND_N		19
147 #define AD4170_CHAN_MAP_AVSS			23
148 #define AD4170_CHAN_MAP_DGND			24
149 #define AD4170_CHAN_MAP_REFIN1_P		25
150 #define AD4170_CHAN_MAP_REFIN1_N		26
151 #define AD4170_CHAN_MAP_REFIN2_P		27
152 #define AD4170_CHAN_MAP_REFIN2_N		28
153 #define AD4170_CHAN_MAP_REFOUT			29
154 
155 /* AD4170_MISC_REG constants */
156 #define AD4170_MISC_CHOP_IEXC_PAIR1			0x1
157 #define AD4170_MISC_CHOP_IEXC_PAIR2			0x2
158 #define AD4170_MISC_CHOP_IEXC_BOTH			0x3
159 
160 /* AD4170_PIN_MUXING_REG constants */
161 #define AD4170_PIN_MUXING_DIG_AUX1_DISABLED		0x0
162 #define AD4170_PIN_MUXING_DIG_AUX1_RDY			0x1
163 
164 /* AD4170_ADC_CTRL_REG constants */
165 #define AD4170_ADC_CTRL_MODE_CONT			0x0
166 #define AD4170_ADC_CTRL_MODE_SINGLE			0x4
167 #define AD4170_ADC_CTRL_MODE_IDLE			0x7
168 
169 #define AD4170_ADC_CTRL_CONT_READ_DISABLE		0x0
170 #define AD4170_ADC_CTRL_CONT_READ_ENABLE		0x1
171 
172 /* AD4170_FILTER_REG constants */
173 #define AD4170_FILTER_FILTER_TYPE_SINC5_AVG		0x0
174 #define AD4170_FILTER_FILTER_TYPE_SINC5			0x4
175 #define AD4170_FILTER_FILTER_TYPE_SINC3			0x6
176 
177 /* AD4170_CURRENT_SRC_REG constants */
178 #define AD4170_CURRENT_SRC_I_OUT_PIN_AIN(x)		(x)
179 #define AD4170_CURRENT_SRC_I_OUT_PIN_GPIO(x)		((x) + 17)
180 
181 /* AD4170_GPIO_MODE_REG constants */
182 #define AD4170_GPIO_MODE_GPIO_INPUT			1
183 #define AD4170_GPIO_MODE_GPIO_OUTPUT			2
184 
185 /* Device properties and auxiliary constants */
186 
187 #define AD4170_NUM_ANALOG_PINS				9
188 #define AD4170_NUM_GPIO_PINS				4
189 #define AD4170_MAX_ADC_CHANNELS				16
190 #define AD4170_MAX_IIO_CHANNELS				(AD4170_MAX_ADC_CHANNELS + 1)
191 #define AD4170_MAX_ANALOG_PINS				8
192 #define AD4170_MAX_SETUPS				8
193 #define AD4170_INVALID_SETUP				9
194 #define AD4170_SPI_INST_PHASE_LEN			2
195 #define AD4170_SPI_MAX_XFER_LEN				6
196 #define AD4170_NUM_CURRENT_SRC				4
197 #define AD4170_DEFAULT_SAMP_RATE			(125 * HZ_PER_KHZ)
198 
199 #define AD4170_INT_REF_2_5V				2500000
200 
201 /* Internal and external clock properties */
202 #define AD4170_INT_CLOCK_16MHZ				(16 * HZ_PER_MHZ)
203 #define AD4170_EXT_CLOCK_MHZ_MIN			(1 * HZ_PER_MHZ)
204 #define AD4170_EXT_CLOCK_MHZ_MAX			(17 * HZ_PER_MHZ)
205 
206 #define AD4170_NUM_PGA_OPTIONS				10
207 
208 /* Digital filter properties */
209 #define AD4170_SINC3_MIN_FS				4
210 #define AD4170_SINC3_MAX_FS				65532
211 #define AD4170_SINC5_MIN_FS				1
212 #define AD4170_SINC5_MAX_FS				256
213 
214 #define AD4170_GAIN_REG_DEFAULT				0x555555
215 
216 #define AD4170_ADC_CTRL_CONT_READ_EXIT			0xA5
217 
218 /* Analog pin functions  */
219 #define AD4170_PIN_UNASSIGNED				0x00
220 #define AD4170_PIN_ANALOG_IN				0x01
221 #define AD4170_PIN_CURRENT_OUT				0x02
222 #define AD4170_PIN_VBIAS				0x04
223 
224 /* GPIO pin functions  */
225 #define AD4170_GPIO_UNASSIGNED				0x00
226 #define AD4170_GPIO_AC_EXCITATION			0x02
227 #define AD4170_GPIO_OUTPUT				0x04
228 
229 /* Current source */
230 #define AD4170_CURRENT_SRC_DISABLED			0xFF
231 
232 static const unsigned int ad4170_reg_size[] = {
233 	[AD4170_CONFIG_A_REG] = 1,
234 	[AD4170_DATA_24B_REG] = 3,
235 	[AD4170_PIN_MUXING_REG] = 2,
236 	[AD4170_CLOCK_CTRL_REG] = 2,
237 	[AD4170_ADC_CTRL_REG] = 2,
238 	[AD4170_CHAN_EN_REG] = 2,
239 	/*
240 	 * CHANNEL_SETUP and CHANNEL_MAP register are all 2 byte size each and
241 	 * their addresses are interleaved such that we have CHANNEL_SETUP0
242 	 * address followed by CHANNEL_MAP0 address, followed by CHANNEL_SETUP1,
243 	 * and so on until CHANNEL_MAP15.
244 	 * Thus, initialize the register size for them only once.
245 	 */
246 	[AD4170_CHAN_SETUP_REG(0) ... AD4170_CHAN_MAP_REG(AD4170_MAX_ADC_CHANNELS - 1)] = 2,
247 	/*
248 	 * MISC, AFE, FILTER, FILTER_FS, OFFSET, and GAIN register addresses are
249 	 * also interleaved but MISC, AFE, FILTER, FILTER_FS, OFFSET are 16-bit
250 	 * while OFFSET, GAIN are 24-bit registers so we can't init them all to
251 	 * the same size.
252 	 */
253 	[AD4170_MISC_REG(0) ... AD4170_FILTER_FS_REG(0)] = 2,
254 	[AD4170_MISC_REG(1) ... AD4170_FILTER_FS_REG(1)] = 2,
255 	[AD4170_MISC_REG(2) ... AD4170_FILTER_FS_REG(2)] = 2,
256 	[AD4170_MISC_REG(3) ... AD4170_FILTER_FS_REG(3)] = 2,
257 	[AD4170_MISC_REG(4) ... AD4170_FILTER_FS_REG(4)] = 2,
258 	[AD4170_MISC_REG(5) ... AD4170_FILTER_FS_REG(5)] = 2,
259 	[AD4170_MISC_REG(6) ... AD4170_FILTER_FS_REG(6)] = 2,
260 	[AD4170_MISC_REG(7) ... AD4170_FILTER_FS_REG(7)] = 2,
261 	[AD4170_OFFSET_REG(0) ... AD4170_GAIN_REG(0)] = 3,
262 	[AD4170_OFFSET_REG(1) ... AD4170_GAIN_REG(1)] = 3,
263 	[AD4170_OFFSET_REG(2) ... AD4170_GAIN_REG(2)] = 3,
264 	[AD4170_OFFSET_REG(3) ... AD4170_GAIN_REG(3)] = 3,
265 	[AD4170_OFFSET_REG(4) ... AD4170_GAIN_REG(4)] = 3,
266 	[AD4170_OFFSET_REG(5) ... AD4170_GAIN_REG(5)] = 3,
267 	[AD4170_OFFSET_REG(6) ... AD4170_GAIN_REG(6)] = 3,
268 	[AD4170_OFFSET_REG(7) ... AD4170_GAIN_REG(7)] = 3,
269 	[AD4170_V_BIAS_REG] = 2,
270 	[AD4170_CURRENT_SRC_REG(0) ... AD4170_CURRENT_SRC_REG(3)] = 2,
271 	[AD4170_GPIO_MODE_REG] = 2,
272 	[AD4170_GPIO_OUTPUT_REG] = 2,
273 	[AD4170_GPIO_INPUT_REG] = 2,
274 	[AD4170_ADC_CTRL_CONT_READ_EXIT_REG] = 0,
275 };
276 
277 enum ad4170_ref_buf {
278 	AD4170_REF_BUF_PRE,	/* Pre-charge referrence buffer */
279 	AD4170_REF_BUF_FULL,	/* Full referrence buffering */
280 	AD4170_REF_BUF_BYPASS,	/* Bypass referrence buffering */
281 };
282 
283 /* maps adi,positive/negative-reference-buffer property values to enum */
284 static const char * const ad4170_ref_buf_str[] = {
285 	[AD4170_REF_BUF_PRE] = "precharge",
286 	[AD4170_REF_BUF_FULL] = "full",
287 	[AD4170_REF_BUF_BYPASS] = "disabled",
288 };
289 
290 enum ad4170_ref_select {
291 	AD4170_REF_REFIN1,
292 	AD4170_REF_REFIN2,
293 	AD4170_REF_REFOUT,
294 	AD4170_REF_AVDD,
295 };
296 
297 enum ad4170_filter_type {
298 	AD4170_SINC5_AVG,
299 	AD4170_SINC5,
300 	AD4170_SINC3,
301 };
302 
303 enum ad4170_regulator {
304 	AD4170_AVDD_SUP,
305 	AD4170_AVSS_SUP,
306 	AD4170_IOVDD_SUP,
307 	AD4170_REFIN1P_SUP,
308 	AD4170_REFIN1N_SUP,
309 	AD4170_REFIN2P_SUP,
310 	AD4170_REFIN2N_SUP,
311 	AD4170_MAX_SUP,
312 };
313 
314 static const char *const ad4170_clk_sel[] = {
315 	"ext-clk", "xtal",
316 };
317 
318 enum ad4170_int_pin_sel {
319 	AD4170_INT_PIN_SDO,
320 	AD4170_INT_PIN_DIG_AUX1,
321 };
322 
323 static const char * const ad4170_int_pin_names[] = {
324 	[AD4170_INT_PIN_SDO] = "sdo",
325 	[AD4170_INT_PIN_DIG_AUX1] = "dig_aux1",
326 };
327 
328 static const unsigned int ad4170_sinc3_filt_fs_tbl[] = {
329 	4, 8, 12, 16, 20, 40, 48, 80,			/*  0 -  7 */
330 	100, 256, 500, 1000, 5000, 8332, 10000, 25000,	/*  8 - 15 */
331 	50000, 65532,					/* 16 - 17 */
332 };
333 
334 #define AD4170_MAX_FS_TBL_SIZE		ARRAY_SIZE(ad4170_sinc3_filt_fs_tbl)
335 
336 static const unsigned int ad4170_sinc5_filt_fs_tbl[] = {
337 	1, 2, 4, 8, 12, 16, 20, 40, 48, 80, 100, 256,
338 };
339 
340 static const unsigned int ad4170_iout_pin_tbl[] = {
341 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(0),
342 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(1),
343 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(2),
344 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(3),
345 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(4),
346 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(5),
347 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(6),
348 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(7),
349 	AD4170_CURRENT_SRC_I_OUT_PIN_AIN(8),
350 	AD4170_CURRENT_SRC_I_OUT_PIN_GPIO(0),
351 	AD4170_CURRENT_SRC_I_OUT_PIN_GPIO(1),
352 	AD4170_CURRENT_SRC_I_OUT_PIN_GPIO(2),
353 	AD4170_CURRENT_SRC_I_OUT_PIN_GPIO(3),
354 };
355 
356 static const unsigned int ad4170_iout_current_ua_tbl[] = {
357 	0, 10, 50, 100, 250, 500, 1000, 1500,
358 };
359 
360 enum ad4170_sensor_enum {
361 	AD4170_ADC_SENSOR = 0,
362 	AD4170_WEIGH_SCALE_SENSOR = 1,
363 	AD4170_RTD_SENSOR = 2,
364 	AD4170_THERMOCOUPLE_SENSOR = 3,
365 };
366 
367 /* maps adi,sensor-type property value to enum */
368 static const char * const ad4170_sensor_type[] = {
369 	[AD4170_ADC_SENSOR] = "adc",
370 	[AD4170_WEIGH_SCALE_SENSOR] = "weighscale",
371 	[AD4170_RTD_SENSOR] = "rtd",
372 	[AD4170_THERMOCOUPLE_SENSOR] = "thermocouple",
373 };
374 
375 struct ad4170_chip_info {
376 	const char *name;
377 };
378 
379 static const struct ad4170_chip_info ad4170_chip_info = {
380 	.name = "ad4170-4",
381 };
382 
383 static const struct ad4170_chip_info ad4190_chip_info = {
384 	.name = "ad4190-4",
385 };
386 
387 static const struct ad4170_chip_info ad4195_chip_info = {
388 	.name = "ad4195-4",
389 };
390 
391 /*
392  * There are 8 of each MISC, AFE, FILTER, FILTER_FS, OFFSET, and GAIN
393  * configuration registers. That is, there are 8 miscellaneous registers, MISC0
394  * to MISC7. Each MISC register is associated with a setup; MISCN is associated
395  * with setup number N. The other 5 above mentioned types of registers have
396  * analogous structure. A setup is a set of those registers. For example,
397  * setup 1 comprises of MISC1, AFE1, FILTER1, FILTER_FS1, OFFSET1, and GAIN1
398  * registers. Also, there are 16 CHANNEL_SETUP registers (CHANNEL_SETUP0 to
399  * CHANNEL_SETUP15). Each channel setup is associated with one of the 8 possible
400  * setups. Thus, AD4170 can support up to 16 channels but, since there are only
401  * 8 available setups, channels must share settings if more than 8 channels are
402  * configured.
403  *
404  * If this struct is modified, ad4170_setup_eq() will probably need to be
405  * updated too.
406  */
407 struct ad4170_setup {
408 	u16 misc;
409 	u16 afe;
410 	u16 filter;
411 	u16 filter_fs;
412 	u32 offset; /* For calibration purposes */
413 	u32 gain; /* For calibration purposes */
414 };
415 
416 struct ad4170_setup_info {
417 	struct ad4170_setup setup;
418 	unsigned int enabled_channels;
419 	unsigned int channels;
420 };
421 
422 struct ad4170_chan_info {
423 	unsigned int input_range_uv;
424 	unsigned int setup_num; /* Index to access state setup_infos array */
425 	struct ad4170_setup setup; /* cached setup */
426 	int offset_tbl[10];
427 	u32 scale_tbl[10][2];
428 	bool initialized;
429 	bool enabled;
430 };
431 
432 static const char * const ad4170_filt_names[] = {
433 	[AD4170_SINC5_AVG] = "sinc5+avg",
434 	[AD4170_SINC5] = "sinc5",
435 	[AD4170_SINC3] = "sinc3",
436 };
437 
438 struct ad4170_state {
439 	struct mutex lock; /* Protect read-modify-write and multi write sequences */
440 	int vrefs_uv[AD4170_MAX_SUP];
441 	u32 mclk_hz;
442 	struct ad4170_setup_info setup_infos[AD4170_MAX_SETUPS];
443 	struct ad4170_chan_info chan_infos[AD4170_MAX_ADC_CHANNELS];
444 	struct completion completion;
445 	struct iio_chan_spec chans[AD4170_MAX_IIO_CHANNELS];
446 	struct spi_device *spi;
447 	struct regmap *regmap;
448 	int sps_tbl[ARRAY_SIZE(ad4170_filt_names)][AD4170_MAX_FS_TBL_SIZE][2];
449 	__be32 bounce_buffer[AD4170_MAX_ADC_CHANNELS];
450 	struct spi_message msg;
451 	struct spi_transfer xfer;
452 	struct iio_trigger *trig;
453 	struct clk_hw int_clk_hw;
454 	unsigned int clock_ctrl;
455 	unsigned int pins_fn[AD4170_NUM_ANALOG_PINS];
456 	int gpio_fn[AD4170_NUM_GPIO_PINS];
457 	unsigned int cur_src_pins[AD4170_NUM_CURRENT_SRC];
458 	struct gpio_chip gpiochip;
459 	/*
460 	 * DMA (thus cache coherency maintenance) requires the transfer buffers
461 	 * to live in their own cache lines.
462 	 */
463 	u8 rx_buf[4] __aligned(IIO_DMA_MINALIGN);
464 };
465 
ad4170_fill_sps_tbl(struct ad4170_state * st)466 static void ad4170_fill_sps_tbl(struct ad4170_state *st)
467 {
468 	unsigned int tmp0, tmp1, i;
469 
470 	/*
471 	 * The ODR can be calculated the same way for sinc5+avg, sinc5, and
472 	 * sinc3 filter types with the exception that sinc5 filter has a
473 	 * narrowed range of allowed FILTER_FS values.
474 	 */
475 	for (i = 0; i < ARRAY_SIZE(ad4170_sinc3_filt_fs_tbl); i++) {
476 		tmp0 = div_u64_rem(st->mclk_hz, 32 * ad4170_sinc3_filt_fs_tbl[i],
477 				   &tmp1);
478 		tmp1 = mult_frac(tmp1, MICRO, 32 * ad4170_sinc3_filt_fs_tbl[i]);
479 		/* Fill sinc5+avg filter SPS table */
480 		st->sps_tbl[AD4170_SINC5_AVG][i][0] = tmp0; /* Integer part */
481 		st->sps_tbl[AD4170_SINC5_AVG][i][1] = tmp1; /* Fractional part */
482 
483 		/* Fill sinc3 filter SPS table */
484 		st->sps_tbl[AD4170_SINC3][i][0] = tmp0; /* Integer part */
485 		st->sps_tbl[AD4170_SINC3][i][1] = tmp1; /* Fractional part */
486 	}
487 	/* Sinc5 filter ODR doesn't use all FILTER_FS bits */
488 	for (i = 0; i < ARRAY_SIZE(ad4170_sinc5_filt_fs_tbl); i++) {
489 		tmp0 = div_u64_rem(st->mclk_hz, 32 * ad4170_sinc5_filt_fs_tbl[i],
490 				   &tmp1);
491 		tmp1 = mult_frac(tmp1, MICRO, 32 * ad4170_sinc5_filt_fs_tbl[i]);
492 		/* Fill sinc5 filter SPS table */
493 		st->sps_tbl[AD4170_SINC5][i][0] = tmp0; /* Integer part */
494 		st->sps_tbl[AD4170_SINC5][i][1] = tmp1; /* Fractional part */
495 	}
496 }
497 
ad4170_debugfs_reg_access(struct iio_dev * indio_dev,unsigned int reg,unsigned int writeval,unsigned int * readval)498 static int ad4170_debugfs_reg_access(struct iio_dev *indio_dev,
499 				     unsigned int reg, unsigned int writeval,
500 				     unsigned int *readval)
501 {
502 	struct ad4170_state *st = iio_priv(indio_dev);
503 
504 	if (readval)
505 		return regmap_read(st->regmap, reg, readval);
506 
507 	return regmap_write(st->regmap, reg, writeval);
508 }
509 
ad4170_get_reg_size(struct ad4170_state * st,unsigned int reg,unsigned int * size)510 static int ad4170_get_reg_size(struct ad4170_state *st, unsigned int reg,
511 			       unsigned int *size)
512 {
513 	if (reg >= ARRAY_SIZE(ad4170_reg_size))
514 		return -EINVAL;
515 
516 	*size = ad4170_reg_size[reg];
517 
518 	return 0;
519 }
520 
ad4170_reg_write(void * context,unsigned int reg,unsigned int val)521 static int ad4170_reg_write(void *context, unsigned int reg, unsigned int val)
522 {
523 	struct ad4170_state *st = context;
524 	u8 tx_buf[AD4170_SPI_MAX_XFER_LEN];
525 	unsigned int size;
526 	int ret;
527 
528 	ret = ad4170_get_reg_size(st, reg, &size);
529 	if (ret)
530 		return ret;
531 
532 	put_unaligned_be16(reg, tx_buf);
533 	switch (size) {
534 	case 3:
535 		put_unaligned_be24(val, &tx_buf[AD4170_SPI_INST_PHASE_LEN]);
536 		break;
537 	case 2:
538 		put_unaligned_be16(val, &tx_buf[AD4170_SPI_INST_PHASE_LEN]);
539 		break;
540 	case 1:
541 		tx_buf[AD4170_SPI_INST_PHASE_LEN] = val;
542 		break;
543 	case 0:
544 		/* Write continuous read exit code */
545 		tx_buf[0] = AD4170_ADC_CTRL_CONT_READ_EXIT;
546 		return spi_write_then_read(st->spi, tx_buf, 1, NULL, 0);
547 	default:
548 		return -EINVAL;
549 	}
550 
551 	return spi_write_then_read(st->spi, tx_buf,
552 				   AD4170_SPI_INST_PHASE_LEN + size, NULL, 0);
553 }
554 
ad4170_reg_read(void * context,unsigned int reg,unsigned int * val)555 static int ad4170_reg_read(void *context, unsigned int reg, unsigned int *val)
556 {
557 	struct ad4170_state *st = context;
558 	u8 tx_buf[AD4170_SPI_INST_PHASE_LEN];
559 	unsigned int size;
560 	int ret;
561 
562 	put_unaligned_be16(AD4170_REG_READ_MASK | reg, tx_buf);
563 
564 	ret = ad4170_get_reg_size(st, reg, &size);
565 	if (ret)
566 		return ret;
567 
568 	ret = spi_write_then_read(st->spi, tx_buf, ARRAY_SIZE(tx_buf),
569 				  st->rx_buf, size);
570 	if (ret)
571 		return ret;
572 
573 	switch (size) {
574 	case 3:
575 		*val = get_unaligned_be24(st->rx_buf);
576 		return 0;
577 	case 2:
578 		*val = get_unaligned_be16(st->rx_buf);
579 		return 0;
580 	case 1:
581 		*val = st->rx_buf[0];
582 		return 0;
583 	default:
584 		return -EINVAL;
585 	}
586 }
587 
588 static const struct regmap_config ad4170_regmap_config = {
589 	.reg_read = ad4170_reg_read,
590 	.reg_write = ad4170_reg_write,
591 };
592 
ad4170_setup_eq(struct ad4170_setup * a,struct ad4170_setup * b)593 static bool ad4170_setup_eq(struct ad4170_setup *a, struct ad4170_setup *b)
594 {
595 	if (a->misc != b->misc ||
596 	    a->afe != b->afe ||
597 	    a->filter != b->filter ||
598 	    a->filter_fs != b->filter_fs ||
599 	    a->offset != b->offset ||
600 	    a->gain != b->gain)
601 		return false;
602 
603 	return true;
604 }
605 
ad4170_find_setup(struct ad4170_state * st,struct ad4170_setup * target_setup,unsigned int * setup_num,bool * overwrite)606 static int ad4170_find_setup(struct ad4170_state *st,
607 			     struct ad4170_setup *target_setup,
608 			     unsigned int *setup_num, bool *overwrite)
609 {
610 	unsigned int i;
611 
612 	*setup_num = AD4170_INVALID_SETUP;
613 	*overwrite = false;
614 
615 	for (i = 0; i < AD4170_MAX_SETUPS; i++) {
616 		struct ad4170_setup_info *setup_info = &st->setup_infos[i];
617 
618 		/* Immediately accept a matching setup. */
619 		if (ad4170_setup_eq(target_setup, &setup_info->setup)) {
620 			*setup_num = i;
621 			return 0;
622 		}
623 
624 		/* Ignore all setups which are used by enabled channels. */
625 		if (setup_info->enabled_channels)
626 			continue;
627 
628 		/* Find the least used slot. */
629 		if (*setup_num == AD4170_INVALID_SETUP ||
630 		    setup_info->channels < st->setup_infos[*setup_num].channels)
631 			*setup_num = i;
632 	}
633 
634 	if (*setup_num == AD4170_INVALID_SETUP)
635 		return -EINVAL;
636 
637 	*overwrite = true;
638 	return 0;
639 }
640 
ad4170_unlink_channel(struct ad4170_state * st,unsigned int channel)641 static void ad4170_unlink_channel(struct ad4170_state *st, unsigned int channel)
642 {
643 	struct ad4170_chan_info *chan_info = &st->chan_infos[channel];
644 	struct ad4170_setup_info *setup_info = &st->setup_infos[chan_info->setup_num];
645 
646 	chan_info->setup_num = AD4170_INVALID_SETUP;
647 	setup_info->channels--;
648 }
649 
ad4170_unlink_setup(struct ad4170_state * st,unsigned int setup_num)650 static int ad4170_unlink_setup(struct ad4170_state *st, unsigned int setup_num)
651 {
652 	unsigned int i;
653 
654 	for (i = 0; i < AD4170_MAX_ADC_CHANNELS; i++) {
655 		struct ad4170_chan_info *chan_info = &st->chan_infos[i];
656 
657 		if (!chan_info->initialized || chan_info->setup_num != setup_num)
658 			continue;
659 
660 		ad4170_unlink_channel(st, i);
661 	}
662 	return 0;
663 }
664 
ad4170_link_channel_setup(struct ad4170_state * st,unsigned int chan_addr,unsigned int setup_num)665 static int ad4170_link_channel_setup(struct ad4170_state *st,
666 				     unsigned int chan_addr,
667 				     unsigned int setup_num)
668 {
669 	struct ad4170_setup_info *setup_info = &st->setup_infos[setup_num];
670 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan_addr];
671 	int ret;
672 
673 	ret = regmap_update_bits(st->regmap, AD4170_CHAN_SETUP_REG(chan_addr),
674 				 AD4170_CHAN_SETUP_SETUP_MSK,
675 				 FIELD_PREP(AD4170_CHAN_SETUP_SETUP_MSK, setup_num));
676 	if (ret)
677 		return ret;
678 
679 	chan_info->setup_num = setup_num;
680 	setup_info->channels++;
681 	return 0;
682 }
683 
ad4170_write_setup(struct ad4170_state * st,unsigned int setup_num,struct ad4170_setup * setup)684 static int ad4170_write_setup(struct ad4170_state *st, unsigned int setup_num,
685 			      struct ad4170_setup *setup)
686 {
687 	int ret;
688 
689 	/*
690 	 * It is recommended to place the ADC in standby mode or idle mode to
691 	 * write to OFFSET and GAIN registers.
692 	 */
693 	ret = regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
694 				 AD4170_ADC_CTRL_MODE_MSK,
695 				 FIELD_PREP(AD4170_ADC_CTRL_MODE_MSK,
696 					    AD4170_ADC_CTRL_MODE_IDLE));
697 	if (ret)
698 		return ret;
699 
700 	ret = regmap_write(st->regmap, AD4170_MISC_REG(setup_num), setup->misc);
701 	if (ret)
702 		return ret;
703 
704 	ret = regmap_write(st->regmap, AD4170_AFE_REG(setup_num), setup->afe);
705 	if (ret)
706 		return ret;
707 
708 	ret = regmap_write(st->regmap, AD4170_FILTER_REG(setup_num),
709 			   setup->filter);
710 	if (ret)
711 		return ret;
712 
713 	ret = regmap_write(st->regmap, AD4170_FILTER_FS_REG(setup_num),
714 			   setup->filter_fs);
715 	if (ret)
716 		return ret;
717 
718 	ret = regmap_write(st->regmap, AD4170_OFFSET_REG(setup_num),
719 			   setup->offset);
720 	if (ret)
721 		return ret;
722 
723 	ret = regmap_write(st->regmap, AD4170_GAIN_REG(setup_num), setup->gain);
724 	if (ret)
725 		return ret;
726 
727 	memcpy(&st->setup_infos[setup_num].setup, setup, sizeof(*setup));
728 	return 0;
729 }
730 
ad4170_write_channel_setup(struct ad4170_state * st,unsigned int chan_addr,bool on_enable)731 static int ad4170_write_channel_setup(struct ad4170_state *st,
732 				      unsigned int chan_addr, bool on_enable)
733 {
734 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan_addr];
735 	bool overwrite;
736 	int setup_num;
737 	int ret;
738 
739 	/*
740 	 * Similar to AD4130 driver, the following cases need to be handled.
741 	 *
742 	 * 1. Enabled and linked channel with setup changes:
743 	 *    - Find a setup. If not possible, return error.
744 	 *    - Unlink channel from current setup.
745 	 *    - If the setup found has only disabled channels linked to it,
746 	 *      unlink all channels, and write the new setup to it.
747 	 *    - Link channel to new setup.
748 	 *
749 	 * 2. Soon to be enabled and unlinked channel:
750 	 *    - Find a setup. If not possible, return error.
751 	 *    - If the setup found has only disabled channels linked to it,
752 	 *      unlink all channels, and write the new setup to it.
753 	 *    - Link channel to the setup.
754 	 *
755 	 * 3. Disabled and linked channel with setup changes:
756 	 *    - Unlink channel from current setup.
757 	 *
758 	 * 4. Soon to be enabled and linked channel:
759 	 * 5. Disabled and unlinked channel with setup changes:
760 	 *    - Do nothing.
761 	 */
762 
763 	/* Cases 3, 4, and 5 */
764 	if (chan_info->setup_num != AD4170_INVALID_SETUP) {
765 		/* Case 4 */
766 		if (on_enable)
767 			return 0;
768 
769 		/* Case 3 */
770 		if (!chan_info->enabled) {
771 			ad4170_unlink_channel(st, chan_addr);
772 			return 0;
773 		}
774 	} else if (!on_enable && !chan_info->enabled) {
775 		/* Case 5 */
776 		return 0;
777 	}
778 
779 	/* Cases 1 & 2 */
780 	ret = ad4170_find_setup(st, &chan_info->setup, &setup_num, &overwrite);
781 	if (ret)
782 		return ret;
783 
784 	if (chan_info->setup_num != AD4170_INVALID_SETUP)
785 		/* Case 1 */
786 		ad4170_unlink_channel(st, chan_addr);
787 
788 	if (overwrite) {
789 		ret = ad4170_unlink_setup(st, setup_num);
790 		if (ret)
791 			return ret;
792 
793 		ret = ad4170_write_setup(st, setup_num, &chan_info->setup);
794 		if (ret)
795 			return ret;
796 	}
797 
798 	return ad4170_link_channel_setup(st, chan_addr, setup_num);
799 }
800 
ad4170_set_channel_enable(struct ad4170_state * st,unsigned int chan_addr,bool status)801 static int ad4170_set_channel_enable(struct ad4170_state *st,
802 				     unsigned int chan_addr, bool status)
803 {
804 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan_addr];
805 	struct ad4170_setup_info *setup_info;
806 	int ret;
807 
808 	if (chan_info->enabled == status)
809 		return 0;
810 
811 	if (status) {
812 		ret = ad4170_write_channel_setup(st, chan_addr, true);
813 		if (ret)
814 			return ret;
815 	}
816 
817 	setup_info = &st->setup_infos[chan_info->setup_num];
818 
819 	ret = regmap_update_bits(st->regmap, AD4170_CHAN_EN_REG,
820 				 AD4170_CHAN_EN(chan_addr),
821 				 status ? AD4170_CHAN_EN(chan_addr) : 0);
822 	if (ret)
823 		return ret;
824 
825 	setup_info->enabled_channels += status ? 1 : -1;
826 	chan_info->enabled = status;
827 	return 0;
828 }
829 
__ad4170_get_filter_type(unsigned int filter)830 static int __ad4170_get_filter_type(unsigned int filter)
831 {
832 	u16 f_conf = FIELD_GET(AD4170_FILTER_FILTER_TYPE_MSK, filter);
833 
834 	switch (f_conf) {
835 	case AD4170_FILTER_FILTER_TYPE_SINC5_AVG:
836 		return AD4170_SINC5_AVG;
837 	case AD4170_FILTER_FILTER_TYPE_SINC5:
838 		return AD4170_SINC5;
839 	case AD4170_FILTER_FILTER_TYPE_SINC3:
840 		return AD4170_SINC3;
841 	default:
842 		return -EINVAL;
843 	}
844 }
845 
ad4170_set_filter_type(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,unsigned int val)846 static int ad4170_set_filter_type(struct iio_dev *indio_dev,
847 				  struct iio_chan_spec const *chan,
848 				  unsigned int val)
849 {
850 	struct ad4170_state *st = iio_priv(indio_dev);
851 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
852 	struct ad4170_setup *setup = &chan_info->setup;
853 	unsigned int filter_type_conf;
854 	int ret;
855 
856 	switch (val) {
857 	case AD4170_SINC5_AVG:
858 		filter_type_conf = AD4170_FILTER_FILTER_TYPE_SINC5_AVG;
859 		break;
860 	case AD4170_SINC5:
861 		filter_type_conf = AD4170_FILTER_FILTER_TYPE_SINC5;
862 		break;
863 	case AD4170_SINC3:
864 		filter_type_conf = AD4170_FILTER_FILTER_TYPE_SINC3;
865 		break;
866 	default:
867 		return -EINVAL;
868 	}
869 
870 	/*
871 	 * The filters provide the same ODR for a given filter_fs value but
872 	 * there are different minimum and maximum filter_fs limits for each
873 	 * filter. The filter_fs value will be adjusted if the current filter_fs
874 	 * is out of the limits of the just requested filter. Since the
875 	 * filter_fs value affects the ODR (sampling_frequency), changing the
876 	 * filter may lead to a change in the sampling frequency.
877 	 */
878 	scoped_guard(mutex, &st->lock) {
879 		if (!iio_device_claim_direct(indio_dev))
880 			return -EBUSY;
881 
882 		if (val == AD4170_SINC5_AVG || val == AD4170_SINC3)
883 			setup->filter_fs = clamp(val, AD4170_SINC3_MIN_FS,
884 						 AD4170_SINC3_MAX_FS);
885 		else
886 			setup->filter_fs = clamp(val, AD4170_SINC5_MIN_FS,
887 						 AD4170_SINC5_MAX_FS);
888 
889 		setup->filter &= ~AD4170_FILTER_FILTER_TYPE_MSK;
890 		setup->filter |= FIELD_PREP(AD4170_FILTER_FILTER_TYPE_MSK,
891 					    filter_type_conf);
892 
893 		ret = ad4170_write_channel_setup(st, chan->address, false);
894 		iio_device_release_direct(indio_dev);
895 	}
896 
897 	return ret;
898 }
899 
ad4170_get_filter_type(struct iio_dev * indio_dev,struct iio_chan_spec const * chan)900 static int ad4170_get_filter_type(struct iio_dev *indio_dev,
901 				  struct iio_chan_spec const *chan)
902 {
903 	struct ad4170_state *st = iio_priv(indio_dev);
904 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
905 	struct ad4170_setup *setup = &chan_info->setup;
906 
907 	return __ad4170_get_filter_type(setup->filter);
908 }
909 
910 static const struct iio_enum ad4170_filter_type_enum = {
911 	.items = ad4170_filt_names,
912 	.num_items = ARRAY_SIZE(ad4170_filt_names),
913 	.get = ad4170_get_filter_type,
914 	.set = ad4170_set_filter_type,
915 };
916 
917 static const struct iio_chan_spec_ext_info ad4170_filter_type_ext_info[] = {
918 	IIO_ENUM("filter_type", IIO_SEPARATE, &ad4170_filter_type_enum),
919 	IIO_ENUM_AVAILABLE("filter_type", IIO_SHARED_BY_TYPE,
920 			   &ad4170_filter_type_enum),
921 	{ }
922 };
923 
924 static const struct iio_chan_spec ad4170_channel_template = {
925 	.type = IIO_VOLTAGE,
926 	.indexed = 1,
927 	.differential = 1,
928 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
929 			      BIT(IIO_CHAN_INFO_SCALE) |
930 			      BIT(IIO_CHAN_INFO_CALIBBIAS) |
931 			      BIT(IIO_CHAN_INFO_CALIBSCALE) |
932 			      BIT(IIO_CHAN_INFO_SAMP_FREQ) |
933 			      BIT(IIO_CHAN_INFO_OFFSET),
934 	.info_mask_separate_available = BIT(IIO_CHAN_INFO_SCALE) |
935 					BIT(IIO_CHAN_INFO_SAMP_FREQ),
936 	.ext_info = ad4170_filter_type_ext_info,
937 	.scan_type = {
938 		.realbits = 24,
939 		.storagebits = 32,
940 		.shift = 8,
941 		.endianness = IIO_BE,
942 	},
943 };
944 
945 static const struct iio_chan_spec ad4170_temp_channel_template = {
946 	.type = IIO_TEMP,
947 	.indexed = 0,
948 	.channel = 17,
949 	.channel2 = 17,
950 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
951 			      BIT(IIO_CHAN_INFO_SCALE) |
952 			      BIT(IIO_CHAN_INFO_OFFSET) |
953 			      BIT(IIO_CHAN_INFO_CALIBSCALE) |
954 			      BIT(IIO_CHAN_INFO_CALIBBIAS) |
955 			      BIT(IIO_CHAN_INFO_SAMP_FREQ),
956 	.info_mask_separate_available = BIT(IIO_CHAN_INFO_SAMP_FREQ),
957 	.scan_type = {
958 		.sign = 's',
959 		.realbits = 24,
960 		.storagebits = 32,
961 		.shift = 8,
962 		.endianness = IIO_BE,
963 	},
964 };
965 
966 /*
967  * Receives the number of a multiplexed AD4170 input (ain_n), and stores the
968  * voltage (in µV) of the specified input into ain_voltage. If the input number
969  * is a ordinary analog input (AIN0 to AIN8), stores zero into ain_voltage.
970  * If a voltage regulator required by a special input is unavailable, return
971  * error code. Return 0 on success.
972  */
ad4170_get_ain_voltage_uv(struct ad4170_state * st,int ain_n,int * ain_voltage)973 static int ad4170_get_ain_voltage_uv(struct ad4170_state *st, int ain_n,
974 				     int *ain_voltage)
975 {
976 	struct device *dev = &st->spi->dev;
977 	int v_diff;
978 
979 	*ain_voltage = 0;
980 	/*
981 	 * The voltage bias (vbias) sets the common-mode voltage of the channel
982 	 * to (AVDD + AVSS)/2. If provided, AVSS supply provides the magnitude
983 	 * (absolute value) of the negative voltage supplied to the AVSS pin.
984 	 * So, we do AVDD - AVSS to compute the DC voltage generated by the bias
985 	 * voltage generator.
986 	 */
987 	if (st->pins_fn[ain_n] & AD4170_PIN_VBIAS) {
988 		int v_diff = st->vrefs_uv[AD4170_AVDD_SUP] - st->vrefs_uv[AD4170_AVSS_SUP];
989 		*ain_voltage = v_diff / 2;
990 		return 0;
991 	}
992 
993 	if (ain_n <= AD4170_CHAN_MAP_TEMP_SENSOR)
994 		return 0;
995 
996 	switch (ain_n) {
997 	case AD4170_CHAN_MAP_AVDD_AVSS_N:
998 		v_diff = st->vrefs_uv[AD4170_AVDD_SUP] - st->vrefs_uv[AD4170_AVSS_SUP];
999 		*ain_voltage = v_diff / 5;
1000 		return 0;
1001 	case AD4170_CHAN_MAP_IOVDD_DGND_N:
1002 		*ain_voltage = st->vrefs_uv[AD4170_IOVDD_SUP] / 5;
1003 		return 0;
1004 	case AD4170_CHAN_MAP_AVSS:
1005 		*ain_voltage = st->vrefs_uv[AD4170_AVSS_SUP];
1006 		return 0;
1007 	case AD4170_CHAN_MAP_DGND:
1008 		*ain_voltage = 0;
1009 		return 0;
1010 	case AD4170_CHAN_MAP_REFIN1_P:
1011 		if (st->vrefs_uv[AD4170_REFIN1P_SUP] == -ENODEV)
1012 			return dev_err_probe(dev, -ENODEV,
1013 					     "input set to REFIN+ but ref not provided\n");
1014 
1015 		*ain_voltage = st->vrefs_uv[AD4170_REFIN1P_SUP];
1016 		return 0;
1017 	case AD4170_CHAN_MAP_REFIN1_N:
1018 		if (st->vrefs_uv[AD4170_REFIN1N_SUP] == -ENODEV)
1019 			return dev_err_probe(dev, -ENODEV,
1020 					     "input set to REFIN- but ref not provided\n");
1021 
1022 		*ain_voltage = st->vrefs_uv[AD4170_REFIN1N_SUP];
1023 		return 0;
1024 	case AD4170_CHAN_MAP_REFIN2_P:
1025 		if (st->vrefs_uv[AD4170_REFIN2P_SUP] == -ENODEV)
1026 			return dev_err_probe(dev, -ENODEV,
1027 					     "input set to REFIN2+ but ref not provided\n");
1028 
1029 		*ain_voltage = st->vrefs_uv[AD4170_REFIN2P_SUP];
1030 		return 0;
1031 	case AD4170_CHAN_MAP_REFIN2_N:
1032 		if (st->vrefs_uv[AD4170_REFIN2N_SUP] == -ENODEV)
1033 			return dev_err_probe(dev, -ENODEV,
1034 					     "input set to REFIN2- but ref not provided\n");
1035 
1036 		*ain_voltage = st->vrefs_uv[AD4170_REFIN2N_SUP];
1037 		return 0;
1038 	case AD4170_CHAN_MAP_REFOUT:
1039 		/* REFOUT is 2.5V relative to AVSS so take that into account */
1040 		*ain_voltage = st->vrefs_uv[AD4170_AVSS_SUP] + AD4170_INT_REF_2_5V;
1041 		return 0;
1042 	default:
1043 		return -EINVAL;
1044 	}
1045 }
1046 
ad4170_validate_analog_input(struct ad4170_state * st,int pin)1047 static int ad4170_validate_analog_input(struct ad4170_state *st, int pin)
1048 {
1049 	if (pin <= AD4170_MAX_ANALOG_PINS) {
1050 		if (st->pins_fn[pin] & AD4170_PIN_CURRENT_OUT)
1051 			return dev_err_probe(&st->spi->dev, -EINVAL,
1052 					     "Pin %d already used with fn %u.\n",
1053 					     pin, st->pins_fn[pin]);
1054 
1055 		st->pins_fn[pin] |= AD4170_PIN_ANALOG_IN;
1056 	}
1057 	return 0;
1058 }
1059 
ad4170_validate_channel_input(struct ad4170_state * st,int pin,bool com)1060 static int ad4170_validate_channel_input(struct ad4170_state *st, int pin, bool com)
1061 {
1062 	/* Check common-mode input pin is mapped to a special input. */
1063 	if (com && (pin < AD4170_CHAN_MAP_AVDD_AVSS_P || pin > AD4170_CHAN_MAP_REFOUT))
1064 		return dev_err_probe(&st->spi->dev, -EINVAL,
1065 				     "Invalid common-mode input pin number. %d\n",
1066 				     pin);
1067 
1068 	/* Check differential input pin is mapped to a analog input pin. */
1069 	if (!com && pin > AD4170_MAX_ANALOG_PINS)
1070 		return dev_err_probe(&st->spi->dev, -EINVAL,
1071 				     "Invalid analog input pin number. %d\n",
1072 				     pin);
1073 
1074 	return ad4170_validate_analog_input(st, pin);
1075 }
1076 
1077 /*
1078  * Verifies whether the channel input configuration is valid by checking the
1079  * input numbers.
1080  * Returns 0 on valid channel input configuration. -EINVAL otherwise.
1081  */
ad4170_validate_channel(struct ad4170_state * st,struct iio_chan_spec const * chan)1082 static int ad4170_validate_channel(struct ad4170_state *st,
1083 				   struct iio_chan_spec const *chan)
1084 {
1085 	int ret;
1086 
1087 	ret = ad4170_validate_channel_input(st, chan->channel, false);
1088 	if (ret)
1089 		return ret;
1090 
1091 	return ad4170_validate_channel_input(st, chan->channel2,
1092 					     !chan->differential);
1093 }
1094 
1095 /*
1096  * Verifies whether the channel configuration is valid by checking the provided
1097  * input type, polarity, and voltage references result in a sane input range.
1098  * Returns negative error code on failure.
1099  */
ad4170_get_input_range(struct ad4170_state * st,struct iio_chan_spec const * chan,unsigned int ch_reg,unsigned int ref_sel)1100 static int ad4170_get_input_range(struct ad4170_state *st,
1101 				  struct iio_chan_spec const *chan,
1102 				  unsigned int ch_reg, unsigned int ref_sel)
1103 {
1104 	bool bipolar = chan->scan_type.sign == 's';
1105 	struct device *dev = &st->spi->dev;
1106 	int refp, refn, ain_voltage, ret;
1107 
1108 	switch (ref_sel) {
1109 	case AD4170_REF_REFIN1:
1110 		if (st->vrefs_uv[AD4170_REFIN1P_SUP] == -ENODEV ||
1111 		    st->vrefs_uv[AD4170_REFIN1N_SUP] == -ENODEV)
1112 			return dev_err_probe(dev, -ENODEV,
1113 					     "REFIN± selected but not provided\n");
1114 
1115 		refp = st->vrefs_uv[AD4170_REFIN1P_SUP];
1116 		refn = st->vrefs_uv[AD4170_REFIN1N_SUP];
1117 		break;
1118 	case AD4170_REF_REFIN2:
1119 		if (st->vrefs_uv[AD4170_REFIN2P_SUP] == -ENODEV ||
1120 		    st->vrefs_uv[AD4170_REFIN2N_SUP] == -ENODEV)
1121 			return dev_err_probe(dev, -ENODEV,
1122 					     "REFIN2± selected but not provided\n");
1123 
1124 		refp = st->vrefs_uv[AD4170_REFIN2P_SUP];
1125 		refn = st->vrefs_uv[AD4170_REFIN2N_SUP];
1126 		break;
1127 	case AD4170_REF_AVDD:
1128 		refp = st->vrefs_uv[AD4170_AVDD_SUP];
1129 		refn = st->vrefs_uv[AD4170_AVSS_SUP];
1130 		break;
1131 	case AD4170_REF_REFOUT:
1132 		/* REFOUT is 2.5 V relative to AVSS */
1133 		refp = st->vrefs_uv[AD4170_AVSS_SUP] + AD4170_INT_REF_2_5V;
1134 		refn = st->vrefs_uv[AD4170_AVSS_SUP];
1135 		break;
1136 	default:
1137 		return -EINVAL;
1138 	}
1139 
1140 	/*
1141 	 * Find out the analog input range from the channel type, polarity, and
1142 	 * voltage reference selection.
1143 	 * AD4170 channels are either differential or pseudo-differential.
1144 	 * Diff input voltage range: −VREF/gain to +VREF/gain (datasheet page 6)
1145 	 * Pseudo-diff input voltage range: 0 to VREF/gain (datasheet page 6)
1146 	 */
1147 	if (chan->differential) {
1148 		if (!bipolar)
1149 			return dev_err_probe(dev, -EINVAL,
1150 					     "Channel %u differential unipolar\n",
1151 					     ch_reg);
1152 
1153 		/*
1154 		 * Differential bipolar channel.
1155 		 * avss-supply is never above 0V.
1156 		 * Assuming refin1n-supply not above 0V.
1157 		 * Assuming refin2n-supply not above 0V.
1158 		 */
1159 		return refp + abs(refn);
1160 	}
1161 	/*
1162 	 * Some configurations can lead to invalid setups.
1163 	 * For example, if AVSS = -2.5V, REF_SELECT set to REFOUT (REFOUT/AVSS),
1164 	 * and pseudo-diff channel configuration set, then the input range
1165 	 * should go from 0V to +VREF (single-ended - datasheet pg 10), but
1166 	 * REFOUT/AVSS range would be -2.5V to 0V.
1167 	 * Check the positive reference is higher than 0V for pseudo-diff
1168 	 * channels.
1169 	 * Note that at this point in the code, refp can only be >= 0 since all
1170 	 * error codes from reading the regulator voltage have been checked
1171 	 * either at ad4170_regulator_setup() or above in this function.
1172 	 */
1173 	if (refp == 0)
1174 		return dev_err_probe(dev, -EINVAL,
1175 				     "REF+ == GND for pseudo-diff chan %u\n",
1176 				     ch_reg);
1177 
1178 	if (bipolar)
1179 		return refp;
1180 
1181 	/*
1182 	 * Pseudo-differential unipolar channel.
1183 	 * Input expected to swing from IN- to +VREF.
1184 	 */
1185 	ret = ad4170_get_ain_voltage_uv(st, chan->channel2, &ain_voltage);
1186 	if (ret)
1187 		return ret;
1188 
1189 	if (refp - ain_voltage <= 0)
1190 		return dev_err_probe(dev, -EINVAL,
1191 				     "Negative input >= REF+ for pseudo-diff chan %u\n",
1192 				     ch_reg);
1193 
1194 	return refp - ain_voltage;
1195 }
1196 
__ad4170_read_sample(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val)1197 static int __ad4170_read_sample(struct iio_dev *indio_dev,
1198 				struct iio_chan_spec const *chan, int *val)
1199 {
1200 	struct ad4170_state *st = iio_priv(indio_dev);
1201 	unsigned long settling_time_ms;
1202 	int ret;
1203 
1204 	reinit_completion(&st->completion);
1205 	ret = regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
1206 				 AD4170_ADC_CTRL_MODE_MSK,
1207 				 FIELD_PREP(AD4170_ADC_CTRL_MODE_MSK,
1208 					    AD4170_ADC_CTRL_MODE_SINGLE));
1209 	if (ret)
1210 		return ret;
1211 
1212 	/*
1213 	 * When a channel is manually selected by the user, the ADC needs an
1214 	 * extra time to provide the first stable conversion. The ADC settling
1215 	 * time depends on the filter type, filter frequency, and ADC clock
1216 	 * frequency (see datasheet page 53). The maximum settling time among
1217 	 * all filter configurations is 6291164 / fCLK. Use that formula to wait
1218 	 * for sufficient time whatever the filter configuration may be.
1219 	 */
1220 	settling_time_ms = DIV_ROUND_UP(6291164 * MILLI, st->mclk_hz);
1221 	ret = wait_for_completion_timeout(&st->completion,
1222 					  msecs_to_jiffies(settling_time_ms));
1223 	if (!ret)
1224 		dev_dbg(&st->spi->dev,
1225 			"No Data Ready signal. Reading after delay.\n");
1226 
1227 	ret = regmap_read(st->regmap, AD4170_DATA_24B_REG, val);
1228 	if (ret)
1229 		return ret;
1230 
1231 	if (chan->scan_type.sign == 's')
1232 		*val = sign_extend32(*val, chan->scan_type.realbits - 1);
1233 
1234 	return 0;
1235 }
1236 
ad4170_read_sample(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val)1237 static int ad4170_read_sample(struct iio_dev *indio_dev,
1238 			      struct iio_chan_spec const *chan, int *val)
1239 {
1240 	struct ad4170_state *st = iio_priv(indio_dev);
1241 	struct device *dev = &st->spi->dev;
1242 	int ret, ret2;
1243 
1244 	/*
1245 	 * The ADC sequences through all enabled channels. That can lead to
1246 	 * incorrect channel being sampled if a previous read would have left a
1247 	 * different channel enabled. Thus, always enable and disable the
1248 	 * channel on single-shot read.
1249 	 */
1250 	ret = ad4170_set_channel_enable(st, chan->address, true);
1251 	if (ret)
1252 		return ret;
1253 
1254 	ret = __ad4170_read_sample(indio_dev, chan, val);
1255 	if (ret) {
1256 		dev_err(dev, "failed to read sample: %d\n", ret);
1257 
1258 		ret2 = ad4170_set_channel_enable(st, chan->address, false);
1259 		if (ret2)
1260 			dev_err(dev, "failed to disable channel: %d\n", ret2);
1261 
1262 		return ret;
1263 	}
1264 
1265 	ret = ad4170_set_channel_enable(st, chan->address, false);
1266 	if (ret)
1267 		return ret;
1268 
1269 	return IIO_VAL_INT;
1270 }
1271 
ad4170_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long info)1272 static int ad4170_read_raw(struct iio_dev *indio_dev,
1273 			   struct iio_chan_spec const *chan,
1274 			   int *val, int *val2, long info)
1275 {
1276 	struct ad4170_state *st = iio_priv(indio_dev);
1277 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
1278 	struct ad4170_setup *setup = &chan_info->setup;
1279 	enum ad4170_filter_type f_type;
1280 	unsigned int pga, fs_idx;
1281 	int ret;
1282 
1283 	guard(mutex)(&st->lock);
1284 	switch (info) {
1285 	case IIO_CHAN_INFO_RAW:
1286 		if (!iio_device_claim_direct(indio_dev))
1287 			return -EBUSY;
1288 
1289 		ret = ad4170_read_sample(indio_dev, chan, val);
1290 		iio_device_release_direct(indio_dev);
1291 		return ret;
1292 	case IIO_CHAN_INFO_SCALE:
1293 		pga = FIELD_GET(AD4170_AFE_PGA_GAIN_MSK, setup->afe);
1294 		switch (chan->type) {
1295 		case IIO_VOLTAGE:
1296 			*val = chan_info->scale_tbl[pga][0];
1297 			*val2 = chan_info->scale_tbl[pga][1];
1298 			return IIO_VAL_INT_PLUS_NANO;
1299 		case IIO_TEMP:
1300 			/*
1301 			 * The scale_tbl converts output codes to mV units so
1302 			 * multiply by MILLI to make the factor convert to µV.
1303 			 * Then, apply the temperature sensor change sensitivity
1304 			 * of 477 μV/K. Finally, multiply the result by MILLI
1305 			 * again to comply with milli degrees Celsius IIO ABI.
1306 			 */
1307 			*val = 0;
1308 			*val2 = DIV_ROUND_CLOSEST(chan_info->scale_tbl[pga][1] * MILLI, 477) *
1309 						  MILLI;
1310 			return IIO_VAL_INT_PLUS_NANO;
1311 		default:
1312 			return -EINVAL;
1313 		}
1314 	case IIO_CHAN_INFO_OFFSET:
1315 		pga = FIELD_GET(AD4170_AFE_PGA_GAIN_MSK, setup->afe);
1316 		*val = chan_info->offset_tbl[pga];
1317 		return IIO_VAL_INT;
1318 	case IIO_CHAN_INFO_SAMP_FREQ:
1319 		f_type = __ad4170_get_filter_type(setup->filter);
1320 		switch (f_type) {
1321 		case AD4170_SINC5_AVG:
1322 		case AD4170_SINC3:
1323 			fs_idx = find_closest(setup->filter_fs,
1324 					      ad4170_sinc3_filt_fs_tbl,
1325 					      ARRAY_SIZE(ad4170_sinc3_filt_fs_tbl));
1326 			*val = st->sps_tbl[f_type][fs_idx][0];
1327 			*val2 = st->sps_tbl[f_type][fs_idx][1];
1328 			return IIO_VAL_INT_PLUS_MICRO;
1329 		case AD4170_SINC5:
1330 			fs_idx = find_closest(setup->filter_fs,
1331 					      ad4170_sinc5_filt_fs_tbl,
1332 					      ARRAY_SIZE(ad4170_sinc5_filt_fs_tbl));
1333 			*val = st->sps_tbl[f_type][fs_idx][0];
1334 			*val2 = st->sps_tbl[f_type][fs_idx][1];
1335 			return IIO_VAL_INT_PLUS_MICRO;
1336 		default:
1337 			return -EINVAL;
1338 		}
1339 	case IIO_CHAN_INFO_CALIBBIAS:
1340 		*val = setup->offset;
1341 		return IIO_VAL_INT;
1342 	case IIO_CHAN_INFO_CALIBSCALE:
1343 		*val = setup->gain;
1344 		return IIO_VAL_INT;
1345 	default:
1346 		return -EINVAL;
1347 	}
1348 }
1349 
ad4170_fill_scale_tbl(struct iio_dev * indio_dev,struct iio_chan_spec const * chan)1350 static int ad4170_fill_scale_tbl(struct iio_dev *indio_dev,
1351 				 struct iio_chan_spec const *chan)
1352 {
1353 	struct ad4170_state *st = iio_priv(indio_dev);
1354 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
1355 	struct device *dev = &st->spi->dev;
1356 	int bipolar = chan->scan_type.sign == 's' ? 1 : 0;
1357 	int precision_bits = chan->scan_type.realbits;
1358 	int pga, ainm_voltage, ret;
1359 	unsigned long long offset;
1360 
1361 	ainm_voltage = 0;
1362 	ret = ad4170_get_ain_voltage_uv(st, chan->channel2, &ainm_voltage);
1363 	if (ret < 0)
1364 		return dev_err_probe(dev, ret, "Failed to fill scale table\n");
1365 
1366 	for (pga = 0; pga < AD4170_NUM_PGA_OPTIONS; pga++) {
1367 		u64 nv;
1368 		unsigned int lshift, rshift;
1369 
1370 		/*
1371 		 * The PGA options are numbered from 0 to 9, with option 0 being
1372 		 * a gain of 2^0 (no actual gain), and 7 meaning a gain of 2^7.
1373 		 * Option 8, though, sets a gain of 0.5, so the input signal can
1374 		 * be attenuated by 2 rather than amplified. Option 9, allows
1375 		 * the signal to bypass the PGA circuitry (no gain).
1376 		 *
1377 		 * The scale factor to get ADC output codes to values in mV
1378 		 * units is given by:
1379 		 * _scale = (input_range / gain) / 2^precision
1380 		 * AD4170 gain is a power of 2 so the above can be written as
1381 		 * _scale = input_range / 2^(precision + gain)
1382 		 * Keep the input range in µV to avoid truncating the less
1383 		 * significant bits when right shifting it so to preserve scale
1384 		 * precision.
1385 		 */
1386 		nv = (u64)chan_info->input_range_uv * NANO;
1387 		lshift = !!(pga & BIT(3)); /* handle PGA options 8 and 9 */
1388 		rshift = precision_bits - bipolar + (pga & GENMASK(2, 0)) - lshift;
1389 		chan_info->scale_tbl[pga][0] = 0;
1390 		chan_info->scale_tbl[pga][1] = div_u64(nv >> rshift, MILLI);
1391 
1392 		/*
1393 		 * If the negative input is not at GND, the conversion result
1394 		 * (which is relative to IN-) will be offset by the level at IN-.
1395 		 * Use the scale factor the other way around to go from a known
1396 		 * voltage to the corresponding ADC output code.
1397 		 * With that, we are able to get to what would be the output
1398 		 * code for the voltage at the negative input.
1399 		 * If the negative input is not fixed, there is no offset.
1400 		 */
1401 		offset = ((unsigned long long)abs(ainm_voltage)) * MICRO;
1402 		offset = DIV_ROUND_CLOSEST_ULL(offset, chan_info->scale_tbl[pga][1]);
1403 
1404 		/*
1405 		 * After divided by the scale, offset will always fit into 31
1406 		 * bits. For _raw + _offset to be relative to GND, the value
1407 		 * provided as _offset is of opposite sign than the real offset.
1408 		 */
1409 		if (ainm_voltage > 0)
1410 			chan_info->offset_tbl[pga] = -(int)(offset);
1411 		else
1412 			chan_info->offset_tbl[pga] = (int)(offset);
1413 	}
1414 	return 0;
1415 }
1416 
ad4170_read_avail(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long info)1417 static int ad4170_read_avail(struct iio_dev *indio_dev,
1418 			     struct iio_chan_spec const *chan,
1419 			     const int **vals, int *type, int *length,
1420 			     long info)
1421 {
1422 	struct ad4170_state *st = iio_priv(indio_dev);
1423 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
1424 	enum ad4170_filter_type f_type;
1425 
1426 	switch (info) {
1427 	case IIO_CHAN_INFO_SCALE:
1428 		*vals = (int *)chan_info->scale_tbl;
1429 		*length = ARRAY_SIZE(chan_info->scale_tbl) * 2;
1430 		*type = IIO_VAL_INT_PLUS_NANO;
1431 		return IIO_AVAIL_LIST;
1432 	case IIO_CHAN_INFO_SAMP_FREQ:
1433 		*type = IIO_VAL_INT_PLUS_MICRO;
1434 		f_type = ad4170_get_filter_type(indio_dev, chan);
1435 		switch (f_type) {
1436 		case AD4170_SINC5_AVG:
1437 		case AD4170_SINC3:
1438 			/* Read sps_tbl here to ensure in bounds array access */
1439 			*vals = (int *)st->sps_tbl[f_type];
1440 			*length = ARRAY_SIZE(ad4170_sinc3_filt_fs_tbl) * 2;
1441 			return IIO_AVAIL_LIST;
1442 		case AD4170_SINC5:
1443 			/* Read sps_tbl here to ensure in bounds array access */
1444 			*vals = (int *)st->sps_tbl[f_type];
1445 			*length = ARRAY_SIZE(ad4170_sinc5_filt_fs_tbl) * 2;
1446 			return IIO_AVAIL_LIST;
1447 		default:
1448 			return -EINVAL;
1449 		}
1450 	default:
1451 		return -EINVAL;
1452 	}
1453 }
1454 
ad4170_set_pga(struct ad4170_state * st,struct iio_chan_spec const * chan,int val,int val2)1455 static int ad4170_set_pga(struct ad4170_state *st,
1456 			  struct iio_chan_spec const *chan, int val, int val2)
1457 {
1458 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
1459 	struct ad4170_setup *setup = &chan_info->setup;
1460 	unsigned int pga;
1461 
1462 	for (pga = 0; pga < AD4170_NUM_PGA_OPTIONS; pga++) {
1463 		if (val == chan_info->scale_tbl[pga][0] &&
1464 		    val2 == chan_info->scale_tbl[pga][1])
1465 			break;
1466 	}
1467 
1468 	if (pga == AD4170_NUM_PGA_OPTIONS)
1469 		return -EINVAL;
1470 
1471 	guard(mutex)(&st->lock);
1472 	setup->afe &= ~AD4170_AFE_PGA_GAIN_MSK;
1473 	setup->afe |= FIELD_PREP(AD4170_AFE_PGA_GAIN_MSK, pga);
1474 
1475 	return ad4170_write_channel_setup(st, chan->address, false);
1476 }
1477 
ad4170_set_channel_freq(struct ad4170_state * st,struct iio_chan_spec const * chan,int val,int val2)1478 static int ad4170_set_channel_freq(struct ad4170_state *st,
1479 				   struct iio_chan_spec const *chan, int val,
1480 				   int val2)
1481 {
1482 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
1483 	struct ad4170_setup *setup = &chan_info->setup;
1484 	enum ad4170_filter_type f_type = __ad4170_get_filter_type(setup->filter);
1485 	unsigned int filt_fs_tbl_size, i;
1486 
1487 	switch (f_type) {
1488 	case AD4170_SINC5_AVG:
1489 	case AD4170_SINC3:
1490 		filt_fs_tbl_size = ARRAY_SIZE(ad4170_sinc3_filt_fs_tbl);
1491 		break;
1492 	case AD4170_SINC5:
1493 		filt_fs_tbl_size = ARRAY_SIZE(ad4170_sinc5_filt_fs_tbl);
1494 		break;
1495 	}
1496 
1497 	for (i = 0; i < filt_fs_tbl_size; i++) {
1498 		if (st->sps_tbl[f_type][i][0] == val &&
1499 		    st->sps_tbl[f_type][i][1] == val2)
1500 			break;
1501 	}
1502 	if (i == filt_fs_tbl_size)
1503 		return -EINVAL;
1504 
1505 	guard(mutex)(&st->lock);
1506 	if (f_type == AD4170_SINC5)
1507 		setup->filter_fs = ad4170_sinc5_filt_fs_tbl[i];
1508 	else
1509 		setup->filter_fs = ad4170_sinc3_filt_fs_tbl[i];
1510 
1511 	return ad4170_write_channel_setup(st, chan->address, false);
1512 }
1513 
ad4170_set_calib_offset(struct ad4170_state * st,struct iio_chan_spec const * chan,int val)1514 static int ad4170_set_calib_offset(struct ad4170_state *st,
1515 				   struct iio_chan_spec const *chan, int val)
1516 {
1517 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
1518 	struct ad4170_setup *setup = &chan_info->setup;
1519 
1520 	guard(mutex)(&st->lock);
1521 	setup->offset = val;
1522 
1523 	return ad4170_write_channel_setup(st, chan->address, false);
1524 }
1525 
ad4170_set_calib_gain(struct ad4170_state * st,struct iio_chan_spec const * chan,int val)1526 static int ad4170_set_calib_gain(struct ad4170_state *st,
1527 				 struct iio_chan_spec const *chan, int val)
1528 {
1529 	struct ad4170_chan_info *chan_info = &st->chan_infos[chan->address];
1530 	struct ad4170_setup *setup = &chan_info->setup;
1531 
1532 	guard(mutex)(&st->lock);
1533 	setup->gain = val;
1534 
1535 	return ad4170_write_channel_setup(st, chan->address, false);
1536 }
1537 
__ad4170_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long info)1538 static int __ad4170_write_raw(struct iio_dev *indio_dev,
1539 			      struct iio_chan_spec const *chan, int val,
1540 			      int val2, long info)
1541 {
1542 	struct ad4170_state *st = iio_priv(indio_dev);
1543 
1544 	switch (info) {
1545 	case IIO_CHAN_INFO_SCALE:
1546 		return ad4170_set_pga(st, chan, val, val2);
1547 	case IIO_CHAN_INFO_SAMP_FREQ:
1548 		return ad4170_set_channel_freq(st, chan, val, val2);
1549 	case IIO_CHAN_INFO_CALIBBIAS:
1550 		return ad4170_set_calib_offset(st, chan, val);
1551 	case IIO_CHAN_INFO_CALIBSCALE:
1552 		return ad4170_set_calib_gain(st, chan, val);
1553 	default:
1554 		return -EINVAL;
1555 	}
1556 }
1557 
ad4170_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long info)1558 static int ad4170_write_raw(struct iio_dev *indio_dev,
1559 			    struct iio_chan_spec const *chan, int val,
1560 			    int val2, long info)
1561 {
1562 	int ret;
1563 
1564 	if (!iio_device_claim_direct(indio_dev))
1565 		return -EBUSY;
1566 
1567 	ret = __ad4170_write_raw(indio_dev, chan, val, val2, info);
1568 	iio_device_release_direct(indio_dev);
1569 	return ret;
1570 }
1571 
ad4170_write_raw_get_fmt(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,long info)1572 static int ad4170_write_raw_get_fmt(struct iio_dev *indio_dev,
1573 				    struct iio_chan_spec const *chan,
1574 				    long info)
1575 {
1576 	switch (info) {
1577 	case IIO_CHAN_INFO_SCALE:
1578 		return IIO_VAL_INT_PLUS_NANO;
1579 	case IIO_CHAN_INFO_SAMP_FREQ:
1580 		return IIO_VAL_INT_PLUS_MICRO;
1581 	case IIO_CHAN_INFO_CALIBBIAS:
1582 	case IIO_CHAN_INFO_CALIBSCALE:
1583 		return IIO_VAL_INT;
1584 	default:
1585 		return -EINVAL;
1586 	}
1587 }
1588 
ad4170_update_scan_mode(struct iio_dev * indio_dev,const unsigned long * active_scan_mask)1589 static int ad4170_update_scan_mode(struct iio_dev *indio_dev,
1590 				   const unsigned long *active_scan_mask)
1591 {
1592 	struct ad4170_state *st = iio_priv(indio_dev);
1593 	unsigned int chan_index;
1594 	int ret;
1595 
1596 	iio_for_each_active_channel(indio_dev, chan_index) {
1597 		ret = ad4170_set_channel_enable(st, chan_index, true);
1598 		if (ret)
1599 			return ret;
1600 	}
1601 	return 0;
1602 }
1603 
1604 static const struct iio_info ad4170_info = {
1605 	.read_raw = ad4170_read_raw,
1606 	.read_avail = ad4170_read_avail,
1607 	.write_raw = ad4170_write_raw,
1608 	.write_raw_get_fmt = ad4170_write_raw_get_fmt,
1609 	.update_scan_mode = ad4170_update_scan_mode,
1610 	.debugfs_reg_access = ad4170_debugfs_reg_access,
1611 };
1612 
ad4170_soft_reset(struct ad4170_state * st)1613 static int ad4170_soft_reset(struct ad4170_state *st)
1614 {
1615 	int ret;
1616 
1617 	ret = regmap_write(st->regmap, AD4170_CONFIG_A_REG,
1618 			   AD4170_SW_RESET_MSK);
1619 	if (ret)
1620 		return ret;
1621 
1622 	/* AD4170-4 requires 1 ms between reset and any register access. */
1623 	fsleep(1 * USEC_PER_MSEC);
1624 
1625 	return 0;
1626 }
1627 
ad4170_gpio_get(struct gpio_chip * gc,unsigned int offset)1628 static int ad4170_gpio_get(struct gpio_chip *gc, unsigned int offset)
1629 {
1630 	struct iio_dev *indio_dev = gpiochip_get_data(gc);
1631 	struct ad4170_state *st = iio_priv(indio_dev);
1632 	unsigned int val;
1633 	int ret;
1634 
1635 	if (!iio_device_claim_direct(indio_dev))
1636 		return -EBUSY;
1637 
1638 	ret = regmap_read(st->regmap, AD4170_GPIO_MODE_REG, &val);
1639 	if (ret)
1640 		goto err_release;
1641 
1642 	/*
1643 	 * If the GPIO is configured as an input, read the current value from
1644 	 * AD4170_GPIO_INPUT_REG. Otherwise, read the input value from
1645 	 * AD4170_GPIO_OUTPUT_REG.
1646 	 */
1647 	if (val & BIT(offset * 2))
1648 		ret = regmap_read(st->regmap, AD4170_GPIO_INPUT_REG, &val);
1649 	else
1650 		ret = regmap_read(st->regmap, AD4170_GPIO_OUTPUT_REG, &val);
1651 	if (ret)
1652 		goto err_release;
1653 
1654 	ret = !!(val & BIT(offset));
1655 err_release:
1656 	iio_device_release_direct(indio_dev);
1657 
1658 	return ret;
1659 }
1660 
ad4170_gpio_set(struct gpio_chip * gc,unsigned int offset,int value)1661 static int ad4170_gpio_set(struct gpio_chip *gc, unsigned int offset, int value)
1662 {
1663 	struct iio_dev *indio_dev = gpiochip_get_data(gc);
1664 	struct ad4170_state *st = iio_priv(indio_dev);
1665 	int ret;
1666 
1667 	if (!iio_device_claim_direct(indio_dev))
1668 		return -EBUSY;
1669 
1670 	ret = regmap_assign_bits(st->regmap, AD4170_GPIO_OUTPUT_REG,
1671 				 BIT(offset), !!value);
1672 
1673 	iio_device_release_direct(indio_dev);
1674 	return ret;
1675 }
1676 
ad4170_gpio_get_direction(struct gpio_chip * gc,unsigned int offset)1677 static int ad4170_gpio_get_direction(struct gpio_chip *gc, unsigned int offset)
1678 {
1679 	struct iio_dev *indio_dev = gpiochip_get_data(gc);
1680 	struct ad4170_state *st = iio_priv(indio_dev);
1681 	unsigned int val;
1682 	int ret;
1683 
1684 	if (!iio_device_claim_direct(indio_dev))
1685 		return -EBUSY;
1686 
1687 	ret = regmap_read(st->regmap, AD4170_GPIO_MODE_REG, &val);
1688 	if (ret)
1689 		goto err_release;
1690 
1691 	if (val & BIT(offset * 2 + 1))
1692 		ret = GPIO_LINE_DIRECTION_OUT;
1693 	else
1694 		ret = GPIO_LINE_DIRECTION_IN;
1695 
1696 err_release:
1697 	iio_device_release_direct(indio_dev);
1698 
1699 	return ret;
1700 }
1701 
ad4170_gpio_direction_input(struct gpio_chip * gc,unsigned int offset)1702 static int ad4170_gpio_direction_input(struct gpio_chip *gc, unsigned int offset)
1703 {
1704 	struct iio_dev *indio_dev = gpiochip_get_data(gc);
1705 	struct ad4170_state *st = iio_priv(indio_dev);
1706 	unsigned long gpio_mask;
1707 	int ret;
1708 
1709 	if (!iio_device_claim_direct(indio_dev))
1710 		return -EBUSY;
1711 
1712 	switch (offset) {
1713 	case 0:
1714 		gpio_mask = AD4170_GPIO_MODE_GPIO0_MSK;
1715 		break;
1716 	case 1:
1717 		gpio_mask = AD4170_GPIO_MODE_GPIO1_MSK;
1718 		break;
1719 	case 2:
1720 		gpio_mask = AD4170_GPIO_MODE_GPIO2_MSK;
1721 		break;
1722 	case 3:
1723 		gpio_mask = AD4170_GPIO_MODE_GPIO3_MSK;
1724 		break;
1725 	default:
1726 		ret = -EINVAL;
1727 		goto err_release;
1728 	}
1729 	ret = regmap_update_bits(st->regmap, AD4170_GPIO_MODE_REG, gpio_mask,
1730 				 AD4170_GPIO_MODE_GPIO_INPUT << (2 * offset));
1731 
1732 err_release:
1733 	iio_device_release_direct(indio_dev);
1734 
1735 	return ret;
1736 }
1737 
ad4170_gpio_direction_output(struct gpio_chip * gc,unsigned int offset,int value)1738 static int ad4170_gpio_direction_output(struct gpio_chip *gc,
1739 					unsigned int offset, int value)
1740 {
1741 	struct iio_dev *indio_dev = gpiochip_get_data(gc);
1742 	struct ad4170_state *st = iio_priv(indio_dev);
1743 	unsigned long gpio_mask;
1744 	int ret;
1745 
1746 	ret = ad4170_gpio_set(gc, offset, value);
1747 	if (ret)
1748 		return ret;
1749 
1750 	if (!iio_device_claim_direct(indio_dev))
1751 		return -EBUSY;
1752 
1753 	switch (offset) {
1754 	case 0:
1755 		gpio_mask = AD4170_GPIO_MODE_GPIO0_MSK;
1756 		break;
1757 	case 1:
1758 		gpio_mask = AD4170_GPIO_MODE_GPIO1_MSK;
1759 		break;
1760 	case 2:
1761 		gpio_mask = AD4170_GPIO_MODE_GPIO2_MSK;
1762 		break;
1763 	case 3:
1764 		gpio_mask = AD4170_GPIO_MODE_GPIO3_MSK;
1765 		break;
1766 	default:
1767 		ret = -EINVAL;
1768 		goto err_release;
1769 	}
1770 	ret = regmap_update_bits(st->regmap, AD4170_GPIO_MODE_REG, gpio_mask,
1771 				 AD4170_GPIO_MODE_GPIO_OUTPUT << (2 * offset));
1772 
1773 err_release:
1774 	iio_device_release_direct(indio_dev);
1775 
1776 	return ret;
1777 }
1778 
ad4170_gpio_init_valid_mask(struct gpio_chip * gc,unsigned long * valid_mask,unsigned int ngpios)1779 static int ad4170_gpio_init_valid_mask(struct gpio_chip *gc,
1780 				       unsigned long *valid_mask,
1781 				       unsigned int ngpios)
1782 {
1783 	struct ad4170_state *st = gpiochip_get_data(gc);
1784 	unsigned int i;
1785 
1786 	/* Only expose GPIOs that were not assigned any other function. */
1787 	for (i = 0; i < ngpios; i++) {
1788 		bool valid = st->gpio_fn[i] == AD4170_GPIO_UNASSIGNED;
1789 
1790 		__assign_bit(i, valid_mask, valid);
1791 	}
1792 
1793 	return 0;
1794 }
1795 
ad4170_gpio_init(struct iio_dev * indio_dev)1796 static int ad4170_gpio_init(struct iio_dev *indio_dev)
1797 {
1798 	struct ad4170_state *st = iio_priv(indio_dev);
1799 
1800 	st->gpiochip.label = "ad4170_gpios";
1801 	st->gpiochip.base = -1;
1802 	st->gpiochip.ngpio = AD4170_NUM_GPIO_PINS;
1803 	st->gpiochip.parent = &st->spi->dev;
1804 	st->gpiochip.can_sleep = true;
1805 	st->gpiochip.init_valid_mask = ad4170_gpio_init_valid_mask;
1806 	st->gpiochip.get_direction = ad4170_gpio_get_direction;
1807 	st->gpiochip.direction_input = ad4170_gpio_direction_input;
1808 	st->gpiochip.direction_output = ad4170_gpio_direction_output;
1809 	st->gpiochip.get = ad4170_gpio_get;
1810 	st->gpiochip.set = ad4170_gpio_set;
1811 	st->gpiochip.owner = THIS_MODULE;
1812 
1813 	return devm_gpiochip_add_data(&st->spi->dev, &st->gpiochip, indio_dev);
1814 }
1815 
ad4170_validate_excitation_pin(struct ad4170_state * st,u32 pin)1816 static int ad4170_validate_excitation_pin(struct ad4170_state *st, u32 pin)
1817 {
1818 	struct device *dev = &st->spi->dev;
1819 	unsigned int i;
1820 
1821 	/* Check the pin number is valid */
1822 	for (i = 0; i < ARRAY_SIZE(ad4170_iout_pin_tbl); i++)
1823 		if (ad4170_iout_pin_tbl[i] == pin)
1824 			break;
1825 
1826 	if (i == ARRAY_SIZE(ad4170_iout_pin_tbl))
1827 		return dev_err_probe(dev, -EINVAL,
1828 				     "Invalid excitation pin: %u\n",
1829 				     pin);
1830 
1831 	/* Check the pin is available */
1832 	if (pin <= AD4170_MAX_ANALOG_PINS) {
1833 		if (st->pins_fn[pin] != AD4170_PIN_UNASSIGNED)
1834 			return dev_err_probe(dev, -EINVAL,
1835 					     "Pin %u already used with fn %u\n",
1836 					     pin, st->pins_fn[pin]);
1837 
1838 		st->pins_fn[pin] |= AD4170_PIN_CURRENT_OUT;
1839 	} else {
1840 		unsigned int gpio = pin - AD4170_CURRENT_SRC_I_OUT_PIN_GPIO(0);
1841 
1842 		if (st->gpio_fn[gpio] != AD4170_GPIO_UNASSIGNED)
1843 			return dev_err_probe(dev, -EINVAL,
1844 					     "GPIO %u already used with fn %u\n",
1845 					     gpio, st->gpio_fn[gpio]);
1846 
1847 		st->gpio_fn[gpio] |= AD4170_GPIO_AC_EXCITATION;
1848 	}
1849 
1850 	return 0;
1851 }
1852 
ad4170_validate_excitation_pins(struct ad4170_state * st,u32 * exc_pins,int num_exc_pins)1853 static int ad4170_validate_excitation_pins(struct ad4170_state *st,
1854 					   u32 *exc_pins, int num_exc_pins)
1855 {
1856 	unsigned int i;
1857 	int ret;
1858 
1859 	for (i = 0; i < num_exc_pins; i++) {
1860 		ret = ad4170_validate_excitation_pin(st, exc_pins[i]);
1861 		if (ret)
1862 			return ret;
1863 	}
1864 	return 0;
1865 }
1866 
1867 static const char *const ad4170_i_out_pin_dt_props[] = {
1868 	"adi,excitation-pin-0",
1869 	"adi,excitation-pin-1",
1870 	"adi,excitation-pin-2",
1871 	"adi,excitation-pin-3",
1872 };
1873 
1874 static const char *const ad4170_i_out_val_dt_props[] = {
1875 	"adi,excitation-current-0-microamp",
1876 	"adi,excitation-current-1-microamp",
1877 	"adi,excitation-current-2-microamp",
1878 	"adi,excitation-current-3-microamp",
1879 };
1880 
1881 /*
1882  * Parses firmware data describing output current source setup. There are 4
1883  * excitation currents (IOUT0 to IOUT3) that can be configured independently.
1884  * Excitation currents are added if they are output on the same pin.
1885  */
ad4170_parse_exc_current(struct ad4170_state * st,struct fwnode_handle * child,unsigned int * exc_pins,unsigned int * exc_curs,unsigned int * num_exc_pins)1886 static int ad4170_parse_exc_current(struct ad4170_state *st,
1887 				    struct fwnode_handle *child,
1888 				    unsigned int *exc_pins,
1889 				    unsigned int *exc_curs,
1890 				    unsigned int *num_exc_pins)
1891 {
1892 	struct device *dev = &st->spi->dev;
1893 	unsigned int num_pins, i, j;
1894 	u32 pin, val;
1895 	int ret;
1896 
1897 	num_pins = 0;
1898 	for (i = 0; i < AD4170_NUM_CURRENT_SRC; i++) {
1899 		/* Parse excitation current output pin properties. */
1900 		pin = AD4170_CURRENT_SRC_I_OUT_PIN_AIN(0);
1901 		ret = fwnode_property_read_u32(child, ad4170_i_out_pin_dt_props[i],
1902 					       &pin);
1903 		if (ret)
1904 			continue;
1905 
1906 		exc_pins[num_pins] = pin;
1907 
1908 		/* Parse excitation current value properties. */
1909 		val = ad4170_iout_current_ua_tbl[0];
1910 		fwnode_property_read_u32(child,
1911 					 ad4170_i_out_val_dt_props[i], &val);
1912 
1913 		for (j = 0; j < ARRAY_SIZE(ad4170_iout_current_ua_tbl); j++)
1914 			if (ad4170_iout_current_ua_tbl[j] == val)
1915 				break;
1916 
1917 		if (j == ARRAY_SIZE(ad4170_iout_current_ua_tbl))
1918 			return dev_err_probe(dev, -EINVAL, "Invalid %s: %uuA\n",
1919 					     ad4170_i_out_val_dt_props[i], val);
1920 
1921 		exc_curs[num_pins] = j;
1922 		num_pins++;
1923 	}
1924 	*num_exc_pins = num_pins;
1925 
1926 	return 0;
1927 }
1928 
ad4170_setup_current_src(struct ad4170_state * st,struct fwnode_handle * child,struct ad4170_setup * setup,u32 * exc_pins,unsigned int * exc_curs,int num_exc_pins,bool ac_excited)1929 static int ad4170_setup_current_src(struct ad4170_state *st,
1930 				    struct fwnode_handle *child,
1931 				    struct ad4170_setup *setup, u32 *exc_pins,
1932 				    unsigned int *exc_curs, int num_exc_pins,
1933 				    bool ac_excited)
1934 {
1935 	unsigned int exc_cur_pair, i, j;
1936 	int ret;
1937 
1938 	for (i = 0; i < num_exc_pins; i++) {
1939 		unsigned int exc_cur = exc_curs[i];
1940 		unsigned int pin = exc_pins[i];
1941 		unsigned int current_src = 0;
1942 
1943 		for (j = 0; j < AD4170_NUM_CURRENT_SRC; j++)
1944 			if (st->cur_src_pins[j] == AD4170_CURRENT_SRC_DISABLED)
1945 				break;
1946 
1947 		if (j == AD4170_NUM_CURRENT_SRC)
1948 			return dev_err_probe(&st->spi->dev, -EINVAL,
1949 					     "Too many excitation current sources\n");
1950 
1951 		current_src |= FIELD_PREP(AD4170_CURRENT_SRC_I_OUT_PIN_MSK, pin);
1952 		current_src |= FIELD_PREP(AD4170_CURRENT_SRC_I_OUT_VAL_MSK, exc_cur);
1953 		st->cur_src_pins[j] = pin;
1954 		ret = regmap_write(st->regmap, AD4170_CURRENT_SRC_REG(j),
1955 				   current_src);
1956 		if (ret)
1957 			return ret;
1958 	}
1959 
1960 	if (!ac_excited)
1961 		return 0;
1962 
1963 	if (num_exc_pins < 2)
1964 		return dev_err_probe(&st->spi->dev, -EINVAL,
1965 			"Current chopping requested but only one pin provided: %u\n",
1966 			exc_pins[0]);
1967 
1968 	/*
1969 	 * Two use cases to handle here:
1970 	 * - 2 pairs of excitation currents;
1971 	 * - 1 pair of excitation currents.
1972 	 */
1973 	if (num_exc_pins == 4) {
1974 		for (i = 0; i < AD4170_NUM_CURRENT_SRC; i++)
1975 			if (st->cur_src_pins[i] != exc_pins[i])
1976 				return dev_err_probe(&st->spi->dev, -EINVAL,
1977 						     "Unable to use 4 exc pins\n");
1978 	} else {
1979 		/*
1980 		 * Excitation current chopping is configured in pairs. Current
1981 		 * sources IOUT0 and IOUT1 form pair 1, IOUT2 and IOUT3 make up
1982 		 * pair 2. So, if current chopping was requested, check if the
1983 		 * first end of the first pair of excitation currents is
1984 		 * available. Try the next pair if IOUT0 has already been
1985 		 * configured for another channel.
1986 		 */
1987 		i = st->cur_src_pins[0] == exc_pins[0] ? 0 : 2;
1988 
1989 		if (st->cur_src_pins[i] != exc_pins[0] ||
1990 		    st->cur_src_pins[i + 1] != exc_pins[1])
1991 			return dev_err_probe(&st->spi->dev, -EINVAL,
1992 					     "Failed to setup current chopping\n");
1993 
1994 		st->cur_src_pins[i] = exc_pins[0];
1995 		st->cur_src_pins[i + 1] = exc_pins[1];
1996 
1997 		if (i == 0)
1998 			exc_cur_pair = AD4170_MISC_CHOP_IEXC_PAIR1;
1999 		else
2000 			exc_cur_pair = AD4170_MISC_CHOP_IEXC_PAIR2;
2001 	}
2002 
2003 	/*
2004 	 * Configure excitation current chopping.
2005 	 * Chop both pairs if using four excitation pins.
2006 	 */
2007 	setup->misc |= FIELD_PREP(AD4170_MISC_CHOP_IEXC_MSK,
2008 				  num_exc_pins == 2 ?
2009 				  exc_cur_pair :
2010 				  AD4170_MISC_CHOP_IEXC_BOTH);
2011 
2012 	return 0;
2013 }
2014 
ad4170_setup_bridge(struct ad4170_state * st,struct fwnode_handle * child,struct ad4170_setup * setup,u32 * exc_pins,unsigned int * exc_curs,int num_exc_pins,bool ac_excited)2015 static int ad4170_setup_bridge(struct ad4170_state *st,
2016 			       struct fwnode_handle *child,
2017 			       struct ad4170_setup *setup, u32 *exc_pins,
2018 			       unsigned int *exc_curs, int num_exc_pins,
2019 			       bool ac_excited)
2020 {
2021 	unsigned long gpio_mask;
2022 	unsigned int i;
2023 	int ret;
2024 
2025 	/*
2026 	 * If a specific current is provided through
2027 	 * adi,excitation-current-n-microamp, set excitation pins provided
2028 	 * through adi,excitation-pin-n to excite the bridge circuit.
2029 	 */
2030 	for (i = 0; i < num_exc_pins; i++)
2031 		if (exc_curs[i] > 0)
2032 			return ad4170_setup_current_src(st, child, setup, exc_pins,
2033 							exc_curs, num_exc_pins,
2034 							ac_excited);
2035 
2036 	/*
2037 	 * Else, use predefined ACX1, ACX1 negated, ACX2, ACX2 negated signals
2038 	 * to AC excite the bridge. Those signals are output on GPIO2, GPIO0,
2039 	 * GPIO3, and GPIO1, respectively. If only two pins are specified for AC
2040 	 * excitation, use ACX1 and ACX2 (GPIO2 and GPIO3).
2041 	 *
2042 	 * Also, to avoid any short-circuit condition when more than one channel
2043 	 * is enabled, set GPIO2 and GPIO0 high, and set GPIO1 and GPIO3 low to
2044 	 * DC excite the bridge whenever a channel without AC excitation is
2045 	 * selected. That is needed because GPIO pins are controlled by the next
2046 	 * highest priority GPIO function when a channel doesn't enable AC
2047 	 * excitation. See datasheet Figure 113 Weigh Scale (AC Excitation) for
2048 	 * the reference circuit diagram.
2049 	 */
2050 	if (num_exc_pins == 2) {
2051 		setup->misc |= FIELD_PREP(AD4170_MISC_CHOP_ADC_MSK, 0x3);
2052 
2053 		gpio_mask = AD4170_GPIO_MODE_GPIO3_MSK | AD4170_GPIO_MODE_GPIO2_MSK;
2054 		ret = regmap_update_bits(st->regmap, AD4170_GPIO_MODE_REG, gpio_mask,
2055 					 FIELD_PREP(AD4170_GPIO_MODE_GPIO3_MSK,
2056 						    AD4170_GPIO_MODE_GPIO_OUTPUT) |
2057 					 FIELD_PREP(AD4170_GPIO_MODE_GPIO2_MSK,
2058 						    AD4170_GPIO_MODE_GPIO_OUTPUT));
2059 		if (ret)
2060 			return ret;
2061 
2062 		/*
2063 		 * Set GPIO2 high and GPIO3 low to DC excite the bridge when
2064 		 * a different channel is selected.
2065 		 */
2066 		gpio_mask = AD4170_GPIO_OUTPUT_GPIO_MSK(3) |
2067 			    AD4170_GPIO_OUTPUT_GPIO_MSK(2);
2068 		ret = regmap_update_bits(st->regmap, AD4170_GPIO_OUTPUT_REG, gpio_mask,
2069 					 FIELD_PREP(AD4170_GPIO_OUTPUT_GPIO_MSK(3), 0) |
2070 					 FIELD_PREP(AD4170_GPIO_OUTPUT_GPIO_MSK(2), 1));
2071 		if (ret)
2072 			return ret;
2073 
2074 		st->gpio_fn[3] |= AD4170_GPIO_OUTPUT;
2075 		st->gpio_fn[2] |= AD4170_GPIO_OUTPUT;
2076 	} else {
2077 		setup->misc |= FIELD_PREP(AD4170_MISC_CHOP_ADC_MSK, 0x2);
2078 
2079 		gpio_mask = AD4170_GPIO_MODE_GPIO3_MSK | AD4170_GPIO_MODE_GPIO2_MSK |
2080 			    AD4170_GPIO_MODE_GPIO1_MSK | AD4170_GPIO_MODE_GPIO0_MSK;
2081 		ret = regmap_update_bits(st->regmap, AD4170_GPIO_MODE_REG, gpio_mask,
2082 					 FIELD_PREP(AD4170_GPIO_MODE_GPIO3_MSK,
2083 						    AD4170_GPIO_MODE_GPIO_OUTPUT) |
2084 					 FIELD_PREP(AD4170_GPIO_MODE_GPIO2_MSK,
2085 						    AD4170_GPIO_MODE_GPIO_OUTPUT) |
2086 					 FIELD_PREP(AD4170_GPIO_MODE_GPIO1_MSK,
2087 						    AD4170_GPIO_MODE_GPIO_OUTPUT) |
2088 					 FIELD_PREP(AD4170_GPIO_MODE_GPIO0_MSK,
2089 						    AD4170_GPIO_MODE_GPIO_OUTPUT));
2090 		if (ret)
2091 			return ret;
2092 
2093 		/*
2094 		 * Set GPIO2 and GPIO0 high, and set GPIO1 and GPIO3 low to DC
2095 		 * excite the bridge when a different channel is selected.
2096 		 */
2097 		gpio_mask = AD4170_GPIO_OUTPUT_GPIO_MSK(3) |
2098 			    AD4170_GPIO_OUTPUT_GPIO_MSK(2) |
2099 			    AD4170_GPIO_OUTPUT_GPIO_MSK(1) |
2100 			    AD4170_GPIO_OUTPUT_GPIO_MSK(0);
2101 		ret = regmap_update_bits(st->regmap, AD4170_GPIO_OUTPUT_REG, gpio_mask,
2102 					 FIELD_PREP(AD4170_GPIO_OUTPUT_GPIO_MSK(3), 0) |
2103 					 FIELD_PREP(AD4170_GPIO_OUTPUT_GPIO_MSK(2), 1) |
2104 					 FIELD_PREP(AD4170_GPIO_OUTPUT_GPIO_MSK(1), 0) |
2105 					 FIELD_PREP(AD4170_GPIO_OUTPUT_GPIO_MSK(0), 1));
2106 		if (ret)
2107 			return ret;
2108 
2109 		st->gpio_fn[3] |= AD4170_GPIO_OUTPUT;
2110 		st->gpio_fn[2] |= AD4170_GPIO_OUTPUT;
2111 		st->gpio_fn[1] |= AD4170_GPIO_OUTPUT;
2112 		st->gpio_fn[0] |= AD4170_GPIO_OUTPUT;
2113 	}
2114 
2115 	return 0;
2116 }
2117 
ad4170_setup_rtd(struct ad4170_state * st,struct fwnode_handle * child,struct ad4170_setup * setup,u32 * exc_pins,unsigned int * exc_curs,int num_exc_pins,bool ac_excited)2118 static int ad4170_setup_rtd(struct ad4170_state *st,
2119 			    struct fwnode_handle *child,
2120 			    struct ad4170_setup *setup, u32 *exc_pins,
2121 			    unsigned int *exc_curs, int num_exc_pins, bool ac_excited)
2122 {
2123 	return ad4170_setup_current_src(st, child, setup, exc_pins,
2124 					exc_curs, num_exc_pins, ac_excited);
2125 }
2126 
ad4170_parse_external_sensor(struct ad4170_state * st,struct fwnode_handle * child,struct ad4170_setup * setup,struct iio_chan_spec * chan,unsigned int s_type)2127 static int ad4170_parse_external_sensor(struct ad4170_state *st,
2128 					struct fwnode_handle *child,
2129 					struct ad4170_setup *setup,
2130 					struct iio_chan_spec *chan,
2131 					unsigned int s_type)
2132 {
2133 	unsigned int num_exc_pins, reg_val;
2134 	struct device *dev = &st->spi->dev;
2135 	u32 pins[2], exc_pins[4], exc_curs[4];
2136 	bool ac_excited;
2137 	int ret;
2138 
2139 	ret = fwnode_property_read_u32_array(child, "diff-channels", pins,
2140 					     ARRAY_SIZE(pins));
2141 	if (ret)
2142 		return dev_err_probe(dev, ret,
2143 				     "Failed to read sensor diff-channels\n");
2144 
2145 	chan->differential = true;
2146 	chan->channel = pins[0];
2147 	chan->channel2 = pins[1];
2148 
2149 	ret = ad4170_parse_exc_current(st, child, exc_pins, exc_curs, &num_exc_pins);
2150 	if (ret)
2151 		return ret;
2152 
2153 	/* The external sensor may not need excitation from the ADC chip. */
2154 	if (num_exc_pins == 0)
2155 		return 0;
2156 
2157 	ret = ad4170_validate_excitation_pins(st, exc_pins, num_exc_pins);
2158 	if (ret)
2159 		return ret;
2160 
2161 	ac_excited = fwnode_property_read_bool(child, "adi,excitation-ac");
2162 
2163 	if (s_type == AD4170_THERMOCOUPLE_SENSOR) {
2164 		if (st->pins_fn[chan->channel2] & AD4170_PIN_VBIAS) {
2165 			reg_val = BIT(chan->channel2);
2166 			ret = regmap_write(st->regmap, AD4170_V_BIAS_REG, reg_val);
2167 			if (ret)
2168 				dev_err_probe(dev, ret, "Failed to set vbias\n");
2169 		}
2170 	}
2171 	if (s_type == AD4170_WEIGH_SCALE_SENSOR)
2172 		ret = ad4170_setup_bridge(st, child, setup, exc_pins, exc_curs,
2173 					  num_exc_pins, ac_excited);
2174 	else
2175 		ret = ad4170_setup_rtd(st, child, setup, exc_pins, exc_curs,
2176 				       num_exc_pins, ac_excited);
2177 
2178 	return ret;
2179 }
2180 
ad4170_parse_reference(struct ad4170_state * st,struct fwnode_handle * child,struct ad4170_setup * setup)2181 static int ad4170_parse_reference(struct ad4170_state *st,
2182 				  struct fwnode_handle *child,
2183 				  struct ad4170_setup *setup)
2184 {
2185 	struct device *dev = &st->spi->dev;
2186 	const char *propname;
2187 	u32 aux;
2188 	int ret;
2189 
2190 	/* Optional positive reference buffering */
2191 	propname = "adi,positive-reference-buffer";
2192 	ret = device_property_match_property_string(dev, propname,
2193 						    ad4170_ref_buf_str,
2194 						    ARRAY_SIZE(ad4170_ref_buf_str));
2195 
2196 	/* Default to full precharge buffer enabled. */
2197 	setup->afe |= FIELD_PREP(AD4170_AFE_REF_BUF_P_MSK,
2198 				 ret >= 0 ? ret : AD4170_REF_BUF_FULL);
2199 
2200 	/* Optional negative reference buffering */
2201 	propname = "adi,negative-reference-buffer";
2202 	ret = device_property_match_property_string(dev, propname,
2203 						    ad4170_ref_buf_str,
2204 						    ARRAY_SIZE(ad4170_ref_buf_str));
2205 
2206 	/* Default to full precharge buffer enabled. */
2207 	setup->afe |= FIELD_PREP(AD4170_AFE_REF_BUF_M_MSK,
2208 				 ret >= 0 ? ret : AD4170_REF_BUF_FULL);
2209 
2210 	/* Optional voltage reference selection */
2211 	propname = "adi,reference-select";
2212 	aux = AD4170_REF_REFOUT; /* Default reference selection. */
2213 	fwnode_property_read_u32(child, propname, &aux);
2214 	if (aux > AD4170_REF_AVDD)
2215 		return dev_err_probe(dev, -EINVAL, "Invalid %s: %u\n",
2216 				     propname, aux);
2217 
2218 	setup->afe |= FIELD_PREP(AD4170_AFE_REF_SELECT_MSK, aux);
2219 
2220 	return 0;
2221 }
2222 
ad4170_parse_adc_channel_type(struct device * dev,struct fwnode_handle * child,struct iio_chan_spec * chan)2223 static int ad4170_parse_adc_channel_type(struct device *dev,
2224 					 struct fwnode_handle *child,
2225 					 struct iio_chan_spec *chan)
2226 {
2227 	const char *propname, *propname2;
2228 	int ret, ret2;
2229 	u32 pins[2];
2230 
2231 	propname = "single-channel";
2232 	propname2 = "diff-channels";
2233 	if (!fwnode_property_present(child, propname) &&
2234 	    !fwnode_property_present(child, propname2))
2235 		return dev_err_probe(dev, -EINVAL,
2236 				     "Channel must define one of %s or %s.\n",
2237 				     propname, propname2);
2238 
2239 	/* Parse differential channel configuration */
2240 	ret = fwnode_property_read_u32_array(child, propname2, pins,
2241 					     ARRAY_SIZE(pins));
2242 	if (!ret) {
2243 		chan->differential = true;
2244 		chan->channel = pins[0];
2245 		chan->channel2 = pins[1];
2246 		return 0;
2247 	}
2248 	/* Failed to parse diff chan so try pseudo-diff chan props */
2249 
2250 	propname2 = "common-mode-channel";
2251 	if (fwnode_property_present(child, propname) &&
2252 	    !fwnode_property_present(child, propname2))
2253 		return dev_err_probe(dev, -EINVAL,
2254 				     "When %s is defined, %s must be defined too\n",
2255 				     propname, propname2);
2256 
2257 	/* Parse pseudo-differential channel configuration */
2258 	ret = fwnode_property_read_u32(child, propname, &pins[0]);
2259 	ret2 = fwnode_property_read_u32(child, propname2, &pins[1]);
2260 
2261 	if (!ret && !ret2) {
2262 		chan->differential = false;
2263 		chan->channel = pins[0];
2264 		chan->channel2 = pins[1];
2265 		return 0;
2266 	}
2267 	return dev_err_probe(dev, -EINVAL,
2268 			     "Failed to parse channel %lu input. %d, %d\n",
2269 			     chan->address, ret, ret2);
2270 }
2271 
ad4170_parse_channel_node(struct iio_dev * indio_dev,struct fwnode_handle * child,unsigned int chan_num)2272 static int ad4170_parse_channel_node(struct iio_dev *indio_dev,
2273 				     struct fwnode_handle *child,
2274 				     unsigned int chan_num)
2275 {
2276 	struct ad4170_state *st = iio_priv(indio_dev);
2277 	unsigned int s_type = AD4170_ADC_SENSOR;
2278 	struct device *dev = &st->spi->dev;
2279 	struct ad4170_chan_info *chan_info;
2280 	struct ad4170_setup *setup;
2281 	struct iio_chan_spec *chan;
2282 	unsigned int ref_select;
2283 	unsigned int ch_reg;
2284 	bool bipolar;
2285 	int ret;
2286 
2287 	ret = fwnode_property_read_u32(child, "reg", &ch_reg);
2288 	if (ret)
2289 		return dev_err_probe(dev, ret, "Failed to read channel reg\n");
2290 
2291 	if (ch_reg >= AD4170_MAX_ADC_CHANNELS)
2292 		return dev_err_probe(dev, -EINVAL,
2293 				     "Channel idx greater than no of channels\n");
2294 
2295 	chan = &st->chans[chan_num];
2296 	*chan = ad4170_channel_template;
2297 
2298 	chan->address = ch_reg;
2299 	chan->scan_index = ch_reg;
2300 	chan_info = &st->chan_infos[chan->address];
2301 
2302 	chan_info->setup_num = AD4170_INVALID_SETUP;
2303 	chan_info->initialized = true;
2304 
2305 	setup = &chan_info->setup;
2306 	ret = ad4170_parse_reference(st, child, setup);
2307 	if (ret)
2308 		return ret;
2309 
2310 	ret = fwnode_property_match_property_string(child, "adi,sensor-type",
2311 						    ad4170_sensor_type,
2312 						    ARRAY_SIZE(ad4170_sensor_type));
2313 
2314 	/* Default to conventional ADC channel if sensor type not present */
2315 	s_type = ret < 0 ? AD4170_ADC_SENSOR : ret;
2316 	switch (s_type) {
2317 	case AD4170_ADC_SENSOR:
2318 		ret = ad4170_parse_adc_channel_type(dev, child, chan);
2319 		if (ret)
2320 			return ret;
2321 
2322 		break;
2323 	case AD4170_WEIGH_SCALE_SENSOR:
2324 	case AD4170_THERMOCOUPLE_SENSOR:
2325 	case AD4170_RTD_SENSOR:
2326 		ret = ad4170_parse_external_sensor(st, child, setup, chan, s_type);
2327 		if (ret)
2328 			return ret;
2329 
2330 		break;
2331 	default:
2332 		return -EINVAL;
2333 	}
2334 
2335 	bipolar = fwnode_property_read_bool(child, "bipolar");
2336 	setup->afe |= FIELD_PREP(AD4170_AFE_BIPOLAR_MSK, bipolar);
2337 	if (bipolar)
2338 		chan->scan_type.sign = 's';
2339 	else
2340 		chan->scan_type.sign = 'u';
2341 
2342 	ret = ad4170_validate_channel(st, chan);
2343 	if (ret)
2344 		return ret;
2345 
2346 	ref_select = FIELD_GET(AD4170_AFE_REF_SELECT_MSK, setup->afe);
2347 	ret = ad4170_get_input_range(st, chan, ch_reg, ref_select);
2348 	if (ret < 0)
2349 		return dev_err_probe(dev, ret, "Invalid input config\n");
2350 
2351 	chan_info->input_range_uv = ret;
2352 	return 0;
2353 }
2354 
ad4170_parse_channels(struct iio_dev * indio_dev)2355 static int ad4170_parse_channels(struct iio_dev *indio_dev)
2356 {
2357 	struct ad4170_state *st = iio_priv(indio_dev);
2358 	struct device *dev = &st->spi->dev;
2359 	unsigned int num_channels;
2360 	unsigned int chan_num;
2361 	int ret;
2362 
2363 	num_channels = device_get_child_node_count(dev);
2364 
2365 	if (num_channels > AD4170_MAX_ADC_CHANNELS)
2366 		return dev_err_probe(dev, -EINVAL, "Too many channels\n");
2367 
2368 	/* Add one for temperature */
2369 	num_channels = min(num_channels + 1, AD4170_MAX_ADC_CHANNELS);
2370 
2371 	chan_num = 0;
2372 	device_for_each_child_node_scoped(dev, child) {
2373 		ret = ad4170_parse_channel_node(indio_dev, child, chan_num++);
2374 		if (ret)
2375 			return ret;
2376 	}
2377 
2378 	/*
2379 	 * Add internal temperature sensor channel if the maximum number of
2380 	 * channels has not been reached.
2381 	 */
2382 	if (num_channels < AD4170_MAX_ADC_CHANNELS) {
2383 		struct ad4170_setup *setup = &st->chan_infos[chan_num].setup;
2384 
2385 		st->chans[chan_num] = ad4170_temp_channel_template;
2386 		st->chans[chan_num].address = chan_num;
2387 		st->chans[chan_num].scan_index = chan_num;
2388 
2389 		st->chan_infos[chan_num].setup_num = AD4170_INVALID_SETUP;
2390 		st->chan_infos[chan_num].initialized = true;
2391 
2392 		setup->afe |= FIELD_PREP(AD4170_AFE_REF_SELECT_MSK,
2393 					 AD4170_REF_AVDD);
2394 
2395 		ret = ad4170_get_input_range(st, &st->chans[chan_num], chan_num,
2396 					     AD4170_REF_AVDD);
2397 		if (ret < 0)
2398 			return dev_err_probe(dev, ret, "Invalid input config\n");
2399 
2400 		st->chan_infos[chan_num].input_range_uv = ret;
2401 		chan_num++;
2402 	}
2403 
2404 	/* Add timestamp channel */
2405 	struct iio_chan_spec ts_chan = IIO_CHAN_SOFT_TIMESTAMP(chan_num);
2406 
2407 	st->chans[chan_num] = ts_chan;
2408 	num_channels = num_channels + 1;
2409 
2410 	indio_dev->num_channels = num_channels;
2411 	indio_dev->channels = st->chans;
2412 
2413 	return 0;
2414 }
2415 
clk_hw_to_ad4170(struct clk_hw * hw)2416 static struct ad4170_state *clk_hw_to_ad4170(struct clk_hw *hw)
2417 {
2418 	return container_of(hw, struct ad4170_state, int_clk_hw);
2419 }
2420 
ad4170_sel_clk(struct ad4170_state * st,unsigned int clk_sel)2421 static unsigned long ad4170_sel_clk(struct ad4170_state *st,
2422 				    unsigned int clk_sel)
2423 {
2424 	st->clock_ctrl &= ~AD4170_CLOCK_CTRL_CLOCKSEL_MSK;
2425 	st->clock_ctrl |= FIELD_PREP(AD4170_CLOCK_CTRL_CLOCKSEL_MSK, clk_sel);
2426 	return regmap_write(st->regmap, AD4170_CLOCK_CTRL_REG, st->clock_ctrl);
2427 }
2428 
ad4170_clk_recalc_rate(struct clk_hw * hw,unsigned long parent_rate)2429 static unsigned long ad4170_clk_recalc_rate(struct clk_hw *hw,
2430 					    unsigned long parent_rate)
2431 {
2432 	return AD4170_INT_CLOCK_16MHZ;
2433 }
2434 
ad4170_clk_output_is_enabled(struct clk_hw * hw)2435 static int ad4170_clk_output_is_enabled(struct clk_hw *hw)
2436 {
2437 	struct ad4170_state *st = clk_hw_to_ad4170(hw);
2438 	u32 clk_sel;
2439 
2440 	clk_sel = FIELD_GET(AD4170_CLOCK_CTRL_CLOCKSEL_MSK, st->clock_ctrl);
2441 	return clk_sel == AD4170_CLOCK_CTRL_CLOCKSEL_INT_OUT;
2442 }
2443 
ad4170_clk_output_prepare(struct clk_hw * hw)2444 static int ad4170_clk_output_prepare(struct clk_hw *hw)
2445 {
2446 	struct ad4170_state *st = clk_hw_to_ad4170(hw);
2447 
2448 	return ad4170_sel_clk(st, AD4170_CLOCK_CTRL_CLOCKSEL_INT_OUT);
2449 }
2450 
ad4170_clk_output_unprepare(struct clk_hw * hw)2451 static void ad4170_clk_output_unprepare(struct clk_hw *hw)
2452 {
2453 	struct ad4170_state *st = clk_hw_to_ad4170(hw);
2454 
2455 	ad4170_sel_clk(st, AD4170_CLOCK_CTRL_CLOCKSEL_INT);
2456 }
2457 
2458 static const struct clk_ops ad4170_int_clk_ops = {
2459 	.recalc_rate = ad4170_clk_recalc_rate,
2460 	.is_enabled = ad4170_clk_output_is_enabled,
2461 	.prepare = ad4170_clk_output_prepare,
2462 	.unprepare = ad4170_clk_output_unprepare,
2463 };
2464 
ad4170_register_clk_provider(struct iio_dev * indio_dev)2465 static int ad4170_register_clk_provider(struct iio_dev *indio_dev)
2466 {
2467 	struct ad4170_state *st = iio_priv(indio_dev);
2468 	struct device *dev = indio_dev->dev.parent;
2469 	struct clk_init_data init = {};
2470 	int ret;
2471 
2472 	if (device_property_read_string(dev, "clock-output-names", &init.name)) {
2473 		init.name = devm_kasprintf(dev, GFP_KERNEL, "%pfw",
2474 					   dev_fwnode(dev));
2475 		if (!init.name)
2476 			return -ENOMEM;
2477 	}
2478 
2479 	init.ops = &ad4170_int_clk_ops;
2480 
2481 	st->int_clk_hw.init = &init;
2482 	ret = devm_clk_hw_register(dev, &st->int_clk_hw);
2483 	if (ret)
2484 		return ret;
2485 
2486 	return devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get,
2487 					   &st->int_clk_hw);
2488 }
2489 
ad4170_clock_select(struct iio_dev * indio_dev)2490 static int ad4170_clock_select(struct iio_dev *indio_dev)
2491 {
2492 	struct ad4170_state *st = iio_priv(indio_dev);
2493 	struct device *dev = &st->spi->dev;
2494 	struct clk *ext_clk;
2495 	int ret;
2496 
2497 	ext_clk = devm_clk_get_optional_enabled(dev, NULL);
2498 	if (IS_ERR(ext_clk))
2499 		return dev_err_probe(dev, PTR_ERR(ext_clk),
2500 				     "Failed to get external clock\n");
2501 
2502 	if (!ext_clk) {
2503 		/* Use internal clock reference */
2504 		st->mclk_hz = AD4170_INT_CLOCK_16MHZ;
2505 		st->clock_ctrl |= FIELD_PREP(AD4170_CLOCK_CTRL_CLOCKSEL_MSK,
2506 					     AD4170_CLOCK_CTRL_CLOCKSEL_INT_OUT);
2507 
2508 		if (!device_property_present(&st->spi->dev, "#clock-cells"))
2509 			return 0;
2510 
2511 		return ad4170_register_clk_provider(indio_dev);
2512 	}
2513 
2514 	/* Read optional clock-names prop to specify the external clock type */
2515 	ret = device_property_match_property_string(dev, "clock-names",
2516 						    ad4170_clk_sel,
2517 						    ARRAY_SIZE(ad4170_clk_sel));
2518 
2519 	ret = ret < 0 ? 0 : ret; /* Default to external clock if no clock-names */
2520 	st->clock_ctrl |= FIELD_PREP(AD4170_CLOCK_CTRL_CLOCKSEL_MSK,
2521 				     AD4170_CLOCK_CTRL_CLOCKSEL_EXT + ret);
2522 
2523 	st->mclk_hz = clk_get_rate(ext_clk);
2524 	if (st->mclk_hz < AD4170_EXT_CLOCK_MHZ_MIN ||
2525 	    st->mclk_hz > AD4170_EXT_CLOCK_MHZ_MAX) {
2526 		return dev_err_probe(dev, -EINVAL,
2527 				     "Invalid external clock frequency %u\n",
2528 				     st->mclk_hz);
2529 	}
2530 
2531 	return 0;
2532 }
2533 
ad4170_parse_firmware(struct iio_dev * indio_dev)2534 static int ad4170_parse_firmware(struct iio_dev *indio_dev)
2535 {
2536 	unsigned int vbias_pins[AD4170_MAX_ANALOG_PINS];
2537 	struct ad4170_state *st = iio_priv(indio_dev);
2538 	struct device *dev = &st->spi->dev;
2539 	unsigned int num_vbias_pins;
2540 	int reg_data, ret;
2541 	u32 int_pin_sel;
2542 	unsigned int i;
2543 
2544 	ret = ad4170_clock_select(indio_dev);
2545 	if (ret)
2546 		return dev_err_probe(dev, ret, "Failed to setup device clock\n");
2547 
2548 	ret = regmap_write(st->regmap, AD4170_CLOCK_CTRL_REG, st->clock_ctrl);
2549 	if (ret)
2550 		return ret;
2551 
2552 	for (i = 0; i < AD4170_NUM_CURRENT_SRC; i++)
2553 		st->cur_src_pins[i] = AD4170_CURRENT_SRC_DISABLED;
2554 
2555 	/* On power on, device defaults to using SDO pin for data ready signal */
2556 	int_pin_sel = AD4170_INT_PIN_SDO;
2557 	ret = device_property_match_property_string(dev, "interrupt-names",
2558 						    ad4170_int_pin_names,
2559 						    ARRAY_SIZE(ad4170_int_pin_names));
2560 	if (ret >= 0)
2561 		int_pin_sel = ret;
2562 
2563 	reg_data = FIELD_PREP(AD4170_PIN_MUXING_DIG_AUX1_CTRL_MSK,
2564 			      int_pin_sel == AD4170_INT_PIN_DIG_AUX1 ?
2565 			      AD4170_PIN_MUXING_DIG_AUX1_RDY :
2566 			      AD4170_PIN_MUXING_DIG_AUX1_DISABLED);
2567 
2568 	ret = regmap_update_bits(st->regmap, AD4170_PIN_MUXING_REG,
2569 				 AD4170_PIN_MUXING_DIG_AUX1_CTRL_MSK, reg_data);
2570 	if (ret)
2571 		return ret;
2572 
2573 	ret = device_property_count_u32(dev, "adi,vbias-pins");
2574 	if (ret > 0) {
2575 		if (ret > AD4170_MAX_ANALOG_PINS)
2576 			return dev_err_probe(dev, -EINVAL,
2577 					     "Too many vbias pins %u\n", ret);
2578 
2579 		num_vbias_pins = ret;
2580 
2581 		ret = device_property_read_u32_array(dev, "adi,vbias-pins",
2582 						     vbias_pins,
2583 						     num_vbias_pins);
2584 		if (ret)
2585 			return dev_err_probe(dev, ret,
2586 					     "Failed to read vbias pins\n");
2587 
2588 		for (i = 0; i < num_vbias_pins; i++)
2589 			st->pins_fn[vbias_pins[i]] |= AD4170_PIN_VBIAS;
2590 	}
2591 
2592 	ret = ad4170_parse_channels(indio_dev);
2593 	if (ret)
2594 		return ret;
2595 
2596 	/* Only create a GPIO chip if flagged for it */
2597 	if (device_property_read_bool(dev, "gpio-controller")) {
2598 		ret = ad4170_gpio_init(indio_dev);
2599 		if (ret)
2600 			return ret;
2601 	}
2602 
2603 	return 0;
2604 }
2605 
ad4170_initial_config(struct iio_dev * indio_dev)2606 static int ad4170_initial_config(struct iio_dev *indio_dev)
2607 {
2608 	struct ad4170_state *st = iio_priv(indio_dev);
2609 	struct device *dev = &st->spi->dev;
2610 	unsigned int i;
2611 	int ret;
2612 
2613 	ad4170_fill_sps_tbl(st);
2614 
2615 	ret = regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
2616 				 AD4170_ADC_CTRL_MODE_MSK,
2617 				 FIELD_PREP(AD4170_ADC_CTRL_MODE_MSK,
2618 					    AD4170_ADC_CTRL_MODE_IDLE));
2619 	if (ret)
2620 		return dev_err_probe(dev, ret,
2621 				     "Failed to set ADC mode to idle\n");
2622 
2623 	for (i = 0; i < indio_dev->num_channels; i++) {
2624 		struct ad4170_chan_info *chan_info;
2625 		struct iio_chan_spec const *chan;
2626 		struct ad4170_setup *setup;
2627 		unsigned int val;
2628 
2629 		chan = &indio_dev->channels[i];
2630 		if (chan->type == IIO_TIMESTAMP)
2631 			continue;
2632 
2633 		chan_info = &st->chan_infos[chan->address];
2634 
2635 		setup = &chan_info->setup;
2636 		setup->gain = AD4170_GAIN_REG_DEFAULT;
2637 		ret = ad4170_write_channel_setup(st, chan->address, false);
2638 		if (ret)
2639 			return dev_err_probe(dev, ret,
2640 					     "Failed to write channel setup\n");
2641 
2642 		val = FIELD_PREP(AD4170_CHAN_MAP_AINP_MSK, chan->channel) |
2643 		      FIELD_PREP(AD4170_CHAN_MAP_AINM_MSK, chan->channel2);
2644 
2645 		ret = regmap_write(st->regmap, AD4170_CHAN_MAP_REG(i), val);
2646 		if (ret)
2647 			return dev_err_probe(dev, ret,
2648 					     "Failed to write CHAN_MAP_REG\n");
2649 
2650 		ret = ad4170_set_channel_freq(st, chan,
2651 					      AD4170_DEFAULT_SAMP_RATE, 0);
2652 		if (ret)
2653 			return dev_err_probe(dev, ret,
2654 					     "Failed to set channel freq\n");
2655 
2656 		ret = ad4170_fill_scale_tbl(indio_dev, chan);
2657 		if (ret)
2658 			return dev_err_probe(dev, ret,
2659 					     "Failed to fill scale tbl\n");
2660 	}
2661 
2662 	/* Disable all channels to avoid reading from unexpected channel */
2663 	ret = regmap_write(st->regmap, AD4170_CHAN_EN_REG, 0);
2664 	if (ret)
2665 		return dev_err_probe(dev, ret,
2666 				     "Failed to disable channels\n");
2667 
2668 	/*
2669 	 * Configure channels to share the same data output register, i.e. data
2670 	 * can be read from the same register address regardless of channel
2671 	 * number.
2672 	 */
2673 	return regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
2674 				 AD4170_ADC_CTRL_MULTI_DATA_REG_SEL_MSK,
2675 				 AD4170_ADC_CTRL_MULTI_DATA_REG_SEL_MSK);
2676 }
2677 
ad4170_prepare_spi_message(struct ad4170_state * st)2678 static int ad4170_prepare_spi_message(struct ad4170_state *st)
2679 {
2680 	/*
2681 	 * Continuous data register read is enabled on buffer postenable so
2682 	 * no instruction phase is needed meaning we don't need to send the
2683 	 * register address to read data. Transfer only needs the read buffer.
2684 	 */
2685 	st->xfer.rx_buf = &st->rx_buf;
2686 	st->xfer.len = BITS_TO_BYTES(ad4170_channel_template.scan_type.realbits);
2687 
2688 	spi_message_init_with_transfers(&st->msg, &st->xfer, 1);
2689 
2690 	return devm_spi_optimize_message(&st->spi->dev, st->spi, &st->msg);
2691 }
2692 
ad4170_buffer_postenable(struct iio_dev * indio_dev)2693 static int ad4170_buffer_postenable(struct iio_dev *indio_dev)
2694 {
2695 	struct ad4170_state *st = iio_priv(indio_dev);
2696 	int ret;
2697 
2698 	ret = regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
2699 				 AD4170_ADC_CTRL_MODE_MSK,
2700 				 FIELD_PREP(AD4170_ADC_CTRL_MODE_MSK,
2701 					    AD4170_ADC_CTRL_MODE_CONT));
2702 	if (ret)
2703 		return ret;
2704 
2705 	/*
2706 	 * This enables continuous read of the ADC data register. The ADC must
2707 	 * be in continuous conversion mode.
2708 	 */
2709 	return regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
2710 				  AD4170_ADC_CTRL_CONT_READ_MSK,
2711 				  FIELD_PREP(AD4170_ADC_CTRL_CONT_READ_MSK,
2712 					     AD4170_ADC_CTRL_CONT_READ_ENABLE));
2713 }
2714 
ad4170_buffer_predisable(struct iio_dev * indio_dev)2715 static int ad4170_buffer_predisable(struct iio_dev *indio_dev)
2716 {
2717 	struct ad4170_state *st = iio_priv(indio_dev);
2718 	unsigned int i;
2719 	int ret;
2720 
2721 	/*
2722 	 * Use a high register address (virtual register) to request a write of
2723 	 * 0xA5 to the ADC during the first 8 SCLKs of the ADC data read cycle,
2724 	 * thus exiting continuous read.
2725 	 */
2726 	ret = regmap_write(st->regmap, AD4170_ADC_CTRL_CONT_READ_EXIT_REG, 0);
2727 	if (ret)
2728 		return ret;
2729 
2730 	ret = regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
2731 				 AD4170_ADC_CTRL_CONT_READ_MSK,
2732 				 FIELD_PREP(AD4170_ADC_CTRL_CONT_READ_MSK,
2733 					    AD4170_ADC_CTRL_CONT_READ_DISABLE));
2734 	if (ret)
2735 		return ret;
2736 
2737 	ret = regmap_update_bits(st->regmap, AD4170_ADC_CTRL_REG,
2738 				 AD4170_ADC_CTRL_MODE_MSK,
2739 				 FIELD_PREP(AD4170_ADC_CTRL_MODE_MSK,
2740 					    AD4170_ADC_CTRL_MODE_IDLE));
2741 	if (ret)
2742 		return ret;
2743 
2744 	/*
2745 	 * The ADC sequences through all the enabled channels (see datasheet
2746 	 * page 95). That can lead to incorrect channel being read if a
2747 	 * single-shot read (or buffered read with different active_scan_mask)
2748 	 * is done after buffer disable. Disable all channels so only requested
2749 	 * channels will be read.
2750 	 */
2751 	for (i = 0; i < indio_dev->num_channels; i++) {
2752 		if (indio_dev->channels[i].type == IIO_TIMESTAMP)
2753 			continue;
2754 
2755 		ret = ad4170_set_channel_enable(st, i, false);
2756 		if (ret)
2757 			return ret;
2758 	}
2759 
2760 	return 0;
2761 }
2762 
ad4170_validate_scan_mask(struct iio_dev * indio_dev,const unsigned long * scan_mask)2763 static bool ad4170_validate_scan_mask(struct iio_dev *indio_dev,
2764 				      const unsigned long *scan_mask)
2765 {
2766 	unsigned int masklength = iio_get_masklength(indio_dev);
2767 	unsigned int enabled;
2768 
2769 	/*
2770 	 * The channel sequencer cycles through the enabled channels in
2771 	 * sequential order, from channel 0 to channel 15, bypassing disabled
2772 	 * channels. When more than one channel is enabled, channel 0 must
2773 	 * always be enabled. See datasheet channel_en register description at
2774 	 * page 95.
2775 	 */
2776 	enabled = bitmap_weight(scan_mask, masklength);
2777 	if (enabled > 1)
2778 		return test_bit(0, scan_mask);
2779 
2780 	return enabled == 1;
2781 }
2782 
2783 static const struct iio_buffer_setup_ops ad4170_buffer_ops = {
2784 	.postenable = ad4170_buffer_postenable,
2785 	.predisable = ad4170_buffer_predisable,
2786 	.validate_scan_mask = ad4170_validate_scan_mask,
2787 };
2788 
ad4170_trigger_handler(int irq,void * p)2789 static irqreturn_t ad4170_trigger_handler(int irq, void *p)
2790 {
2791 	struct iio_poll_func *pf = p;
2792 	struct iio_dev *indio_dev = pf->indio_dev;
2793 	struct ad4170_state *st = iio_priv(indio_dev);
2794 	unsigned int chan_index;
2795 	unsigned int i = 0;
2796 	int ret;
2797 
2798 	iio_for_each_active_channel(indio_dev, chan_index) {
2799 		ret = spi_sync(st->spi, &st->msg);
2800 		if (ret)
2801 			goto err_out;
2802 
2803 		memcpy(&st->bounce_buffer[i++], st->rx_buf, ARRAY_SIZE(st->rx_buf));
2804 	}
2805 
2806 	iio_push_to_buffers_with_ts(indio_dev, st->bounce_buffer,
2807 				    sizeof(st->bounce_buffer),
2808 				    iio_get_time_ns(indio_dev));
2809 err_out:
2810 	iio_trigger_notify_done(indio_dev->trig);
2811 	return IRQ_HANDLED;
2812 }
2813 
2814 static const struct iio_trigger_ops ad4170_trigger_ops = {
2815 	.validate_device = iio_trigger_validate_own_device,
2816 };
2817 
ad4170_irq_handler(int irq,void * dev_id)2818 static irqreturn_t ad4170_irq_handler(int irq, void *dev_id)
2819 {
2820 	struct iio_dev *indio_dev = dev_id;
2821 	struct ad4170_state *st = iio_priv(indio_dev);
2822 
2823 	if (iio_buffer_enabled(indio_dev))
2824 		iio_trigger_poll(st->trig);
2825 	else
2826 		complete(&st->completion);
2827 
2828 	return IRQ_HANDLED;
2829 };
2830 
ad4170_trigger_setup(struct iio_dev * indio_dev)2831 static int ad4170_trigger_setup(struct iio_dev *indio_dev)
2832 {
2833 	struct ad4170_state *st = iio_priv(indio_dev);
2834 	struct device *dev = &st->spi->dev;
2835 	int ret;
2836 
2837 	st->trig = devm_iio_trigger_alloc(dev, "%s-trig%d",
2838 					  indio_dev->name,
2839 					  iio_device_id(indio_dev));
2840 	if (!st->trig)
2841 		return -ENOMEM;
2842 
2843 	st->trig->ops = &ad4170_trigger_ops;
2844 
2845 	iio_trigger_set_drvdata(st->trig, indio_dev);
2846 	ret = devm_iio_trigger_register(dev, st->trig);
2847 	if (ret)
2848 		return dev_err_probe(dev, ret, "Failed to register trigger\n");
2849 
2850 	indio_dev->trig = iio_trigger_get(st->trig);
2851 
2852 	return 0;
2853 }
2854 
ad4170_regulator_setup(struct ad4170_state * st)2855 static int ad4170_regulator_setup(struct ad4170_state *st)
2856 {
2857 	struct device *dev = &st->spi->dev;
2858 	int ret;
2859 
2860 	/* Required regulators */
2861 	ret = devm_regulator_get_enable_read_voltage(dev, "avdd");
2862 	if (ret < 0)
2863 		return dev_err_probe(dev, ret, "Failed to get AVDD voltage.\n");
2864 
2865 	st->vrefs_uv[AD4170_AVDD_SUP] = ret;
2866 
2867 	ret = devm_regulator_get_enable_read_voltage(dev, "iovdd");
2868 	if (ret < 0)
2869 		return dev_err_probe(dev, ret, "Failed to get IOVDD voltage.\n");
2870 
2871 	st->vrefs_uv[AD4170_IOVDD_SUP] = ret;
2872 
2873 	/* Optional regulators */
2874 	ret = devm_regulator_get_enable_read_voltage(dev, "avss");
2875 	if (ret < 0 && ret != -ENODEV)
2876 		return dev_err_probe(dev, ret, "Failed to get AVSS voltage.\n");
2877 
2878 	/*
2879 	 * Assume AVSS at GND (0V) if not provided.
2880 	 * REVISIT: AVSS is never above system ground level (i.e. AVSS is either
2881 	 * GND or a negative voltage). But we currently don't have support for
2882 	 * reading negative voltages with the regulator framework. So, the
2883 	 * current AD4170 support reads a positive value from the regulator,
2884 	 * then inverts sign to make that negative.
2885 	 */
2886 	st->vrefs_uv[AD4170_AVSS_SUP] = ret == -ENODEV ? 0 : -ret;
2887 
2888 	ret = devm_regulator_get_enable_read_voltage(dev, "refin1p");
2889 	if (ret < 0 && ret != -ENODEV)
2890 		return dev_err_probe(dev, ret, "Failed to get REFIN+ voltage.\n");
2891 
2892 	st->vrefs_uv[AD4170_REFIN1P_SUP] = ret;
2893 
2894 	ret = devm_regulator_get_enable_read_voltage(dev, "refin1n");
2895 	if (ret < 0 && ret != -ENODEV)
2896 		return dev_err_probe(dev, ret, "Failed to get REFIN- voltage.\n");
2897 
2898 	/*
2899 	 * Negative supplies are assumed to provide negative voltage.
2900 	 * REVISIT when support for negative regulator voltage read be available
2901 	 * in the regulator framework.
2902 	 */
2903 	st->vrefs_uv[AD4170_REFIN1N_SUP] = ret == -ENODEV ? -ENODEV : -ret;
2904 
2905 	ret = devm_regulator_get_enable_read_voltage(dev, "refin2p");
2906 	if (ret < 0 && ret != -ENODEV)
2907 		return dev_err_probe(dev, ret, "Failed to get REFIN2+ voltage.\n");
2908 
2909 	st->vrefs_uv[AD4170_REFIN2P_SUP] = ret;
2910 
2911 	ret = devm_regulator_get_enable_read_voltage(dev, "refin2n");
2912 	if (ret < 0 && ret != -ENODEV)
2913 		return dev_err_probe(dev, ret, "Failed to get REFIN2- voltage.\n");
2914 
2915 	/*
2916 	 * Negative supplies are assumed to provide negative voltage.
2917 	 * REVISIT when support for negative regulator voltage read be available
2918 	 * in the regulator framework.
2919 	 */
2920 	st->vrefs_uv[AD4170_REFIN2N_SUP] = ret == -ENODEV ? -ENODEV : -ret;
2921 
2922 	return 0;
2923 }
2924 
ad4170_probe(struct spi_device * spi)2925 static int ad4170_probe(struct spi_device *spi)
2926 {
2927 	const struct ad4170_chip_info *chip;
2928 	struct device *dev = &spi->dev;
2929 	struct iio_dev *indio_dev;
2930 	struct ad4170_state *st;
2931 	int ret;
2932 
2933 	indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
2934 	if (!indio_dev)
2935 		return -ENOMEM;
2936 
2937 	st = iio_priv(indio_dev);
2938 	st->spi = spi;
2939 
2940 	ret = devm_mutex_init(dev, &st->lock);
2941 	if (ret)
2942 		return ret;
2943 
2944 	chip = spi_get_device_match_data(spi);
2945 	if (!chip)
2946 		return -EINVAL;
2947 
2948 	indio_dev->name = chip->name;
2949 	indio_dev->info = &ad4170_info;
2950 
2951 	st->regmap = devm_regmap_init(dev, NULL, st, &ad4170_regmap_config);
2952 	if (IS_ERR(st->regmap))
2953 		return dev_err_probe(dev, PTR_ERR(st->regmap),
2954 				     "Failed to initialize regmap\n");
2955 
2956 	ret = ad4170_regulator_setup(st);
2957 	if (ret)
2958 		return ret;
2959 
2960 	ret = ad4170_soft_reset(st);
2961 	if (ret)
2962 		return ret;
2963 
2964 	ret = ad4170_parse_firmware(indio_dev);
2965 	if (ret)
2966 		return dev_err_probe(dev, ret, "Failed to parse firmware\n");
2967 
2968 	ret = ad4170_initial_config(indio_dev);
2969 	if (ret)
2970 		return dev_err_probe(dev, ret, "Failed to setup device\n");
2971 
2972 	init_completion(&st->completion);
2973 
2974 	if (spi->irq) {
2975 		ret = devm_request_irq(dev, spi->irq, &ad4170_irq_handler,
2976 				       IRQF_ONESHOT, indio_dev->name, indio_dev);
2977 		if (ret)
2978 			return ret;
2979 
2980 		ret = ad4170_trigger_setup(indio_dev);
2981 		if (ret)
2982 			return ret;
2983 	}
2984 
2985 	ret = ad4170_prepare_spi_message(st);
2986 	if (ret)
2987 		return dev_err_probe(dev, ret, "Failed to prepare SPI message\n");
2988 
2989 	ret = devm_iio_triggered_buffer_setup(dev, indio_dev, NULL,
2990 					      &ad4170_trigger_handler,
2991 					      &ad4170_buffer_ops);
2992 	if (ret)
2993 		return dev_err_probe(dev, ret, "Failed to setup read buffer\n");
2994 
2995 	return devm_iio_device_register(dev, indio_dev);
2996 }
2997 
2998 static const struct spi_device_id ad4170_id_table[] = {
2999 	{ "ad4170-4", (kernel_ulong_t)&ad4170_chip_info },
3000 	{ "ad4190-4", (kernel_ulong_t)&ad4190_chip_info },
3001 	{ "ad4195-4", (kernel_ulong_t)&ad4195_chip_info },
3002 	{ }
3003 };
3004 MODULE_DEVICE_TABLE(spi, ad4170_id_table);
3005 
3006 static const struct of_device_id ad4170_of_match[] = {
3007 	{ .compatible = "adi,ad4170-4", .data = &ad4170_chip_info },
3008 	{ .compatible = "adi,ad4190-4", .data = &ad4190_chip_info },
3009 	{ .compatible = "adi,ad4195-4", .data = &ad4195_chip_info },
3010 	{ }
3011 };
3012 MODULE_DEVICE_TABLE(of, ad4170_of_match);
3013 
3014 static struct spi_driver ad4170_driver = {
3015 	.driver = {
3016 		.name = "ad4170-4",
3017 		.of_match_table = ad4170_of_match,
3018 	},
3019 	.probe = ad4170_probe,
3020 	.id_table = ad4170_id_table,
3021 };
3022 module_spi_driver(ad4170_driver);
3023 
3024 MODULE_AUTHOR("Ana-Maria Cusco <ana-maria.cusco@analog.com>");
3025 MODULE_AUTHOR("Marcelo Schmitt <marcelo.schmitt@analog.com>");
3026 MODULE_DESCRIPTION("Analog Devices AD4170 SPI driver");
3027 MODULE_LICENSE("GPL");
3028