1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * SPI ADC driver for Analog Devices Inc. AD4695 and similar chips
4  *
5  * https://www.analog.com/en/products/ad4695.html
6  * https://www.analog.com/en/products/ad4696.html
7  * https://www.analog.com/en/products/ad4697.html
8  * https://www.analog.com/en/products/ad4698.html
9  *
10  * Copyright 2024 Analog Devices Inc.
11  * Copyright 2024 BayLibre, SAS
12  */
13 
14 #include <linux/align.h>
15 #include <linux/bitfield.h>
16 #include <linux/bits.h>
17 #include <linux/compiler.h>
18 #include <linux/delay.h>
19 #include <linux/device.h>
20 #include <linux/err.h>
21 #include <linux/gpio/consumer.h>
22 #include <linux/iio/buffer-dmaengine.h>
23 #include <linux/iio/buffer.h>
24 #include <linux/iio/iio.h>
25 #include <linux/iio/triggered_buffer.h>
26 #include <linux/iio/trigger_consumer.h>
27 #include <linux/minmax.h>
28 #include <linux/mutex.h>
29 #include <linux/property.h>
30 #include <linux/pwm.h>
31 #include <linux/regmap.h>
32 #include <linux/regulator/consumer.h>
33 #include <linux/spi/offload/consumer.h>
34 #include <linux/spi/offload/provider.h>
35 #include <linux/spi/spi.h>
36 #include <linux/units.h>
37 
38 #include <dt-bindings/iio/adc/adi,ad4695.h>
39 
40 /* AD4695 registers */
41 #define AD4695_REG_SPI_CONFIG_A				0x0000
42 #define   AD4695_REG_SPI_CONFIG_A_SW_RST		  (BIT(7) | BIT(0))
43 #define   AD4695_REG_SPI_CONFIG_A_ADDR_DIR		  BIT(5)
44 #define AD4695_REG_SPI_CONFIG_B				0x0001
45 #define   AD4695_REG_SPI_CONFIG_B_INST_MODE		  BIT(7)
46 #define AD4695_REG_DEVICE_TYPE				0x0003
47 #define AD4695_REG_SCRATCH_PAD				0x000A
48 #define AD4695_REG_VENDOR_L				0x000C
49 #define AD4695_REG_VENDOR_H				0x000D
50 #define AD4695_REG_LOOP_MODE				0x000E
51 #define AD4695_REG_SPI_CONFIG_C				0x0010
52 #define   AD4695_REG_SPI_CONFIG_C_MB_STRICT		  BIT(7)
53 #define AD4695_REG_SPI_STATUS				0x0011
54 #define AD4695_REG_STATUS				0x0014
55 #define AD4695_REG_ALERT_STATUS1			0x0015
56 #define AD4695_REG_ALERT_STATUS2			0x0016
57 #define AD4695_REG_CLAMP_STATUS				0x001A
58 #define AD4695_REG_SETUP				0x0020
59 #define   AD4695_REG_SETUP_LDO_EN			  BIT(4)
60 #define   AD4695_REG_SETUP_SPI_MODE			  BIT(2)
61 #define   AD4695_REG_SETUP_SPI_CYC_CTRL			  BIT(1)
62 #define AD4695_REG_REF_CTRL				0x0021
63 #define   AD4695_REG_REF_CTRL_OV_MODE			  BIT(7)
64 #define   AD4695_REG_REF_CTRL_VREF_SET			  GENMASK(4, 2)
65 #define   AD4695_REG_REF_CTRL_REFHIZ_EN			  BIT(1)
66 #define   AD4695_REG_REF_CTRL_REFBUF_EN			  BIT(0)
67 #define AD4695_REG_SEQ_CTRL				0x0022
68 #define   AD4695_REG_SEQ_CTRL_STD_SEQ_EN		  BIT(7)
69 #define   AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS		  GENMASK(6, 0)
70 #define AD4695_REG_AC_CTRL				0x0023
71 #define AD4695_REG_STD_SEQ_CONFIG			0x0024
72 #define AD4695_REG_GPIO_CTRL				0x0026
73 #define AD4695_REG_GP_MODE				0x0027
74 #define   AD4695_REG_GP_MODE_BUSY_GP_SEL		  BIT(5)
75 #define   AD4695_REG_GP_MODE_BUSY_GP_EN			  BIT(1)
76 #define AD4695_REG_TEMP_CTRL				0x0029
77 #define   AD4695_REG_TEMP_CTRL_TEMP_EN			  BIT(0)
78 #define AD4695_REG_CONFIG_IN(n)				(0x0030 | (n))
79 #define   AD4695_REG_CONFIG_IN_MODE			  BIT(6)
80 #define   AD4695_REG_CONFIG_IN_PAIR			  GENMASK(5, 4)
81 #define   AD4695_REG_CONFIG_IN_AINHIGHZ_EN		  BIT(3)
82 #define   AD4695_REG_CONFIG_IN_OSR_SET			  GENMASK(1, 0)
83 #define AD4695_REG_UPPER_IN(n)				(0x0040 | (2 * (n)))
84 #define AD4695_REG_LOWER_IN(n)				(0x0060 | (2 * (n)))
85 #define AD4695_REG_HYST_IN(n)				(0x0080 | (2 * (n)))
86 #define AD4695_REG_OFFSET_IN(n)				(0x00A0 | (2 * (n)))
87 #define AD4695_REG_GAIN_IN(n)				(0x00C0 | (2 * (n)))
88 #define AD4695_REG_AS_SLOT(n)				(0x0100 | (n))
89 #define   AD4695_REG_AS_SLOT_INX			  GENMASK(3, 0)
90 
91 /* Conversion mode commands */
92 #define AD4695_CMD_EXIT_CNV_MODE	0x0A
93 #define AD4695_CMD_TEMP_CHAN		0x0F
94 #define AD4695_CMD_VOLTAGE_CHAN(n)	(0x10 | (n))
95 
96 /* timing specs */
97 #define AD4695_T_CONVERT_NS		415
98 #define AD4695_T_WAKEUP_HW_MS		3
99 #define AD4695_T_WAKEUP_SW_MS		3
100 #define AD4695_T_REFBUF_MS		100
101 #define AD4695_T_REGCONFIG_NS		20
102 #define AD4695_T_SCK_CNV_DELAY_NS	80
103 #define AD4695_T_CNVL_NS		80
104 #define AD4695_T_CNVH_NS		10
105 #define AD4695_REG_ACCESS_SCLK_HZ	(10 * MEGA)
106 
107 /* Max number of voltage input channels. */
108 #define AD4695_MAX_CHANNELS		16
109 /* Max size of 1 raw sample in bytes. */
110 #define AD4695_MAX_CHANNEL_SIZE		2
111 
112 enum ad4695_in_pair {
113 	AD4695_IN_PAIR_REFGND,
114 	AD4695_IN_PAIR_COM,
115 	AD4695_IN_PAIR_EVEN_ODD,
116 };
117 
118 struct ad4695_chip_info {
119 	const char *name;
120 	int max_sample_rate;
121 	u32 t_acq_ns;
122 	u8 num_voltage_inputs;
123 };
124 
125 struct ad4695_channel_config {
126 	unsigned int channel;
127 	bool highz_en;
128 	bool bipolar;
129 	enum ad4695_in_pair pin_pairing;
130 	unsigned int common_mode_mv;
131 	unsigned int oversampling_ratio;
132 };
133 
134 struct ad4695_state {
135 	struct spi_device *spi;
136 	struct spi_offload *offload;
137 	struct spi_offload_trigger *offload_trigger;
138 	struct regmap *regmap;
139 	struct regmap *regmap16;
140 	struct gpio_desc *reset_gpio;
141 	/* currently PWM CNV only supported with SPI offload use */
142 	struct pwm_device *cnv_pwm;
143 	/* protects against concurrent use of cnv_pwm */
144 	struct mutex cnv_pwm_lock;
145 	/* offload also requires separate gpio to manually control CNV */
146 	struct gpio_desc *cnv_gpio;
147 	/* voltages channels plus temperature and timestamp */
148 	struct iio_chan_spec iio_chan[AD4695_MAX_CHANNELS + 2];
149 	struct ad4695_channel_config channels_cfg[AD4695_MAX_CHANNELS];
150 	const struct ad4695_chip_info *chip_info;
151 	int sample_freq_range[3];
152 	/* Reference voltage. */
153 	unsigned int vref_mv;
154 	/* Common mode input pin voltage. */
155 	unsigned int com_mv;
156 	/*
157 	 * 2 per voltage and temperature chan plus 1 xfer to trigger 1st
158 	 * CNV. Excluding the trigger xfer, every 2nd xfer only serves
159 	 * to control CS and add a delay between the last SCLK and next
160 	 * CNV rising edges.
161 	 */
162 	struct spi_transfer buf_read_xfer[AD4695_MAX_CHANNELS * 2 + 3];
163 	struct spi_message buf_read_msg;
164 	/* Raw conversion data received. */
165 	u8 buf[ALIGN((AD4695_MAX_CHANNELS + 2) * AD4695_MAX_CHANNEL_SIZE,
166 		     sizeof(s64)) + sizeof(s64)] __aligned(IIO_DMA_MINALIGN);
167 	u16 raw_data;
168 	/* Commands to send for single conversion. */
169 	u16 cnv_cmd;
170 	u8 cnv_cmd2;
171 	/* Buffer for storing data from regmap bus reads/writes */
172 	u8 regmap_bus_data[4];
173 };
174 
175 static const struct regmap_range ad4695_regmap_rd_ranges[] = {
176 	regmap_reg_range(AD4695_REG_SPI_CONFIG_A, AD4695_REG_SPI_CONFIG_B),
177 	regmap_reg_range(AD4695_REG_DEVICE_TYPE, AD4695_REG_DEVICE_TYPE),
178 	regmap_reg_range(AD4695_REG_SCRATCH_PAD, AD4695_REG_SCRATCH_PAD),
179 	regmap_reg_range(AD4695_REG_VENDOR_L, AD4695_REG_LOOP_MODE),
180 	regmap_reg_range(AD4695_REG_SPI_CONFIG_C, AD4695_REG_SPI_STATUS),
181 	regmap_reg_range(AD4695_REG_STATUS, AD4695_REG_ALERT_STATUS2),
182 	regmap_reg_range(AD4695_REG_CLAMP_STATUS, AD4695_REG_CLAMP_STATUS),
183 	regmap_reg_range(AD4695_REG_SETUP, AD4695_REG_AC_CTRL),
184 	regmap_reg_range(AD4695_REG_GPIO_CTRL, AD4695_REG_TEMP_CTRL),
185 	regmap_reg_range(AD4695_REG_CONFIG_IN(0), AD4695_REG_CONFIG_IN(15)),
186 	regmap_reg_range(AD4695_REG_AS_SLOT(0), AD4695_REG_AS_SLOT(127)),
187 };
188 
189 static const struct regmap_access_table ad4695_regmap_rd_table = {
190 	.yes_ranges = ad4695_regmap_rd_ranges,
191 	.n_yes_ranges = ARRAY_SIZE(ad4695_regmap_rd_ranges),
192 };
193 
194 static const struct regmap_range ad4695_regmap_wr_ranges[] = {
195 	regmap_reg_range(AD4695_REG_SPI_CONFIG_A, AD4695_REG_SPI_CONFIG_B),
196 	regmap_reg_range(AD4695_REG_SCRATCH_PAD, AD4695_REG_SCRATCH_PAD),
197 	regmap_reg_range(AD4695_REG_LOOP_MODE, AD4695_REG_LOOP_MODE),
198 	regmap_reg_range(AD4695_REG_SPI_CONFIG_C, AD4695_REG_SPI_STATUS),
199 	regmap_reg_range(AD4695_REG_SETUP, AD4695_REG_AC_CTRL),
200 	regmap_reg_range(AD4695_REG_GPIO_CTRL, AD4695_REG_TEMP_CTRL),
201 	regmap_reg_range(AD4695_REG_CONFIG_IN(0), AD4695_REG_CONFIG_IN(15)),
202 	regmap_reg_range(AD4695_REG_AS_SLOT(0), AD4695_REG_AS_SLOT(127)),
203 };
204 
205 static const struct regmap_access_table ad4695_regmap_wr_table = {
206 	.yes_ranges = ad4695_regmap_wr_ranges,
207 	.n_yes_ranges = ARRAY_SIZE(ad4695_regmap_wr_ranges),
208 };
209 
210 static const struct regmap_config ad4695_regmap_config = {
211 	.name = "ad4695-8",
212 	.reg_bits = 16,
213 	.val_bits = 8,
214 	.max_register = AD4695_REG_AS_SLOT(127),
215 	.rd_table = &ad4695_regmap_rd_table,
216 	.wr_table = &ad4695_regmap_wr_table,
217 };
218 
219 static const struct regmap_range ad4695_regmap16_rd_ranges[] = {
220 	regmap_reg_range(AD4695_REG_STD_SEQ_CONFIG, AD4695_REG_STD_SEQ_CONFIG),
221 	regmap_reg_range(AD4695_REG_UPPER_IN(0), AD4695_REG_GAIN_IN(15)),
222 };
223 
224 static const struct regmap_access_table ad4695_regmap16_rd_table = {
225 	.yes_ranges = ad4695_regmap16_rd_ranges,
226 	.n_yes_ranges = ARRAY_SIZE(ad4695_regmap16_rd_ranges),
227 };
228 
229 static const struct regmap_range ad4695_regmap16_wr_ranges[] = {
230 	regmap_reg_range(AD4695_REG_STD_SEQ_CONFIG, AD4695_REG_STD_SEQ_CONFIG),
231 	regmap_reg_range(AD4695_REG_UPPER_IN(0), AD4695_REG_GAIN_IN(15)),
232 };
233 
234 static const struct regmap_access_table ad4695_regmap16_wr_table = {
235 	.yes_ranges = ad4695_regmap16_wr_ranges,
236 	.n_yes_ranges = ARRAY_SIZE(ad4695_regmap16_wr_ranges),
237 };
238 
239 static const struct regmap_config ad4695_regmap16_config = {
240 	.name = "ad4695-16",
241 	.reg_bits = 16,
242 	.reg_stride = 2,
243 	.val_bits = 16,
244 	.val_format_endian = REGMAP_ENDIAN_LITTLE,
245 	.max_register = AD4695_REG_GAIN_IN(15),
246 	.rd_table = &ad4695_regmap16_rd_table,
247 	.wr_table = &ad4695_regmap16_wr_table,
248 };
249 
ad4695_regmap_bus_reg_write(void * context,const void * data,size_t count)250 static int ad4695_regmap_bus_reg_write(void *context, const void *data,
251 				       size_t count)
252 {
253 	struct ad4695_state *st = context;
254 	struct spi_transfer xfer = {
255 			.speed_hz = AD4695_REG_ACCESS_SCLK_HZ,
256 			.len = count,
257 			.tx_buf = st->regmap_bus_data,
258 	};
259 
260 	if (count > ARRAY_SIZE(st->regmap_bus_data))
261 		return -EINVAL;
262 
263 	memcpy(st->regmap_bus_data, data, count);
264 
265 	return spi_sync_transfer(st->spi, &xfer, 1);
266 }
267 
ad4695_regmap_bus_reg_read(void * context,const void * reg,size_t reg_size,void * val,size_t val_size)268 static int ad4695_regmap_bus_reg_read(void *context, const void *reg,
269 				      size_t reg_size, void *val,
270 				      size_t val_size)
271 {
272 	struct ad4695_state *st = context;
273 	struct spi_transfer xfers[] = {
274 		{
275 			.speed_hz = AD4695_REG_ACCESS_SCLK_HZ,
276 			.len = reg_size,
277 			.tx_buf = &st->regmap_bus_data[0],
278 		}, {
279 			.speed_hz = AD4695_REG_ACCESS_SCLK_HZ,
280 			.len = val_size,
281 			.rx_buf = &st->regmap_bus_data[2],
282 		},
283 	};
284 	int ret;
285 
286 	if (reg_size > 2)
287 		return -EINVAL;
288 
289 	if (val_size > 2)
290 		return -EINVAL;
291 
292 	memcpy(&st->regmap_bus_data[0], reg, reg_size);
293 
294 	ret = spi_sync_transfer(st->spi, xfers, ARRAY_SIZE(xfers));
295 	if (ret)
296 		return ret;
297 
298 	memcpy(val, &st->regmap_bus_data[2], val_size);
299 
300 	return 0;
301 }
302 
303 static const struct regmap_bus ad4695_regmap_bus = {
304 	.write = ad4695_regmap_bus_reg_write,
305 	.read = ad4695_regmap_bus_reg_read,
306 	.read_flag_mask = 0x80,
307 	.reg_format_endian_default = REGMAP_ENDIAN_BIG,
308 	.val_format_endian_default = REGMAP_ENDIAN_BIG,
309 };
310 
311 enum {
312 	AD4695_SCAN_TYPE_OSR_1,
313 	AD4695_SCAN_TYPE_OSR_4,
314 	AD4695_SCAN_TYPE_OSR_16,
315 	AD4695_SCAN_TYPE_OSR_64,
316 };
317 
318 static const struct iio_scan_type ad4695_scan_type_offload_u[] = {
319 	[AD4695_SCAN_TYPE_OSR_1] = {
320 		.sign = 'u',
321 		.realbits = 16,
322 		.shift = 3,
323 		.storagebits = 32,
324 	},
325 	[AD4695_SCAN_TYPE_OSR_4] = {
326 		.sign = 'u',
327 		.realbits = 17,
328 		.shift = 2,
329 		.storagebits = 32,
330 	},
331 	[AD4695_SCAN_TYPE_OSR_16] = {
332 		.sign = 'u',
333 		.realbits = 18,
334 		.shift = 1,
335 		.storagebits = 32,
336 	},
337 	[AD4695_SCAN_TYPE_OSR_64] = {
338 		.sign = 'u',
339 		.realbits = 19,
340 		.storagebits = 32,
341 	},
342 };
343 
344 static const struct iio_scan_type ad4695_scan_type_offload_s[] = {
345 	[AD4695_SCAN_TYPE_OSR_1] = {
346 		.sign = 's',
347 		.realbits = 16,
348 		.shift = 3,
349 		.storagebits = 32,
350 	},
351 	[AD4695_SCAN_TYPE_OSR_4] = {
352 		.sign = 's',
353 		.realbits = 17,
354 		.shift = 2,
355 		.storagebits = 32,
356 	},
357 	[AD4695_SCAN_TYPE_OSR_16] = {
358 		.sign = 's',
359 		.realbits = 18,
360 		.shift = 1,
361 		.storagebits = 32,
362 	},
363 	[AD4695_SCAN_TYPE_OSR_64] = {
364 		.sign = 's',
365 		.realbits = 19,
366 		.storagebits = 32,
367 	},
368 };
369 
370 static const struct iio_chan_spec ad4695_channel_template = {
371 	.type = IIO_VOLTAGE,
372 	.indexed = 1,
373 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
374 			      BIT(IIO_CHAN_INFO_SCALE) |
375 			      BIT(IIO_CHAN_INFO_OFFSET) |
376 			      BIT(IIO_CHAN_INFO_CALIBSCALE) |
377 			      BIT(IIO_CHAN_INFO_CALIBBIAS),
378 	.info_mask_separate_available = BIT(IIO_CHAN_INFO_CALIBSCALE) |
379 					BIT(IIO_CHAN_INFO_CALIBBIAS),
380 	.scan_type = {
381 		.sign = 'u',
382 		.realbits = 16,
383 		.storagebits = 16,
384 	},
385 };
386 
387 static const struct iio_chan_spec ad4695_temp_channel_template = {
388 	.address = AD4695_CMD_TEMP_CHAN,
389 	.type = IIO_TEMP,
390 	.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
391 			      BIT(IIO_CHAN_INFO_SCALE) |
392 			      BIT(IIO_CHAN_INFO_OFFSET),
393 	.scan_type = {
394 		.sign = 's',
395 		.realbits = 16,
396 		.storagebits = 16,
397 	},
398 };
399 
400 static const struct iio_chan_spec ad4695_soft_timestamp_channel_template =
401 	IIO_CHAN_SOFT_TIMESTAMP(0);
402 
403 static const char * const ad4695_power_supplies[] = {
404 	"avdd", "vio"
405 };
406 
407 static const int ad4695_oversampling_ratios[] = {
408 	1, 4, 16, 64,
409 };
410 
411 static const struct ad4695_chip_info ad4695_chip_info = {
412 	.name = "ad4695",
413 	.max_sample_rate = 500 * KILO,
414 	.t_acq_ns = 1715,
415 	.num_voltage_inputs = 16,
416 };
417 
418 static const struct ad4695_chip_info ad4696_chip_info = {
419 	.name = "ad4696",
420 	.max_sample_rate = 1 * MEGA,
421 	.t_acq_ns = 715,
422 	.num_voltage_inputs = 16,
423 };
424 
425 static const struct ad4695_chip_info ad4697_chip_info = {
426 	.name = "ad4697",
427 	.max_sample_rate = 500 * KILO,
428 	.t_acq_ns = 1715,
429 	.num_voltage_inputs = 8,
430 };
431 
432 static const struct ad4695_chip_info ad4698_chip_info = {
433 	.name = "ad4698",
434 	.max_sample_rate = 1 * MEGA,
435 	.t_acq_ns = 715,
436 	.num_voltage_inputs = 8,
437 };
438 
ad4695_cnv_manual_trigger(struct ad4695_state * st)439 static void ad4695_cnv_manual_trigger(struct ad4695_state *st)
440 {
441 	gpiod_set_value_cansleep(st->cnv_gpio, 1);
442 	ndelay(10);
443 	gpiod_set_value_cansleep(st->cnv_gpio, 0);
444 }
445 
446 /**
447  * ad4695_set_single_cycle_mode - Set the device in single cycle mode
448  * @st: The AD4695 state
449  * @channel: The first channel to read
450  *
451  * As per the datasheet, to enable single cycle mode, we need to set
452  * STD_SEQ_EN=0, NUM_SLOTS_AS=0 and CYC_CTRL=1 (Table 15). Setting SPI_MODE=1
453  * triggers the first conversion using the channel in AS_SLOT0.
454  *
455  * Context: can sleep, must be called with iio_device_claim_direct held
456  * Return: 0 on success, a negative error code on failure
457  */
ad4695_set_single_cycle_mode(struct ad4695_state * st,unsigned int channel)458 static int ad4695_set_single_cycle_mode(struct ad4695_state *st,
459 					unsigned int channel)
460 {
461 	int ret;
462 
463 	ret = regmap_clear_bits(st->regmap, AD4695_REG_SEQ_CTRL,
464 				AD4695_REG_SEQ_CTRL_STD_SEQ_EN |
465 				AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS);
466 	if (ret)
467 		return ret;
468 
469 	ret = regmap_write(st->regmap, AD4695_REG_AS_SLOT(0),
470 			   FIELD_PREP(AD4695_REG_AS_SLOT_INX, channel));
471 	if (ret)
472 		return ret;
473 
474 	return regmap_set_bits(st->regmap, AD4695_REG_SETUP,
475 			       AD4695_REG_SETUP_SPI_MODE |
476 			       AD4695_REG_SETUP_SPI_CYC_CTRL);
477 }
478 
479 /**
480  * ad4695_enter_advanced_sequencer_mode - Put the ADC in advanced sequencer mode
481  * @st: The driver state
482  * @n: The number of slots to use - must be >= 2, <= 128
483  *
484  * As per the datasheet, to enable advanced sequencer, we need to set
485  * STD_SEQ_EN=0, NUM_SLOTS_AS=n-1 and CYC_CTRL=0 (Table 15). Setting SPI_MODE=1
486  * triggers the first conversion using the channel in AS_SLOT0.
487  *
488  * Return: 0 on success, a negative error code on failure
489  */
ad4695_enter_advanced_sequencer_mode(struct ad4695_state * st,u32 n)490 static int ad4695_enter_advanced_sequencer_mode(struct ad4695_state *st, u32 n)
491 {
492 	int ret;
493 
494 	ret = regmap_update_bits(st->regmap, AD4695_REG_SEQ_CTRL,
495 		AD4695_REG_SEQ_CTRL_STD_SEQ_EN |
496 		AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS,
497 		FIELD_PREP(AD4695_REG_SEQ_CTRL_STD_SEQ_EN, 0) |
498 		FIELD_PREP(AD4695_REG_SEQ_CTRL_NUM_SLOTS_AS, n - 1));
499 	if (ret)
500 		return ret;
501 
502 	return regmap_update_bits(st->regmap, AD4695_REG_SETUP,
503 		AD4695_REG_SETUP_SPI_MODE | AD4695_REG_SETUP_SPI_CYC_CTRL,
504 		FIELD_PREP(AD4695_REG_SETUP_SPI_MODE, 1) |
505 		FIELD_PREP(AD4695_REG_SETUP_SPI_CYC_CTRL, 0));
506 }
507 
508 /**
509  * ad4695_exit_conversion_mode - Exit conversion mode
510  * @st: The AD4695 state
511  *
512  * Sends SPI command to exit conversion mode.
513  *
514  * Return: 0 on success, a negative error code on failure
515  */
ad4695_exit_conversion_mode(struct ad4695_state * st)516 static int ad4695_exit_conversion_mode(struct ad4695_state *st)
517 {
518 	/*
519 	 * An extra transfer is needed to trigger a conversion here so
520 	 * that we can be 100% sure the command will be processed by the
521 	 * ADC, rather than relying on it to be in the correct state
522 	 * when this function is called (this chip has a quirk where the
523 	 * command only works when reading a conversion, and if the
524 	 * previous conversion was already read then it won't work). The
525 	 * actual conversion command is then run at the slower
526 	 * AD4695_REG_ACCESS_SCLK_HZ speed to guarantee this works.
527 	 */
528 	struct spi_transfer xfers[] = {
529 		{
530 			.delay.value = AD4695_T_CNVL_NS,
531 			.delay.unit = SPI_DELAY_UNIT_NSECS,
532 			.cs_change = 1,
533 			.cs_change_delay.value = AD4695_T_CNVH_NS,
534 			.cs_change_delay.unit = SPI_DELAY_UNIT_NSECS,
535 		},
536 		{
537 			.speed_hz = AD4695_REG_ACCESS_SCLK_HZ,
538 			.tx_buf = &st->cnv_cmd2,
539 			.len = 1,
540 			.delay.value = AD4695_T_REGCONFIG_NS,
541 			.delay.unit = SPI_DELAY_UNIT_NSECS,
542 		},
543 	};
544 
545 	/*
546 	 * Technically, could do a 5-bit transfer, but shifting to start of
547 	 * 8 bits instead for better SPI controller support.
548 	 */
549 	st->cnv_cmd2 = AD4695_CMD_EXIT_CNV_MODE << 3;
550 
551 	if (st->cnv_gpio) {
552 		ad4695_cnv_manual_trigger(st);
553 
554 		/*
555 		 * In this case, CNV is not connected to CS, so we don't need
556 		 * the extra CS toggle to trigger the conversion and toggling
557 		 * CS would have no effect.
558 		 */
559 		return spi_sync_transfer(st->spi, &xfers[1], 1);
560 	}
561 
562 	return spi_sync_transfer(st->spi, xfers, ARRAY_SIZE(xfers));
563 }
564 
ad4695_set_ref_voltage(struct ad4695_state * st,int vref_mv)565 static int ad4695_set_ref_voltage(struct ad4695_state *st, int vref_mv)
566 {
567 	u8 val;
568 
569 	if (vref_mv >= 2400 && vref_mv <= 2750)
570 		val = 0;
571 	else if (vref_mv > 2750 && vref_mv <= 3250)
572 		val = 1;
573 	else if (vref_mv > 3250 && vref_mv <= 3750)
574 		val = 2;
575 	else if (vref_mv > 3750 && vref_mv <= 4500)
576 		val = 3;
577 	else if (vref_mv > 4500 && vref_mv <= 5100)
578 		val = 4;
579 	else
580 		return -EINVAL;
581 
582 	return regmap_update_bits(st->regmap, AD4695_REG_REF_CTRL,
583 				  AD4695_REG_REF_CTRL_VREF_SET,
584 				  FIELD_PREP(AD4695_REG_REF_CTRL_VREF_SET, val));
585 }
586 
587 /**
588  * ad4695_osr_to_regval - convert ratio to OSR register value
589  * @ratio: ratio to check
590  *
591  * Check if ratio is present in the list of available ratios and return
592  * the corresponding value that needs to be written to the register to
593  * select that ratio.
594  *
595  * Returns: register value (0 to 3) or -EINVAL if there is not an exact
596  * match
597  */
ad4695_osr_to_regval(int ratio)598 static int ad4695_osr_to_regval(int ratio)
599 {
600 	int i;
601 
602 	for (i = 0; i < ARRAY_SIZE(ad4695_oversampling_ratios); i++) {
603 		if (ratio == ad4695_oversampling_ratios[i])
604 			return i;
605 	}
606 
607 	return -EINVAL;
608 }
609 
ad4695_write_chn_cfg(struct ad4695_state * st,struct ad4695_channel_config * cfg)610 static int ad4695_write_chn_cfg(struct ad4695_state *st,
611 				struct ad4695_channel_config *cfg)
612 {
613 	u32 mask, val;
614 
615 	mask = AD4695_REG_CONFIG_IN_MODE;
616 	val = FIELD_PREP(AD4695_REG_CONFIG_IN_MODE, cfg->bipolar ? 1 : 0);
617 
618 	mask |= AD4695_REG_CONFIG_IN_PAIR;
619 	val |= FIELD_PREP(AD4695_REG_CONFIG_IN_PAIR, cfg->pin_pairing);
620 
621 	mask |= AD4695_REG_CONFIG_IN_AINHIGHZ_EN;
622 	val |= FIELD_PREP(AD4695_REG_CONFIG_IN_AINHIGHZ_EN,
623 			  cfg->highz_en ? 1 : 0);
624 
625 	return regmap_update_bits(st->regmap,
626 				  AD4695_REG_CONFIG_IN(cfg->channel),
627 				  mask, val);
628 }
629 
ad4695_buffer_preenable(struct iio_dev * indio_dev)630 static int ad4695_buffer_preenable(struct iio_dev *indio_dev)
631 {
632 	struct ad4695_state *st = iio_priv(indio_dev);
633 	struct spi_transfer *xfer;
634 	u8 temp_chan_bit = st->chip_info->num_voltage_inputs;
635 	u32 bit, num_xfer, num_slots;
636 	u32 temp_en = 0;
637 	int ret, rx_buf_offset = 0;
638 
639 	/*
640 	 * We are using the advanced sequencer since it is the only way to read
641 	 * multiple channels that allows individual configuration of each
642 	 * voltage input channel. Slot 0 in the advanced sequencer is used to
643 	 * account for the gap between trigger polls - we don't read data from
644 	 * this slot. Each enabled voltage channel is assigned a slot starting
645 	 * with slot 1.
646 	 */
647 	num_slots = 1;
648 
649 	memset(st->buf_read_xfer, 0, sizeof(st->buf_read_xfer));
650 
651 	/* First xfer is only to trigger conversion of slot 1, so no rx. */
652 	xfer = &st->buf_read_xfer[0];
653 	xfer->cs_change = 1;
654 	xfer->delay.value = st->chip_info->t_acq_ns;
655 	xfer->delay.unit = SPI_DELAY_UNIT_NSECS;
656 	xfer->cs_change_delay.value = AD4695_T_CONVERT_NS;
657 	xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
658 	num_xfer = 1;
659 
660 	iio_for_each_active_channel(indio_dev, bit) {
661 		xfer = &st->buf_read_xfer[num_xfer];
662 		xfer->bits_per_word = 16;
663 		xfer->rx_buf = &st->buf[rx_buf_offset];
664 		xfer->len = 2;
665 		rx_buf_offset += xfer->len;
666 
667 		if (bit == temp_chan_bit) {
668 			temp_en = 1;
669 		} else {
670 			ret = regmap_write(st->regmap,
671 				AD4695_REG_AS_SLOT(num_slots),
672 				FIELD_PREP(AD4695_REG_AS_SLOT_INX, bit));
673 			if (ret)
674 				return ret;
675 
676 			num_slots++;
677 		}
678 
679 		num_xfer++;
680 
681 		/*
682 		 * We need to add a blank xfer in data reads, to meet the timing
683 		 * requirement of a minimum delay between the last SCLK rising
684 		 * edge and the CS deassert.
685 		 */
686 		xfer = &st->buf_read_xfer[num_xfer];
687 		xfer->delay.value = AD4695_T_SCK_CNV_DELAY_NS;
688 		xfer->delay.unit = SPI_DELAY_UNIT_NSECS;
689 		xfer->cs_change = 1;
690 		xfer->cs_change_delay.value = AD4695_T_CONVERT_NS;
691 		xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
692 
693 		num_xfer++;
694 	}
695 
696 	/*
697 	 * The advanced sequencer requires that at least 2 slots are enabled.
698 	 * Since slot 0 is always used for other purposes, we need only 1
699 	 * enabled voltage channel to meet this requirement.  If the temperature
700 	 * channel is the only enabled channel, we need to add one more slot in
701 	 * the sequence but not read from it. This is because the temperature
702 	 * sensor is sampled at the end of the channel sequence in advanced
703 	 * sequencer mode (see datasheet page 38).
704 	 *
705 	 * From the iio_for_each_active_channel() block above, we now have an
706 	 * xfer with data followed by a blank xfer to allow us to meet the
707 	 * timing spec, so move both of those up before adding an extra to
708 	 * handle the temperature-only case.
709 	 */
710 	if (num_slots < 2) {
711 		/* Move last two xfers */
712 		st->buf_read_xfer[num_xfer] = st->buf_read_xfer[num_xfer - 1];
713 		st->buf_read_xfer[num_xfer - 1] = st->buf_read_xfer[num_xfer - 2];
714 		num_xfer++;
715 
716 		/* Modify inserted xfer for extra slot. */
717 		xfer = &st->buf_read_xfer[num_xfer - 3];
718 		memset(xfer, 0, sizeof(*xfer));
719 		xfer->cs_change = 1;
720 		xfer->delay.value = st->chip_info->t_acq_ns;
721 		xfer->delay.unit = SPI_DELAY_UNIT_NSECS;
722 		xfer->cs_change_delay.value = AD4695_T_CONVERT_NS;
723 		xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
724 		xfer++;
725 
726 		/* and add the extra slot in the sequencer */
727 		ret = regmap_write(st->regmap,
728 				   AD4695_REG_AS_SLOT(num_slots),
729 				   FIELD_PREP(AD4695_REG_AS_SLOT_INX, 0));
730 		if (ret)
731 			return ret;
732 
733 		num_slots++;
734 
735 		/*
736 		 * We still want to point at the last xfer when finished, so
737 		 * update the pointer.
738 		 */
739 		xfer = &st->buf_read_xfer[num_xfer - 1];
740 	}
741 
742 	/*
743 	 * Don't keep CS asserted after last xfer. Also triggers conversion of
744 	 * slot 0.
745 	 */
746 	xfer->cs_change = 0;
747 
748 	/*
749 	 * Temperature channel isn't included in the sequence, but rather
750 	 * controlled by setting a bit in the TEMP_CTRL register.
751 	 */
752 
753 	ret = regmap_update_bits(st->regmap, AD4695_REG_TEMP_CTRL,
754 		AD4695_REG_TEMP_CTRL_TEMP_EN,
755 		FIELD_PREP(AD4695_REG_TEMP_CTRL_TEMP_EN, temp_en));
756 	if (ret)
757 		return ret;
758 
759 	spi_message_init_with_transfers(&st->buf_read_msg, st->buf_read_xfer,
760 					num_xfer);
761 
762 	ret = spi_optimize_message(st->spi, &st->buf_read_msg);
763 	if (ret)
764 		return ret;
765 
766 	/* This triggers conversion of slot 0. */
767 	ret = ad4695_enter_advanced_sequencer_mode(st, num_slots);
768 	if (ret)
769 		spi_unoptimize_message(&st->buf_read_msg);
770 
771 	return ret;
772 }
773 
ad4695_buffer_postdisable(struct iio_dev * indio_dev)774 static int ad4695_buffer_postdisable(struct iio_dev *indio_dev)
775 {
776 	struct ad4695_state *st = iio_priv(indio_dev);
777 	int ret;
778 
779 	ret = ad4695_exit_conversion_mode(st);
780 	if (ret)
781 		return ret;
782 
783 	spi_unoptimize_message(&st->buf_read_msg);
784 
785 	return 0;
786 }
787 
788 static const struct iio_buffer_setup_ops ad4695_buffer_setup_ops = {
789 	.preenable = ad4695_buffer_preenable,
790 	.postdisable = ad4695_buffer_postdisable,
791 };
792 
ad4695_trigger_handler(int irq,void * p)793 static irqreturn_t ad4695_trigger_handler(int irq, void *p)
794 {
795 	struct iio_poll_func *pf = p;
796 	struct iio_dev *indio_dev = pf->indio_dev;
797 	struct ad4695_state *st = iio_priv(indio_dev);
798 	int ret;
799 
800 	ret = spi_sync(st->spi, &st->buf_read_msg);
801 	if (ret)
802 		goto out;
803 
804 	iio_push_to_buffers_with_timestamp(indio_dev, st->buf, pf->timestamp);
805 
806 out:
807 	iio_trigger_notify_done(indio_dev->trig);
808 
809 	return IRQ_HANDLED;
810 }
811 
ad4695_offload_buffer_postenable(struct iio_dev * indio_dev)812 static int ad4695_offload_buffer_postenable(struct iio_dev *indio_dev)
813 {
814 	struct ad4695_state *st = iio_priv(indio_dev);
815 	struct spi_offload_trigger_config config = {
816 		.type = SPI_OFFLOAD_TRIGGER_DATA_READY,
817 	};
818 	struct spi_transfer *xfer = &st->buf_read_xfer[0];
819 	struct pwm_state state;
820 	u8 temp_chan_bit = st->chip_info->num_voltage_inputs;
821 	u8 num_slots = 0;
822 	u8 temp_en = 0;
823 	unsigned int bit;
824 	int ret;
825 
826 	iio_for_each_active_channel(indio_dev, bit) {
827 		if (bit == temp_chan_bit) {
828 			temp_en = 1;
829 			continue;
830 		}
831 
832 		ret = regmap_write(st->regmap, AD4695_REG_AS_SLOT(num_slots),
833 				   FIELD_PREP(AD4695_REG_AS_SLOT_INX, bit));
834 		if (ret)
835 			return ret;
836 
837 		num_slots++;
838 	}
839 
840 	/*
841 	 * For non-offload, we could discard data to work around this
842 	 * restriction, but with offload, that is not possible.
843 	 */
844 	if (num_slots < 2) {
845 		dev_err(&st->spi->dev,
846 			"At least two voltage channels must be enabled.\n");
847 		return -EINVAL;
848 	}
849 
850 	ret = regmap_update_bits(st->regmap, AD4695_REG_TEMP_CTRL,
851 				 AD4695_REG_TEMP_CTRL_TEMP_EN,
852 				 FIELD_PREP(AD4695_REG_TEMP_CTRL_TEMP_EN,
853 					    temp_en));
854 	if (ret)
855 		return ret;
856 
857 	/* Each BUSY event means just one sample for one channel is ready. */
858 	memset(xfer, 0, sizeof(*xfer));
859 	xfer->offload_flags = SPI_OFFLOAD_XFER_RX_STREAM;
860 	/* Using 19 bits per word to allow for possible oversampling */
861 	xfer->bits_per_word = 19;
862 	xfer->len = 4;
863 
864 	spi_message_init_with_transfers(&st->buf_read_msg, xfer, 1);
865 	st->buf_read_msg.offload = st->offload;
866 
867 	ret = spi_optimize_message(st->spi, &st->buf_read_msg);
868 	if (ret)
869 		return ret;
870 
871 	/*
872 	 * NB: technically, this is part the SPI offload trigger enable, but it
873 	 * doesn't work to call it from the offload trigger enable callback
874 	 * because it requires accessing the SPI bus. Calling it from the
875 	 * trigger enable callback could cause a deadlock.
876 	 */
877 	ret = regmap_set_bits(st->regmap, AD4695_REG_GP_MODE,
878 			      AD4695_REG_GP_MODE_BUSY_GP_EN);
879 	if (ret)
880 		goto err_unoptimize_message;
881 
882 	ret = spi_offload_trigger_enable(st->offload, st->offload_trigger,
883 					 &config);
884 	if (ret)
885 		goto err_disable_busy_output;
886 
887 	ret = ad4695_enter_advanced_sequencer_mode(st, num_slots);
888 	if (ret)
889 		goto err_offload_trigger_disable;
890 
891 	mutex_lock(&st->cnv_pwm_lock);
892 	pwm_get_state(st->cnv_pwm, &state);
893 	/*
894 	 * PWM subsystem generally rounds down, so requesting 2x minimum high
895 	 * time ensures that we meet the minimum high time in any case.
896 	 */
897 	state.duty_cycle = AD4695_T_CNVH_NS * 2;
898 	ret = pwm_apply_might_sleep(st->cnv_pwm, &state);
899 	mutex_unlock(&st->cnv_pwm_lock);
900 	if (ret)
901 		goto err_offload_exit_conversion_mode;
902 
903 	return 0;
904 
905 err_offload_exit_conversion_mode:
906 	/*
907 	 * We have to unwind in a different order to avoid triggering offload.
908 	 * ad4695_exit_conversion_mode() triggers a conversion, so it has to be
909 	 * done after spi_offload_trigger_disable().
910 	 */
911 	spi_offload_trigger_disable(st->offload, st->offload_trigger);
912 	ad4695_exit_conversion_mode(st);
913 	goto err_disable_busy_output;
914 
915 err_offload_trigger_disable:
916 	spi_offload_trigger_disable(st->offload, st->offload_trigger);
917 
918 err_disable_busy_output:
919 	regmap_clear_bits(st->regmap, AD4695_REG_GP_MODE,
920 			  AD4695_REG_GP_MODE_BUSY_GP_EN);
921 
922 err_unoptimize_message:
923 	spi_unoptimize_message(&st->buf_read_msg);
924 
925 	return ret;
926 }
927 
ad4695_offload_buffer_predisable(struct iio_dev * indio_dev)928 static int ad4695_offload_buffer_predisable(struct iio_dev *indio_dev)
929 {
930 	struct ad4695_state *st = iio_priv(indio_dev);
931 	struct pwm_state state;
932 	int ret;
933 
934 	scoped_guard(mutex, &st->cnv_pwm_lock) {
935 		pwm_get_state(st->cnv_pwm, &state);
936 		state.duty_cycle = 0;
937 		ret = pwm_apply_might_sleep(st->cnv_pwm, &state);
938 		if (ret)
939 			return ret;
940 	}
941 
942 	spi_offload_trigger_disable(st->offload, st->offload_trigger);
943 
944 	/*
945 	 * ad4695_exit_conversion_mode() triggers a conversion, so it has to be
946 	 * done after spi_offload_trigger_disable().
947 	 */
948 	ret = ad4695_exit_conversion_mode(st);
949 	if (ret)
950 		return ret;
951 
952 	ret = regmap_clear_bits(st->regmap, AD4695_REG_GP_MODE,
953 				AD4695_REG_GP_MODE_BUSY_GP_EN);
954 	if (ret)
955 		return ret;
956 
957 	spi_unoptimize_message(&st->buf_read_msg);
958 
959 	return 0;
960 }
961 
962 static const struct iio_buffer_setup_ops ad4695_offload_buffer_setup_ops = {
963 	.postenable = ad4695_offload_buffer_postenable,
964 	.predisable = ad4695_offload_buffer_predisable,
965 };
966 
967 /**
968  * ad4695_read_one_sample - Read a single sample using single-cycle mode
969  * @st: The AD4695 state
970  * @address: The address of the channel to read
971  *
972  * Upon successful return, the sample will be stored in `st->raw_data`.
973  *
974  * Context: can sleep, must be called with iio_device_claim_direct held
975  * Return: 0 on success, a negative error code on failure
976  */
ad4695_read_one_sample(struct ad4695_state * st,unsigned int address)977 static int ad4695_read_one_sample(struct ad4695_state *st, unsigned int address)
978 {
979 	struct spi_transfer xfers[2] = {
980 		{
981 			.speed_hz = AD4695_REG_ACCESS_SCLK_HZ,
982 			.bits_per_word = 16,
983 			.tx_buf = &st->cnv_cmd,
984 			.len = 2,
985 		},
986 		{
987 			/* Required delay between last SCLK and CNV/CS */
988 			.delay.value = AD4695_T_SCK_CNV_DELAY_NS,
989 			.delay.unit = SPI_DELAY_UNIT_NSECS,
990 		}
991 	};
992 	int ret;
993 
994 	ret = ad4695_set_single_cycle_mode(st, address);
995 	if (ret)
996 		return ret;
997 
998 	/*
999 	 * If CNV is connected to CS, the previous function will have triggered
1000 	 * the conversion, otherwise, we do it manually.
1001 	 */
1002 	if (st->cnv_gpio)
1003 		ad4695_cnv_manual_trigger(st);
1004 
1005 	/*
1006 	 * Setting the first channel to the temperature channel isn't supported
1007 	 * in single-cycle mode, so we have to do an extra conversion to read
1008 	 * the temperature.
1009 	 */
1010 	if (address == AD4695_CMD_TEMP_CHAN) {
1011 		st->cnv_cmd = AD4695_CMD_TEMP_CHAN << 11;
1012 
1013 		ret = spi_sync_transfer(st->spi, xfers, ARRAY_SIZE(xfers));
1014 		if (ret)
1015 			return ret;
1016 
1017 		/*
1018 		 * If CNV is connected to CS, the previous function will have
1019 		 * triggered the conversion, otherwise, we do it manually.
1020 		 */
1021 		if (st->cnv_gpio)
1022 			ad4695_cnv_manual_trigger(st);
1023 	}
1024 
1025 	/* Then read the result and exit conversion mode. */
1026 	st->cnv_cmd = AD4695_CMD_EXIT_CNV_MODE << 11;
1027 	xfers[0].rx_buf = &st->raw_data;
1028 
1029 	return spi_sync_transfer(st->spi, xfers, ARRAY_SIZE(xfers));
1030 }
1031 
__ad4695_read_info_raw(struct ad4695_state * st,struct iio_chan_spec const * chan,int * val)1032 static int __ad4695_read_info_raw(struct ad4695_state *st,
1033 				  struct iio_chan_spec const *chan,
1034 				  int *val)
1035 {
1036 	u8 realbits = chan->scan_type.realbits;
1037 	int ret;
1038 
1039 	ret = ad4695_read_one_sample(st, chan->address);
1040 	if (ret)
1041 		return ret;
1042 
1043 	if (chan->scan_type.sign == 's')
1044 		*val = sign_extend32(st->raw_data, realbits - 1);
1045 	else
1046 		*val = st->raw_data;
1047 
1048 	return IIO_VAL_INT;
1049 }
1050 
ad4695_read_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int * val,int * val2,long mask)1051 static int ad4695_read_raw(struct iio_dev *indio_dev,
1052 			   struct iio_chan_spec const *chan,
1053 			   int *val, int *val2, long mask)
1054 {
1055 	struct ad4695_state *st = iio_priv(indio_dev);
1056 	const struct iio_scan_type *scan_type;
1057 	struct ad4695_channel_config *cfg;
1058 	unsigned int reg_val;
1059 	int ret, tmp;
1060 	u8 realbits;
1061 
1062 	if (chan->type == IIO_VOLTAGE)
1063 		cfg = &st->channels_cfg[chan->scan_index];
1064 
1065 	scan_type = iio_get_current_scan_type(indio_dev, chan);
1066 	if (IS_ERR(scan_type))
1067 		return PTR_ERR(scan_type);
1068 
1069 	realbits = scan_type->realbits;
1070 
1071 	switch (mask) {
1072 	case IIO_CHAN_INFO_RAW:
1073 		if (!iio_device_claim_direct(indio_dev))
1074 			return -EBUSY;
1075 
1076 		ret = __ad4695_read_info_raw(st, chan, val);
1077 		iio_device_release_direct(indio_dev);
1078 		return ret;
1079 	case IIO_CHAN_INFO_SCALE:
1080 		switch (chan->type) {
1081 		case IIO_VOLTAGE:
1082 			*val = st->vref_mv;
1083 			*val2 = realbits;
1084 			return IIO_VAL_FRACTIONAL_LOG2;
1085 		case IIO_TEMP:
1086 			/* T_scale (°C) = raw * V_REF (mV) / (-1.8 mV/°C * 2^16) */
1087 			*val = st->vref_mv * -556;
1088 			*val2 = 16;
1089 			return IIO_VAL_FRACTIONAL_LOG2;
1090 		default:
1091 			return -EINVAL;
1092 		}
1093 	case IIO_CHAN_INFO_OFFSET:
1094 		switch (chan->type) {
1095 		case IIO_VOLTAGE:
1096 			if (cfg->pin_pairing == AD4695_IN_PAIR_COM)
1097 				*val = st->com_mv * (1 << realbits) / st->vref_mv;
1098 			else if (cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD)
1099 				*val = cfg->common_mode_mv * (1 << realbits) / st->vref_mv;
1100 			else
1101 				*val = 0;
1102 
1103 			return IIO_VAL_INT;
1104 		case IIO_TEMP:
1105 			/* T_offset (°C) = -725 mV / (-1.8 mV/°C) */
1106 			/* T_offset (raw) = T_offset (°C) * (-1.8 mV/°C) * 2^16 / V_REF (mV) */
1107 			*val = -47513600;
1108 			*val2 = st->vref_mv;
1109 			return IIO_VAL_FRACTIONAL;
1110 		default:
1111 			return -EINVAL;
1112 		}
1113 	case IIO_CHAN_INFO_CALIBSCALE:
1114 		switch (chan->type) {
1115 		case IIO_VOLTAGE:
1116 			if (!iio_device_claim_direct(indio_dev))
1117 				return -EBUSY;
1118 			ret = regmap_read(st->regmap16,
1119 					  AD4695_REG_GAIN_IN(chan->scan_index),
1120 					  &reg_val);
1121 			iio_device_release_direct(indio_dev);
1122 			if (ret)
1123 				return ret;
1124 			*val = reg_val;
1125 			*val2 = 15;
1126 
1127 			return IIO_VAL_FRACTIONAL_LOG2;
1128 		default:
1129 			return -EINVAL;
1130 		}
1131 	case IIO_CHAN_INFO_CALIBBIAS:
1132 		switch (chan->type)
1133 		case IIO_VOLTAGE: {
1134 			if (!iio_device_claim_direct(indio_dev))
1135 				return -EBUSY;
1136 			ret = regmap_read(st->regmap16,
1137 					  AD4695_REG_OFFSET_IN(chan->scan_index),
1138 					  &reg_val);
1139 			iio_device_release_direct(indio_dev);
1140 			if (ret)
1141 				return ret;
1142 
1143 			tmp = sign_extend32(reg_val, 15);
1144 
1145 			switch (cfg->oversampling_ratio) {
1146 			case 1:
1147 				*val = tmp / 4;
1148 				*val2 = abs(tmp) % 4 * MICRO / 4;
1149 				break;
1150 			case 4:
1151 				*val = tmp / 2;
1152 				*val2 = abs(tmp) % 2 * MICRO / 2;
1153 				break;
1154 			case 16:
1155 				*val = tmp;
1156 				*val2 = 0;
1157 				break;
1158 			case 64:
1159 				*val = tmp * 2;
1160 				*val2 = 0;
1161 				break;
1162 			default:
1163 				return -EINVAL;
1164 			}
1165 
1166 			if (tmp < 0 && *val2) {
1167 				*val *= -1;
1168 				*val2 *= -1;
1169 			}
1170 
1171 			return IIO_VAL_INT_PLUS_MICRO;
1172 		default:
1173 			return -EINVAL;
1174 		}
1175 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1176 		switch (chan->type) {
1177 		case IIO_VOLTAGE:
1178 			*val = cfg->oversampling_ratio;
1179 			return IIO_VAL_INT;
1180 		default:
1181 			return -EINVAL;
1182 		}
1183 	case IIO_CHAN_INFO_SAMP_FREQ: {
1184 		struct pwm_state state;
1185 		unsigned int osr = 1;
1186 
1187 		if (chan->type == IIO_VOLTAGE)
1188 			osr = cfg->oversampling_ratio;
1189 
1190 		ret = pwm_get_state_hw(st->cnv_pwm, &state);
1191 		if (ret)
1192 			return ret;
1193 
1194 		/*
1195 		 * The effective sampling frequency for a channel is the input
1196 		 * frequency divided by the channel's OSR value.
1197 		 */
1198 		*val = DIV_ROUND_UP_ULL(NSEC_PER_SEC, state.period * osr);
1199 
1200 		return IIO_VAL_INT;
1201 	}
1202 	default:
1203 		return -EINVAL;
1204 	}
1205 }
1206 
ad4695_write_raw_get_fmt(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,long mask)1207 static int ad4695_write_raw_get_fmt(struct iio_dev *indio_dev,
1208 				    struct iio_chan_spec const *chan,
1209 				    long mask)
1210 {
1211 	switch (mask) {
1212 	case IIO_CHAN_INFO_SAMP_FREQ:
1213 		return IIO_VAL_INT;
1214 	default:
1215 		return IIO_VAL_INT_PLUS_MICRO;
1216 	}
1217 }
1218 
ad4695_set_osr_val(struct ad4695_state * st,struct iio_chan_spec const * chan,int val)1219 static int ad4695_set_osr_val(struct ad4695_state *st,
1220 			      struct iio_chan_spec const *chan,
1221 			      int val)
1222 {
1223 	int osr = ad4695_osr_to_regval(val);
1224 
1225 	if (osr < 0)
1226 		return osr;
1227 
1228 	switch (chan->type) {
1229 	case IIO_VOLTAGE:
1230 		st->channels_cfg[chan->scan_index].oversampling_ratio = val;
1231 		return regmap_update_bits(st->regmap,
1232 				AD4695_REG_CONFIG_IN(chan->scan_index),
1233 				AD4695_REG_CONFIG_IN_OSR_SET,
1234 				FIELD_PREP(AD4695_REG_CONFIG_IN_OSR_SET, osr));
1235 	default:
1236 		return -EINVAL;
1237 	}
1238 }
1239 
ad4695_get_calibbias(int val,int val2,int osr)1240 static unsigned int ad4695_get_calibbias(int val, int val2, int osr)
1241 {
1242 	int val_calc, scale;
1243 
1244 	switch (osr) {
1245 	case 4:
1246 		scale = 4;
1247 		break;
1248 	case 16:
1249 		scale = 2;
1250 		break;
1251 	case 64:
1252 		scale = 1;
1253 		break;
1254 	default:
1255 		scale = 8;
1256 		break;
1257 	}
1258 
1259 	val = clamp_t(int, val, S32_MIN / 8, S32_MAX / 8);
1260 
1261 	/* val2 range is (-MICRO, MICRO) if val == 0, otherwise [0, MICRO) */
1262 	if (val < 0)
1263 		val_calc = val * scale - val2 * scale / MICRO;
1264 	else if (val2 < 0)
1265 		/* if val2 < 0 then val == 0 */
1266 		val_calc = val2 * scale / (int)MICRO;
1267 	else
1268 		val_calc = val * scale + val2 * scale / MICRO;
1269 
1270 	val_calc /= 2;
1271 
1272 	return clamp_t(int, val_calc, S16_MIN, S16_MAX);
1273 }
1274 
__ad4695_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)1275 static int __ad4695_write_raw(struct iio_dev *indio_dev,
1276 			      struct iio_chan_spec const *chan,
1277 			      int val, int val2, long mask)
1278 {
1279 	struct ad4695_state *st = iio_priv(indio_dev);
1280 	unsigned int reg_val;
1281 	unsigned int osr = 1;
1282 
1283 	if (chan->type == IIO_VOLTAGE)
1284 		osr = st->channels_cfg[chan->scan_index].oversampling_ratio;
1285 
1286 	switch (mask) {
1287 	case IIO_CHAN_INFO_CALIBSCALE:
1288 		switch (chan->type) {
1289 		case IIO_VOLTAGE:
1290 			if (val < 0 || val2 < 0)
1291 				reg_val = 0;
1292 			else if (val > 1)
1293 				reg_val = U16_MAX;
1294 			else
1295 				reg_val = (val * (1 << 16) +
1296 					   mul_u64_u32_div(val2, 1 << 16,
1297 							   MICRO)) / 2;
1298 
1299 			return regmap_write(st->regmap16,
1300 					    AD4695_REG_GAIN_IN(chan->scan_index),
1301 					    reg_val);
1302 		default:
1303 			return -EINVAL;
1304 		}
1305 	case IIO_CHAN_INFO_CALIBBIAS:
1306 		switch (chan->type) {
1307 		case IIO_VOLTAGE:
1308 			reg_val = ad4695_get_calibbias(val, val2, osr);
1309 			return regmap_write(st->regmap16,
1310 					    AD4695_REG_OFFSET_IN(chan->scan_index),
1311 					    reg_val);
1312 		default:
1313 			return -EINVAL;
1314 		}
1315 	case IIO_CHAN_INFO_SAMP_FREQ: {
1316 		struct pwm_state state;
1317 		/*
1318 		 * Limit the maximum acceptable sample rate according to
1319 		 * the channel's oversampling ratio.
1320 		 */
1321 		u64 max_osr_rate = DIV_ROUND_UP_ULL(st->chip_info->max_sample_rate,
1322 						    osr);
1323 
1324 		if (val <= 0 || val > max_osr_rate)
1325 			return -EINVAL;
1326 
1327 		guard(mutex)(&st->cnv_pwm_lock);
1328 		pwm_get_state(st->cnv_pwm, &state);
1329 		/*
1330 		 * The required sample frequency for a given OSR is the
1331 		 * input frequency multiplied by it.
1332 		 */
1333 		state.period = DIV_ROUND_UP_ULL(NSEC_PER_SEC, val * osr);
1334 		return pwm_apply_might_sleep(st->cnv_pwm, &state);
1335 	}
1336 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1337 		return ad4695_set_osr_val(st, chan, val);
1338 	default:
1339 		return -EINVAL;
1340 	}
1341 }
1342 
ad4695_write_raw(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,int val,int val2,long mask)1343 static int ad4695_write_raw(struct iio_dev *indio_dev,
1344 			    struct iio_chan_spec const *chan,
1345 			    int val, int val2, long mask)
1346 {
1347 	int ret;
1348 
1349 	if (!iio_device_claim_direct(indio_dev))
1350 		return -EBUSY;
1351 	ret = __ad4695_write_raw(indio_dev, chan, val, val2, mask);
1352 	iio_device_release_direct(indio_dev);
1353 
1354 	return ret;
1355 }
1356 
ad4695_read_avail(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,const int ** vals,int * type,int * length,long mask)1357 static int ad4695_read_avail(struct iio_dev *indio_dev,
1358 			     struct iio_chan_spec const *chan,
1359 			     const int **vals, int *type, int *length,
1360 			     long mask)
1361 {
1362 	int ret;
1363 	static const int ad4695_calibscale_available[6] = {
1364 		/* Range of 0 (inclusive) to 2 (exclusive) */
1365 		0, 15, 1, 15, U16_MAX, 15
1366 	};
1367 	static const int ad4695_calibbias_available[4][6] = {
1368 		/*
1369 		 * Datasheet says FSR/8 which translates to signed/4. The step
1370 		 * depends on oversampling ratio, so we need four different
1371 		 * ranges to select from.
1372 		 */
1373 		{
1374 			S16_MIN / 4, 0,
1375 			0, MICRO / 4,
1376 			S16_MAX / 4, S16_MAX % 4 * MICRO / 4
1377 		},
1378 		{
1379 			S16_MIN / 2, 0,
1380 			0, MICRO / 2,
1381 			S16_MAX / 2, S16_MAX % 2 * MICRO / 2,
1382 		},
1383 		{
1384 			S16_MIN, 0,
1385 			1, 0,
1386 			S16_MAX, 0,
1387 		},
1388 		{
1389 			S16_MIN * 2, 0,
1390 			2, 0,
1391 			S16_MAX * 2, 0,
1392 		},
1393 	};
1394 	struct ad4695_state *st = iio_priv(indio_dev);
1395 	unsigned int osr = 1;
1396 
1397 	if (chan->type == IIO_VOLTAGE)
1398 		osr = st->channels_cfg[chan->scan_index].oversampling_ratio;
1399 
1400 	switch (mask) {
1401 	case IIO_CHAN_INFO_CALIBSCALE:
1402 		switch (chan->type) {
1403 		case IIO_VOLTAGE:
1404 			*vals = ad4695_calibscale_available;
1405 			*type = IIO_VAL_FRACTIONAL_LOG2;
1406 			return IIO_AVAIL_RANGE;
1407 		default:
1408 			return -EINVAL;
1409 		}
1410 	case IIO_CHAN_INFO_CALIBBIAS:
1411 		switch (chan->type) {
1412 		case IIO_VOLTAGE:
1413 			ret = ad4695_osr_to_regval(osr);
1414 			if (ret < 0)
1415 				return ret;
1416 			/*
1417 			 * Select the appropriate calibbias array based on the
1418 			 * OSR value in the register.
1419 			 */
1420 			*vals = ad4695_calibbias_available[ret];
1421 			*type = IIO_VAL_INT_PLUS_MICRO;
1422 			return IIO_AVAIL_RANGE;
1423 		default:
1424 			return -EINVAL;
1425 		}
1426 	case IIO_CHAN_INFO_SAMP_FREQ:
1427 		/* Max sample rate for the channel depends on OSR */
1428 		st->sample_freq_range[2] =
1429 			DIV_ROUND_UP_ULL(st->chip_info->max_sample_rate, osr);
1430 		*vals = st->sample_freq_range;
1431 		*type = IIO_VAL_INT;
1432 		return IIO_AVAIL_RANGE;
1433 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1434 		switch (chan->type) {
1435 		case IIO_VOLTAGE:
1436 			*vals = ad4695_oversampling_ratios;
1437 			*length = ARRAY_SIZE(ad4695_oversampling_ratios);
1438 			*type = IIO_VAL_INT;
1439 			return IIO_AVAIL_LIST;
1440 		default:
1441 			return -EINVAL;
1442 		}
1443 	default:
1444 		return -EINVAL;
1445 	}
1446 }
1447 
ad4695_debugfs_reg_access(struct iio_dev * indio_dev,unsigned int reg,unsigned int writeval,unsigned int * readval)1448 static int ad4695_debugfs_reg_access(struct iio_dev *indio_dev,
1449 				     unsigned int reg,
1450 				     unsigned int writeval,
1451 				     unsigned int *readval)
1452 {
1453 	struct ad4695_state *st = iio_priv(indio_dev);
1454 	int ret = -EINVAL;
1455 
1456 	if (!iio_device_claim_direct(indio_dev))
1457 		return -EBUSY;
1458 
1459 	if (readval) {
1460 		if (regmap_check_range_table(st->regmap, reg,
1461 					     &ad4695_regmap_rd_table))
1462 			ret = regmap_read(st->regmap, reg, readval);
1463 		if (regmap_check_range_table(st->regmap16, reg,
1464 					     &ad4695_regmap16_rd_table))
1465 			ret = regmap_read(st->regmap16, reg, readval);
1466 	} else {
1467 		if (regmap_check_range_table(st->regmap, reg,
1468 					     &ad4695_regmap_wr_table))
1469 			ret = regmap_write(st->regmap, reg, writeval);
1470 		if (regmap_check_range_table(st->regmap16, reg,
1471 					     &ad4695_regmap16_wr_table))
1472 			ret = regmap_write(st->regmap16, reg, writeval);
1473 	}
1474 	iio_device_release_direct(indio_dev);
1475 
1476 	return ret;
1477 }
1478 
ad4695_get_current_scan_type(const struct iio_dev * indio_dev,const struct iio_chan_spec * chan)1479 static int ad4695_get_current_scan_type(const struct iio_dev *indio_dev,
1480 					const struct iio_chan_spec *chan)
1481 {
1482 	struct ad4695_state *st = iio_priv(indio_dev);
1483 	unsigned int osr = st->channels_cfg[chan->scan_index].oversampling_ratio;
1484 
1485 	switch (osr) {
1486 	case 1:
1487 		return AD4695_SCAN_TYPE_OSR_1;
1488 	case 4:
1489 		return AD4695_SCAN_TYPE_OSR_4;
1490 	case 16:
1491 		return AD4695_SCAN_TYPE_OSR_16;
1492 	case 64:
1493 		return AD4695_SCAN_TYPE_OSR_64;
1494 	default:
1495 		return -EINVAL;
1496 	}
1497 }
1498 
1499 static const struct iio_info ad4695_info = {
1500 	.read_raw = &ad4695_read_raw,
1501 	.write_raw_get_fmt = &ad4695_write_raw_get_fmt,
1502 	.write_raw = &ad4695_write_raw,
1503 	.read_avail = &ad4695_read_avail,
1504 	.debugfs_reg_access = &ad4695_debugfs_reg_access,
1505 };
1506 
1507 static const struct iio_info ad4695_offload_info = {
1508 	.read_raw = &ad4695_read_raw,
1509 	.write_raw_get_fmt = &ad4695_write_raw_get_fmt,
1510 	.write_raw = &ad4695_write_raw,
1511 	.get_current_scan_type = &ad4695_get_current_scan_type,
1512 	.read_avail = &ad4695_read_avail,
1513 	.debugfs_reg_access = &ad4695_debugfs_reg_access,
1514 };
1515 
ad4695_parse_channel_cfg(struct ad4695_state * st)1516 static int ad4695_parse_channel_cfg(struct ad4695_state *st)
1517 {
1518 	struct device *dev = &st->spi->dev;
1519 	struct ad4695_channel_config *chan_cfg;
1520 	struct iio_chan_spec *iio_chan;
1521 	int ret, i;
1522 
1523 	/* populate defaults */
1524 	for (i = 0; i < st->chip_info->num_voltage_inputs; i++) {
1525 		chan_cfg = &st->channels_cfg[i];
1526 		iio_chan = &st->iio_chan[i];
1527 
1528 		chan_cfg->highz_en = true;
1529 		chan_cfg->channel = i;
1530 
1531 		/* This is the default OSR after reset */
1532 		chan_cfg->oversampling_ratio = 1;
1533 
1534 		*iio_chan = ad4695_channel_template;
1535 		iio_chan->channel = i;
1536 		iio_chan->scan_index = i;
1537 		iio_chan->address = AD4695_CMD_VOLTAGE_CHAN(i);
1538 	}
1539 
1540 	/* modify based on firmware description */
1541 	device_for_each_child_node_scoped(dev, child) {
1542 		u32 reg, val;
1543 
1544 		ret = fwnode_property_read_u32(child, "reg", &reg);
1545 		if (ret)
1546 			return dev_err_probe(dev, ret,
1547 				"failed to read reg property (%s)\n",
1548 				fwnode_get_name(child));
1549 
1550 		if (reg >= st->chip_info->num_voltage_inputs)
1551 			return dev_err_probe(dev, -EINVAL,
1552 				"reg out of range (%s)\n",
1553 				fwnode_get_name(child));
1554 
1555 		iio_chan = &st->iio_chan[reg];
1556 		chan_cfg = &st->channels_cfg[reg];
1557 
1558 		chan_cfg->highz_en =
1559 			!fwnode_property_read_bool(child, "adi,no-high-z");
1560 		chan_cfg->bipolar = fwnode_property_read_bool(child, "bipolar");
1561 
1562 		ret = fwnode_property_read_u32(child, "common-mode-channel",
1563 					       &val);
1564 		if (ret && ret != -EINVAL)
1565 			return dev_err_probe(dev, ret,
1566 				"failed to read common-mode-channel (%s)\n",
1567 				fwnode_get_name(child));
1568 
1569 		if (ret == -EINVAL || val == AD4695_COMMON_MODE_REFGND)
1570 			chan_cfg->pin_pairing = AD4695_IN_PAIR_REFGND;
1571 		else if (val == AD4695_COMMON_MODE_COM)
1572 			chan_cfg->pin_pairing = AD4695_IN_PAIR_COM;
1573 		else
1574 			chan_cfg->pin_pairing = AD4695_IN_PAIR_EVEN_ODD;
1575 
1576 		if (chan_cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD &&
1577 		    val % 2 == 0)
1578 			return dev_err_probe(dev, -EINVAL,
1579 				"common-mode-channel must be odd number (%s)\n",
1580 				fwnode_get_name(child));
1581 
1582 		if (chan_cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD &&
1583 		    val != reg + 1)
1584 			return dev_err_probe(dev, -EINVAL,
1585 				"common-mode-channel must be next consecutive channel (%s)\n",
1586 				fwnode_get_name(child));
1587 
1588 		if (chan_cfg->pin_pairing == AD4695_IN_PAIR_EVEN_ODD) {
1589 			char name[5];
1590 
1591 			snprintf(name, sizeof(name), "in%d", reg + 1);
1592 
1593 			ret = devm_regulator_get_enable_read_voltage(dev, name);
1594 			if (ret < 0)
1595 				return dev_err_probe(dev, ret,
1596 					"failed to get %s voltage (%s)\n",
1597 					name, fwnode_get_name(child));
1598 
1599 			chan_cfg->common_mode_mv = ret / 1000;
1600 		}
1601 
1602 		if (chan_cfg->bipolar &&
1603 		    chan_cfg->pin_pairing == AD4695_IN_PAIR_REFGND)
1604 			return dev_err_probe(dev, -EINVAL,
1605 				"bipolar mode is not available for inputs paired with REFGND (%s).\n",
1606 				fwnode_get_name(child));
1607 
1608 		if (chan_cfg->bipolar)
1609 			iio_chan->scan_type.sign = 's';
1610 
1611 		ret = ad4695_write_chn_cfg(st, chan_cfg);
1612 		if (ret)
1613 			return ret;
1614 	}
1615 
1616 	/* Temperature channel must be next scan index after voltage channels. */
1617 	st->iio_chan[i] = ad4695_temp_channel_template;
1618 	st->iio_chan[i].scan_index = i;
1619 	i++;
1620 
1621 	st->iio_chan[i] = ad4695_soft_timestamp_channel_template;
1622 	st->iio_chan[i].scan_index = i;
1623 
1624 	return 0;
1625 }
1626 
ad4695_offload_trigger_match(struct spi_offload_trigger * trigger,enum spi_offload_trigger_type type,u64 * args,u32 nargs)1627 static bool ad4695_offload_trigger_match(struct spi_offload_trigger *trigger,
1628 					 enum spi_offload_trigger_type type,
1629 					 u64 *args, u32 nargs)
1630 {
1631 	if (type != SPI_OFFLOAD_TRIGGER_DATA_READY)
1632 		return false;
1633 
1634 	/*
1635 	 * Requires 2 args:
1636 	 * args[0] is the trigger event.
1637 	 * args[1] is the GPIO pin number.
1638 	 */
1639 	if (nargs != 2 || args[0] != AD4695_TRIGGER_EVENT_BUSY)
1640 		return false;
1641 
1642 	return true;
1643 }
1644 
ad4695_offload_trigger_request(struct spi_offload_trigger * trigger,enum spi_offload_trigger_type type,u64 * args,u32 nargs)1645 static int ad4695_offload_trigger_request(struct spi_offload_trigger *trigger,
1646 					  enum spi_offload_trigger_type type,
1647 					  u64 *args, u32 nargs)
1648 {
1649 	struct ad4695_state *st = spi_offload_trigger_get_priv(trigger);
1650 
1651 	/* Should already be validated by match, but just in case. */
1652 	if (nargs != 2)
1653 		return -EINVAL;
1654 
1655 	/* DT tells us if BUSY event uses GP0 or GP3. */
1656 	if (args[1] == AD4695_TRIGGER_PIN_GP3)
1657 		return regmap_set_bits(st->regmap, AD4695_REG_GP_MODE,
1658 				       AD4695_REG_GP_MODE_BUSY_GP_SEL);
1659 
1660 	return regmap_clear_bits(st->regmap, AD4695_REG_GP_MODE,
1661 				 AD4695_REG_GP_MODE_BUSY_GP_SEL);
1662 }
1663 
1664 static int
ad4695_offload_trigger_validate(struct spi_offload_trigger * trigger,struct spi_offload_trigger_config * config)1665 ad4695_offload_trigger_validate(struct spi_offload_trigger *trigger,
1666 				struct spi_offload_trigger_config *config)
1667 {
1668 	if (config->type != SPI_OFFLOAD_TRIGGER_DATA_READY)
1669 		return -EINVAL;
1670 
1671 	return 0;
1672 }
1673 
1674 /*
1675  * NB: There are no enable/disable callbacks here due to requiring a SPI
1676  * message to enable or disable the BUSY output on the ADC.
1677  */
1678 static const struct spi_offload_trigger_ops ad4695_offload_trigger_ops = {
1679 	.match = ad4695_offload_trigger_match,
1680 	.request = ad4695_offload_trigger_request,
1681 	.validate = ad4695_offload_trigger_validate,
1682 };
1683 
ad4695_pwm_disable(void * pwm)1684 static void ad4695_pwm_disable(void *pwm)
1685 {
1686 	pwm_disable(pwm);
1687 }
1688 
ad4695_probe_spi_offload(struct iio_dev * indio_dev,struct ad4695_state * st)1689 static int ad4695_probe_spi_offload(struct iio_dev *indio_dev,
1690 				    struct ad4695_state *st)
1691 {
1692 	struct device *dev = &st->spi->dev;
1693 	struct spi_offload_trigger_info trigger_info = {
1694 		.fwnode = dev_fwnode(dev),
1695 		.ops = &ad4695_offload_trigger_ops,
1696 		.priv = st,
1697 	};
1698 	struct pwm_state pwm_state;
1699 	struct dma_chan *rx_dma;
1700 	int ret, i;
1701 
1702 	indio_dev->info = &ad4695_offload_info;
1703 	indio_dev->num_channels = st->chip_info->num_voltage_inputs + 1;
1704 	indio_dev->setup_ops = &ad4695_offload_buffer_setup_ops;
1705 
1706 	if (!st->cnv_gpio)
1707 		return dev_err_probe(dev, -ENODEV,
1708 				     "CNV GPIO is required for SPI offload\n");
1709 
1710 	ret = devm_spi_offload_trigger_register(dev, &trigger_info);
1711 	if (ret)
1712 		return dev_err_probe(dev, ret,
1713 				     "failed to register offload trigger\n");
1714 
1715 	st->offload_trigger = devm_spi_offload_trigger_get(dev, st->offload,
1716 		SPI_OFFLOAD_TRIGGER_DATA_READY);
1717 	if (IS_ERR(st->offload_trigger))
1718 		return dev_err_probe(dev, PTR_ERR(st->offload_trigger),
1719 				     "failed to get offload trigger\n");
1720 
1721 	ret = devm_mutex_init(dev, &st->cnv_pwm_lock);
1722 	if (ret)
1723 		return ret;
1724 
1725 	st->cnv_pwm = devm_pwm_get(dev, NULL);
1726 	if (IS_ERR(st->cnv_pwm))
1727 		return dev_err_probe(dev, PTR_ERR(st->cnv_pwm),
1728 				     "failed to get CNV PWM\n");
1729 
1730 	pwm_init_state(st->cnv_pwm, &pwm_state);
1731 
1732 	/* If firmware didn't provide default rate, use 10kHz (arbitrary). */
1733 	if (pwm_state.period == 0)
1734 		pwm_state.period = 100 * MILLI;
1735 
1736 	pwm_state.enabled = true;
1737 
1738 	ret = pwm_apply_might_sleep(st->cnv_pwm, &pwm_state);
1739 	if (ret)
1740 		return dev_err_probe(dev, ret, "failed to apply CNV PWM\n");
1741 
1742 	ret = devm_add_action_or_reset(dev, ad4695_pwm_disable, st->cnv_pwm);
1743 	if (ret)
1744 		return ret;
1745 
1746 	rx_dma = devm_spi_offload_rx_stream_request_dma_chan(dev, st->offload);
1747 	if (IS_ERR(rx_dma))
1748 		return dev_err_probe(dev, PTR_ERR(rx_dma),
1749 				     "failed to get offload RX DMA\n");
1750 
1751 	for (i = 0; i < indio_dev->num_channels; i++) {
1752 		struct iio_chan_spec *chan = &st->iio_chan[i];
1753 		struct ad4695_channel_config *cfg;
1754 
1755 		/*
1756 		 * NB: When using offload support, all channels need to have the
1757 		 * same bits_per_word because they all use the same SPI message
1758 		 * for reading one sample. In order to prevent breaking
1759 		 * userspace in the future when oversampling support is added,
1760 		 * all channels are set read 19 bits with a shift of 3 to mask
1761 		 * out the extra bits even though we currently only support 16
1762 		 * bit samples (oversampling ratio == 1).
1763 		 */
1764 		chan->scan_type.shift = 3;
1765 		chan->scan_type.storagebits = 32;
1766 		/* add sample frequency for PWM CNV trigger */
1767 		chan->info_mask_separate |= BIT(IIO_CHAN_INFO_SAMP_FREQ);
1768 		chan->info_mask_separate_available |= BIT(IIO_CHAN_INFO_SAMP_FREQ);
1769 
1770 		/* Add the oversampling properties only for voltage channels */
1771 		if (chan->type != IIO_VOLTAGE)
1772 			continue;
1773 
1774 		cfg = &st->channels_cfg[i];
1775 
1776 		chan->info_mask_separate |= BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO);
1777 		chan->info_mask_separate_available |=
1778 			BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO);
1779 		chan->has_ext_scan_type = 1;
1780 		if (cfg->bipolar) {
1781 			chan->ext_scan_type = ad4695_scan_type_offload_s;
1782 			chan->num_ext_scan_type =
1783 				ARRAY_SIZE(ad4695_scan_type_offload_s);
1784 		} else {
1785 			chan->ext_scan_type = ad4695_scan_type_offload_u;
1786 			chan->num_ext_scan_type =
1787 				ARRAY_SIZE(ad4695_scan_type_offload_u);
1788 		}
1789 	}
1790 
1791 	return devm_iio_dmaengine_buffer_setup_with_handle(dev, indio_dev,
1792 		rx_dma, IIO_BUFFER_DIRECTION_IN);
1793 }
1794 
1795 static const struct spi_offload_config ad4695_spi_offload_config = {
1796 	.capability_flags = SPI_OFFLOAD_CAP_TRIGGER |
1797 			    SPI_OFFLOAD_CAP_RX_STREAM_DMA,
1798 };
1799 
ad4695_probe(struct spi_device * spi)1800 static int ad4695_probe(struct spi_device *spi)
1801 {
1802 	struct device *dev = &spi->dev;
1803 	struct ad4695_state *st;
1804 	struct iio_dev *indio_dev;
1805 	bool use_internal_ldo_supply;
1806 	bool use_internal_ref_buffer;
1807 	int ret;
1808 
1809 	indio_dev = devm_iio_device_alloc(dev, sizeof(*st));
1810 	if (!indio_dev)
1811 		return -ENOMEM;
1812 
1813 	st = iio_priv(indio_dev);
1814 	st->spi = spi;
1815 
1816 	st->chip_info = spi_get_device_match_data(spi);
1817 	if (!st->chip_info)
1818 		return -EINVAL;
1819 
1820 	st->sample_freq_range[0] = 1; /* min */
1821 	st->sample_freq_range[1] = 1; /* step */
1822 	st->sample_freq_range[2] = st->chip_info->max_sample_rate; /* max */
1823 
1824 	st->regmap = devm_regmap_init(dev, &ad4695_regmap_bus, st,
1825 				      &ad4695_regmap_config);
1826 	if (IS_ERR(st->regmap))
1827 		return dev_err_probe(dev, PTR_ERR(st->regmap),
1828 				     "Failed to initialize regmap\n");
1829 
1830 	st->regmap16 = devm_regmap_init(dev, &ad4695_regmap_bus, st,
1831 					&ad4695_regmap16_config);
1832 	if (IS_ERR(st->regmap16))
1833 		return dev_err_probe(dev, PTR_ERR(st->regmap16),
1834 				     "Failed to initialize regmap16\n");
1835 
1836 	st->cnv_gpio = devm_gpiod_get_optional(dev, "cnv", GPIOD_OUT_LOW);
1837 	if (IS_ERR(st->cnv_gpio))
1838 		return dev_err_probe(dev, PTR_ERR(st->cnv_gpio),
1839 				     "Failed to get CNV GPIO\n");
1840 
1841 	ret = devm_regulator_bulk_get_enable(dev,
1842 					     ARRAY_SIZE(ad4695_power_supplies),
1843 					     ad4695_power_supplies);
1844 	if (ret)
1845 		return dev_err_probe(dev, ret,
1846 				     "Failed to enable power supplies\n");
1847 
1848 	/* If LDO_IN supply is present, then we are using internal LDO. */
1849 	ret = devm_regulator_get_enable_optional(dev, "ldo-in");
1850 	if (ret < 0 && ret != -ENODEV)
1851 		return dev_err_probe(dev, ret,
1852 				     "Failed to enable LDO_IN supply\n");
1853 
1854 	use_internal_ldo_supply = ret == 0;
1855 
1856 	if (!use_internal_ldo_supply) {
1857 		/* Otherwise we need an external VDD supply. */
1858 		ret = devm_regulator_get_enable(dev, "vdd");
1859 		if (ret < 0)
1860 			return dev_err_probe(dev, ret,
1861 					     "Failed to enable VDD supply\n");
1862 	}
1863 
1864 	/* If REFIN supply is given, then we are using internal buffer */
1865 	ret = devm_regulator_get_enable_read_voltage(dev, "refin");
1866 	if (ret < 0 && ret != -ENODEV)
1867 		return dev_err_probe(dev, ret, "Failed to get REFIN voltage\n");
1868 
1869 	if (ret != -ENODEV) {
1870 		st->vref_mv = ret / 1000;
1871 		use_internal_ref_buffer = true;
1872 	} else {
1873 		/* Otherwise, we need an external reference. */
1874 		ret = devm_regulator_get_enable_read_voltage(dev, "ref");
1875 		if (ret < 0)
1876 			return dev_err_probe(dev, ret,
1877 					     "Failed to get REF voltage\n");
1878 
1879 		st->vref_mv = ret / 1000;
1880 		use_internal_ref_buffer = false;
1881 	}
1882 
1883 	ret = devm_regulator_get_enable_read_voltage(dev, "com");
1884 	if (ret < 0 && ret != -ENODEV)
1885 		return dev_err_probe(dev, ret, "Failed to get COM voltage\n");
1886 
1887 	st->com_mv = ret == -ENODEV ? 0 : ret / 1000;
1888 
1889 	/*
1890 	 * Reset the device using hardware reset if available or fall back to
1891 	 * software reset.
1892 	 */
1893 
1894 	st->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH);
1895 	if (IS_ERR(st->reset_gpio))
1896 		return PTR_ERR(st->reset_gpio);
1897 
1898 	if (st->reset_gpio) {
1899 		gpiod_set_value(st->reset_gpio, 0);
1900 		msleep(AD4695_T_WAKEUP_HW_MS);
1901 	} else {
1902 		ret = regmap_write(st->regmap, AD4695_REG_SPI_CONFIG_A,
1903 				   AD4695_REG_SPI_CONFIG_A_SW_RST);
1904 		if (ret)
1905 			return ret;
1906 
1907 		msleep(AD4695_T_WAKEUP_SW_MS);
1908 	}
1909 
1910 	/* Needed for regmap16 to be able to work correctly. */
1911 	ret = regmap_set_bits(st->regmap, AD4695_REG_SPI_CONFIG_A,
1912 			      AD4695_REG_SPI_CONFIG_A_ADDR_DIR);
1913 	if (ret)
1914 		return ret;
1915 
1916 	/* Disable internal LDO if it isn't needed. */
1917 	ret = regmap_update_bits(st->regmap, AD4695_REG_SETUP,
1918 				 AD4695_REG_SETUP_LDO_EN,
1919 				 FIELD_PREP(AD4695_REG_SETUP_LDO_EN,
1920 					    use_internal_ldo_supply ? 1 : 0));
1921 	if (ret)
1922 		return ret;
1923 
1924 	/* configure reference supply */
1925 
1926 	if (device_property_present(dev, "adi,no-ref-current-limit")) {
1927 		ret = regmap_set_bits(st->regmap, AD4695_REG_REF_CTRL,
1928 				      AD4695_REG_REF_CTRL_OV_MODE);
1929 		if (ret)
1930 			return ret;
1931 	}
1932 
1933 	if (device_property_present(dev, "adi,no-ref-high-z")) {
1934 		if (use_internal_ref_buffer)
1935 			return dev_err_probe(dev, -EINVAL,
1936 				"Cannot disable high-Z mode for internal reference buffer\n");
1937 
1938 		ret = regmap_clear_bits(st->regmap, AD4695_REG_REF_CTRL,
1939 					AD4695_REG_REF_CTRL_REFHIZ_EN);
1940 		if (ret)
1941 			return ret;
1942 	}
1943 
1944 	ret = ad4695_set_ref_voltage(st, st->vref_mv);
1945 	if (ret)
1946 		return ret;
1947 
1948 	if (use_internal_ref_buffer) {
1949 		ret = regmap_set_bits(st->regmap, AD4695_REG_REF_CTRL,
1950 				      AD4695_REG_REF_CTRL_REFBUF_EN);
1951 		if (ret)
1952 			return ret;
1953 
1954 		/* Give the capacitor some time to charge up. */
1955 		msleep(AD4695_T_REFBUF_MS);
1956 	}
1957 
1958 	ret = ad4695_parse_channel_cfg(st);
1959 	if (ret)
1960 		return ret;
1961 
1962 	indio_dev->name = st->chip_info->name;
1963 	indio_dev->info = &ad4695_info;
1964 	indio_dev->modes = INDIO_DIRECT_MODE;
1965 	indio_dev->channels = st->iio_chan;
1966 	indio_dev->num_channels = st->chip_info->num_voltage_inputs + 2;
1967 
1968 	st->offload = devm_spi_offload_get(dev, spi, &ad4695_spi_offload_config);
1969 	ret = PTR_ERR_OR_ZERO(st->offload);
1970 	if (ret && ret != -ENODEV)
1971 		return dev_err_probe(dev, ret, "failed to get SPI offload\n");
1972 
1973 	/* If no SPI offload, fall back to low speed usage. */
1974 	if (ret == -ENODEV) {
1975 		/* Driver currently requires CNV pin to be connected to SPI CS */
1976 		if (st->cnv_gpio)
1977 			return dev_err_probe(dev, -EINVAL,
1978 					     "CNV GPIO is not supported\n");
1979 
1980 		indio_dev->num_channels = st->chip_info->num_voltage_inputs + 2;
1981 
1982 		ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
1983 						      iio_pollfunc_store_time,
1984 						      ad4695_trigger_handler,
1985 						      &ad4695_buffer_setup_ops);
1986 		if (ret)
1987 			return ret;
1988 	} else {
1989 		ret = ad4695_probe_spi_offload(indio_dev, st);
1990 		if (ret)
1991 			return ret;
1992 	}
1993 
1994 	return devm_iio_device_register(dev, indio_dev);
1995 }
1996 
1997 static const struct spi_device_id ad4695_spi_id_table[] = {
1998 	{ .name = "ad4695", .driver_data = (kernel_ulong_t)&ad4695_chip_info },
1999 	{ .name = "ad4696", .driver_data = (kernel_ulong_t)&ad4696_chip_info },
2000 	{ .name = "ad4697", .driver_data = (kernel_ulong_t)&ad4697_chip_info },
2001 	{ .name = "ad4698", .driver_data = (kernel_ulong_t)&ad4698_chip_info },
2002 	{ }
2003 };
2004 MODULE_DEVICE_TABLE(spi, ad4695_spi_id_table);
2005 
2006 static const struct of_device_id ad4695_of_match_table[] = {
2007 	{ .compatible = "adi,ad4695", .data = &ad4695_chip_info, },
2008 	{ .compatible = "adi,ad4696", .data = &ad4696_chip_info, },
2009 	{ .compatible = "adi,ad4697", .data = &ad4697_chip_info, },
2010 	{ .compatible = "adi,ad4698", .data = &ad4698_chip_info, },
2011 	{ }
2012 };
2013 MODULE_DEVICE_TABLE(of, ad4695_of_match_table);
2014 
2015 static struct spi_driver ad4695_driver = {
2016 	.driver = {
2017 		.name = "ad4695",
2018 		.of_match_table = ad4695_of_match_table,
2019 	},
2020 	.probe = ad4695_probe,
2021 	.id_table = ad4695_spi_id_table,
2022 };
2023 module_spi_driver(ad4695_driver);
2024 
2025 MODULE_AUTHOR("Ramona Gradinariu <ramona.gradinariu@analog.com>");
2026 MODULE_AUTHOR("David Lechner <dlechner@baylibre.com>");
2027 MODULE_DESCRIPTION("Analog Devices AD4695 ADC driver");
2028 MODULE_LICENSE("GPL");
2029 MODULE_IMPORT_NS("IIO_DMAENGINE_BUFFER");
2030