xref: /linux/drivers/iio/adc/at91-sama5d2_adc.c (revision e3966940559d52aa1800a008dcfeec218dd31f88)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Atmel ADC driver for SAMA5D2 devices and compatible.
4  *
5  * Copyright (C) 2015 Atmel,
6  *               2015 Ludovic Desroches <ludovic.desroches@atmel.com>
7  *		 2021 Microchip Technology, Inc. and its subsidiaries
8  *		 2021 Eugen Hristev <eugen.hristev@microchip.com>
9  */
10 
11 #include <linux/bitops.h>
12 #include <linux/cleanup.h>
13 #include <linux/clk.h>
14 #include <linux/delay.h>
15 #include <linux/dma-mapping.h>
16 #include <linux/dmaengine.h>
17 #include <linux/interrupt.h>
18 #include <linux/io.h>
19 #include <linux/module.h>
20 #include <linux/mod_devicetable.h>
21 #include <linux/platform_device.h>
22 #include <linux/property.h>
23 #include <linux/sched.h>
24 #include <linux/units.h>
25 #include <linux/wait.h>
26 #include <linux/iio/iio.h>
27 #include <linux/iio/sysfs.h>
28 #include <linux/iio/buffer.h>
29 #include <linux/iio/trigger.h>
30 #include <linux/iio/trigger_consumer.h>
31 #include <linux/iio/triggered_buffer.h>
32 #include <linux/nvmem-consumer.h>
33 #include <linux/pinctrl/consumer.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/regulator/consumer.h>
36 
37 #include <dt-bindings/iio/adc/at91-sama5d2_adc.h>
38 
39 struct at91_adc_reg_layout {
40 /* Control Register */
41 	u16				CR;
42 /* Software Reset */
43 #define	AT91_SAMA5D2_CR_SWRST		BIT(0)
44 /* Start Conversion */
45 #define	AT91_SAMA5D2_CR_START		BIT(1)
46 /* Touchscreen Calibration */
47 #define	AT91_SAMA5D2_CR_TSCALIB		BIT(2)
48 /* Comparison Restart */
49 #define	AT91_SAMA5D2_CR_CMPRST		BIT(4)
50 
51 /* Mode Register */
52 	u16				MR;
53 /* Trigger Selection */
54 #define	AT91_SAMA5D2_MR_TRGSEL(v)	((v) << 1)
55 /* ADTRG */
56 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG0	0
57 /* TIOA0 */
58 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG1	1
59 /* TIOA1 */
60 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG2	2
61 /* TIOA2 */
62 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG3	3
63 /* PWM event line 0 */
64 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG4	4
65 /* PWM event line 1 */
66 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG5	5
67 /* TIOA3 */
68 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG6	6
69 /* RTCOUT0 */
70 #define	AT91_SAMA5D2_MR_TRGSEL_TRIG7	7
71 /* Sleep Mode */
72 #define	AT91_SAMA5D2_MR_SLEEP		BIT(5)
73 /* Fast Wake Up */
74 #define	AT91_SAMA5D2_MR_FWUP		BIT(6)
75 /* Prescaler Rate Selection */
76 #define	AT91_SAMA5D2_MR_PRESCAL(v)	((v) << AT91_SAMA5D2_MR_PRESCAL_OFFSET)
77 #define	AT91_SAMA5D2_MR_PRESCAL_OFFSET	8
78 #define	AT91_SAMA5D2_MR_PRESCAL_MAX	0xff
79 #define AT91_SAMA5D2_MR_PRESCAL_MASK	GENMASK(15, 8)
80 /* Startup Time */
81 #define	AT91_SAMA5D2_MR_STARTUP(v)	((v) << 16)
82 #define AT91_SAMA5D2_MR_STARTUP_MASK	GENMASK(19, 16)
83 /* Minimum startup time for temperature sensor */
84 #define AT91_SAMA5D2_MR_STARTUP_TS_MIN	(50)
85 /* Analog Change */
86 #define	AT91_SAMA5D2_MR_ANACH		BIT(23)
87 /* Tracking Time */
88 #define	AT91_SAMA5D2_MR_TRACKTIM(v)	((v) << 24)
89 #define	AT91_SAMA5D2_MR_TRACKTIM_TS	6
90 #define	AT91_SAMA5D2_MR_TRACKTIM_MAX	0xf
91 /* Transfer Time */
92 #define	AT91_SAMA5D2_MR_TRANSFER(v)	((v) << 28)
93 #define	AT91_SAMA5D2_MR_TRANSFER_MAX	0x3
94 /* Use Sequence Enable */
95 #define	AT91_SAMA5D2_MR_USEQ		BIT(31)
96 
97 /* Channel Sequence Register 1 */
98 	u16				SEQR1;
99 /* Channel Sequence Register 2 */
100 	u16				SEQR2;
101 /* Channel Enable Register */
102 	u16				CHER;
103 /* Channel Disable Register */
104 	u16				CHDR;
105 /* Channel Status Register */
106 	u16				CHSR;
107 /* Last Converted Data Register */
108 	u16				LCDR;
109 /* Interrupt Enable Register */
110 	u16				IER;
111 /* Interrupt Enable Register - TS X measurement ready */
112 #define AT91_SAMA5D2_IER_XRDY   BIT(20)
113 /* Interrupt Enable Register - TS Y measurement ready */
114 #define AT91_SAMA5D2_IER_YRDY   BIT(21)
115 /* Interrupt Enable Register - TS pressure measurement ready */
116 #define AT91_SAMA5D2_IER_PRDY   BIT(22)
117 /* Interrupt Enable Register - Data ready */
118 #define AT91_SAMA5D2_IER_DRDY   BIT(24)
119 /* Interrupt Enable Register - general overrun error */
120 #define AT91_SAMA5D2_IER_GOVRE BIT(25)
121 /* Interrupt Enable Register - Pen detect */
122 #define AT91_SAMA5D2_IER_PEN    BIT(29)
123 /* Interrupt Enable Register - No pen detect */
124 #define AT91_SAMA5D2_IER_NOPEN  BIT(30)
125 
126 /* Interrupt Disable Register */
127 	u16				IDR;
128 /* Interrupt Mask Register */
129 	u16				IMR;
130 /* Interrupt Status Register */
131 	u16				ISR;
132 /* End of Conversion Interrupt Enable Register */
133 	u16				EOC_IER;
134 /* End of Conversion Interrupt Disable Register */
135 	u16				EOC_IDR;
136 /* End of Conversion Interrupt Mask Register */
137 	u16				EOC_IMR;
138 /* End of Conversion Interrupt Status Register */
139 	u16				EOC_ISR;
140 /* Interrupt Status Register - Pen touching sense status */
141 #define AT91_SAMA5D2_ISR_PENS   BIT(31)
142 /* Last Channel Trigger Mode Register */
143 	u16				LCTMR;
144 /* Last Channel Compare Window Register */
145 	u16				LCCWR;
146 /* Overrun Status Register */
147 	u16				OVER;
148 /* Extended Mode Register */
149 	u16				EMR;
150 /* Extended Mode Register - Oversampling rate */
151 #define AT91_SAMA5D2_EMR_OSR(V, M)		(((V) << 16) & (M))
152 #define AT91_SAMA5D2_EMR_OSR_1SAMPLES		0
153 #define AT91_SAMA5D2_EMR_OSR_4SAMPLES		1
154 #define AT91_SAMA5D2_EMR_OSR_16SAMPLES		2
155 #define AT91_SAMA5D2_EMR_OSR_64SAMPLES		3
156 #define AT91_SAMA5D2_EMR_OSR_256SAMPLES		4
157 
158 /* Extended Mode Register - TRACKX */
159 #define AT91_SAMA5D2_TRACKX_MASK		GENMASK(23, 22)
160 #define AT91_SAMA5D2_TRACKX(x)			(((x) << 22) & \
161 						 AT91_SAMA5D2_TRACKX_MASK)
162 /* TRACKX for temperature sensor. */
163 #define AT91_SAMA5D2_TRACKX_TS			(1)
164 
165 /* Extended Mode Register - Averaging on single trigger event */
166 #define AT91_SAMA5D2_EMR_ASTE(V)		((V) << 20)
167 
168 /* Compare Window Register */
169 	u16				CWR;
170 /* Channel Gain Register */
171 	u16				CGR;
172 /* Channel Offset Register */
173 	u16				COR;
174 /* Channel Offset Register differential offset - constant, not a register */
175 	u16				COR_diff_offset;
176 /* Analog Control Register */
177 	u16				ACR;
178 /* Analog Control Register - Pen detect sensitivity mask */
179 #define AT91_SAMA5D2_ACR_PENDETSENS_MASK        GENMASK(1, 0)
180 /* Analog Control Register - Source last channel */
181 #define AT91_SAMA5D2_ACR_SRCLCH		BIT(16)
182 
183 /* Touchscreen Mode Register */
184 	u16				TSMR;
185 /* Touchscreen Mode Register - No touch mode */
186 #define AT91_SAMA5D2_TSMR_TSMODE_NONE           0
187 /* Touchscreen Mode Register - 4 wire screen, no pressure measurement */
188 #define AT91_SAMA5D2_TSMR_TSMODE_4WIRE_NO_PRESS 1
189 /* Touchscreen Mode Register - 4 wire screen, pressure measurement */
190 #define AT91_SAMA5D2_TSMR_TSMODE_4WIRE_PRESS    2
191 /* Touchscreen Mode Register - 5 wire screen */
192 #define AT91_SAMA5D2_TSMR_TSMODE_5WIRE          3
193 /* Touchscreen Mode Register - Average samples mask */
194 #define AT91_SAMA5D2_TSMR_TSAV_MASK             GENMASK(5, 4)
195 /* Touchscreen Mode Register - Average samples */
196 #define AT91_SAMA5D2_TSMR_TSAV(x)               ((x) << 4)
197 /* Touchscreen Mode Register - Touch/trigger frequency ratio mask */
198 #define AT91_SAMA5D2_TSMR_TSFREQ_MASK           GENMASK(11, 8)
199 /* Touchscreen Mode Register - Touch/trigger frequency ratio */
200 #define AT91_SAMA5D2_TSMR_TSFREQ(x)             ((x) << 8)
201 /* Touchscreen Mode Register - Pen Debounce Time mask */
202 #define AT91_SAMA5D2_TSMR_PENDBC_MASK           GENMASK(31, 28)
203 /* Touchscreen Mode Register - Pen Debounce Time */
204 #define AT91_SAMA5D2_TSMR_PENDBC(x)            ((x) << 28)
205 /* Touchscreen Mode Register - No DMA for touch measurements */
206 #define AT91_SAMA5D2_TSMR_NOTSDMA               BIT(22)
207 /* Touchscreen Mode Register - Disable pen detection */
208 #define AT91_SAMA5D2_TSMR_PENDET_DIS            (0 << 24)
209 /* Touchscreen Mode Register - Enable pen detection */
210 #define AT91_SAMA5D2_TSMR_PENDET_ENA            BIT(24)
211 
212 /* Touchscreen X Position Register */
213 	u16				XPOSR;
214 /* Touchscreen Y Position Register */
215 	u16				YPOSR;
216 /* Touchscreen Pressure Register */
217 	u16				PRESSR;
218 /* Trigger Register */
219 	u16				TRGR;
220 /* Mask for TRGMOD field of TRGR register */
221 #define AT91_SAMA5D2_TRGR_TRGMOD_MASK GENMASK(2, 0)
222 /* No trigger, only software trigger can start conversions */
223 #define AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER 0
224 /* Trigger Mode external trigger rising edge */
225 #define AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_RISE 1
226 /* Trigger Mode external trigger falling edge */
227 #define AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_FALL 2
228 /* Trigger Mode external trigger any edge */
229 #define AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_ANY 3
230 /* Trigger Mode internal periodic */
231 #define AT91_SAMA5D2_TRGR_TRGMOD_PERIODIC 5
232 /* Trigger Mode - trigger period mask */
233 #define AT91_SAMA5D2_TRGR_TRGPER_MASK           GENMASK(31, 16)
234 /* Trigger Mode - trigger period */
235 #define AT91_SAMA5D2_TRGR_TRGPER(x)             ((x) << 16)
236 
237 /* Correction Select Register */
238 	u16				COSR;
239 /* Correction Value Register */
240 	u16				CVR;
241 /* Channel Error Correction Register */
242 	u16				CECR;
243 /* Write Protection Mode Register */
244 	u16				WPMR;
245 /* Write Protection Status Register */
246 	u16				WPSR;
247 /* Version Register */
248 	u16				VERSION;
249 /* Temperature Sensor Mode Register */
250 	u16				TEMPMR;
251 /* Temperature Sensor Mode - Temperature sensor on */
252 #define AT91_SAMA5D2_TEMPMR_TEMPON	BIT(0)
253 };
254 
255 static const struct at91_adc_reg_layout sama5d2_layout = {
256 	.CR =			0x00,
257 	.MR =			0x04,
258 	.SEQR1 =		0x08,
259 	.SEQR2 =		0x0c,
260 	.CHER =			0x10,
261 	.CHDR =			0x14,
262 	.CHSR =			0x18,
263 	.LCDR =			0x20,
264 	.IER =			0x24,
265 	.IDR =			0x28,
266 	.IMR =			0x2c,
267 	.ISR =			0x30,
268 	.LCTMR =		0x34,
269 	.LCCWR =		0x38,
270 	.OVER =			0x3c,
271 	.EMR =			0x40,
272 	.CWR =			0x44,
273 	.CGR =			0x48,
274 	.COR =			0x4c,
275 	.COR_diff_offset =	16,
276 	.ACR =			0x94,
277 	.TSMR =			0xb0,
278 	.XPOSR =		0xb4,
279 	.YPOSR =		0xb8,
280 	.PRESSR =		0xbc,
281 	.TRGR =			0xc0,
282 	.COSR =			0xd0,
283 	.CVR =			0xd4,
284 	.CECR =			0xd8,
285 	.WPMR =			0xe4,
286 	.WPSR =			0xe8,
287 	.VERSION =		0xfc,
288 };
289 
290 static const struct at91_adc_reg_layout sama7g5_layout = {
291 	.CR =			0x00,
292 	.MR =			0x04,
293 	.SEQR1 =		0x08,
294 	.SEQR2 =		0x0c,
295 	.CHER =			0x10,
296 	.CHDR =			0x14,
297 	.CHSR =			0x18,
298 	.LCDR =			0x20,
299 	.IER =			0x24,
300 	.IDR =			0x28,
301 	.IMR =			0x2c,
302 	.ISR =			0x30,
303 	.EOC_IER =		0x34,
304 	.EOC_IDR =		0x38,
305 	.EOC_IMR =		0x3c,
306 	.EOC_ISR =		0x40,
307 	.TEMPMR =		0x44,
308 	.OVER =			0x4c,
309 	.EMR =			0x50,
310 	.CWR =			0x54,
311 	.COR =			0x5c,
312 	.COR_diff_offset =	0,
313 	.ACR =			0xe0,
314 	.TRGR =			0x100,
315 	.COSR =			0x104,
316 	.CVR =			0x108,
317 	.CECR =			0x10c,
318 	.WPMR =			0x118,
319 	.WPSR =			0x11c,
320 	.VERSION =		0x130,
321 };
322 
323 #define AT91_SAMA5D2_TOUCH_SAMPLE_PERIOD_US          2000    /* 2ms */
324 #define AT91_SAMA5D2_TOUCH_PEN_DETECT_DEBOUNCE_US    200
325 
326 #define AT91_SAMA5D2_XYZ_MASK		GENMASK(11, 0)
327 
328 #define AT91_SAMA5D2_MAX_POS_BITS			12
329 
330 #define AT91_HWFIFO_MAX_SIZE_STR	"128"
331 #define AT91_HWFIFO_MAX_SIZE		128
332 
333 #define AT91_SAMA_CHAN_SINGLE(index, num, addr, rbits)			\
334 	{								\
335 		.type = IIO_VOLTAGE,					\
336 		.channel = num,						\
337 		.address = addr,					\
338 		.scan_index = index,					\
339 		.scan_type = {						\
340 			.sign = 'u',					\
341 			.realbits = rbits,				\
342 			.storagebits = 16,				\
343 		},							\
344 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
345 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),	\
346 		.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
347 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
348 		.info_mask_shared_by_all_available =			\
349 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
350 		.datasheet_name = "CH"#num,				\
351 		.indexed = 1,						\
352 	}
353 
354 #define AT91_SAMA5D2_CHAN_SINGLE(index, num, addr)			\
355 	AT91_SAMA_CHAN_SINGLE(index, num, addr, 14)
356 
357 #define AT91_SAMA7G5_CHAN_SINGLE(index, num, addr)			\
358 	AT91_SAMA_CHAN_SINGLE(index, num, addr, 16)
359 
360 #define AT91_SAMA_CHAN_DIFF(index, num, num2, addr, rbits)		\
361 	{								\
362 		.type = IIO_VOLTAGE,					\
363 		.differential = 1,					\
364 		.channel = num,						\
365 		.channel2 = num2,					\
366 		.address = addr,					\
367 		.scan_index = index,					\
368 		.scan_type = {						\
369 			.sign = 's',					\
370 			.realbits = rbits,				\
371 			.storagebits = 16,				\
372 		},							\
373 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
374 		.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),	\
375 		.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
376 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
377 		.info_mask_shared_by_all_available =			\
378 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
379 		.datasheet_name = "CH"#num"-CH"#num2,			\
380 		.indexed = 1,						\
381 	}
382 
383 #define AT91_SAMA5D2_CHAN_DIFF(index, num, num2, addr)			\
384 	AT91_SAMA_CHAN_DIFF(index, num, num2, addr, 14)
385 
386 #define AT91_SAMA7G5_CHAN_DIFF(index, num, num2, addr)			\
387 	AT91_SAMA_CHAN_DIFF(index, num, num2, addr, 16)
388 
389 #define AT91_SAMA5D2_CHAN_TOUCH(num, name, mod)				\
390 	{								\
391 		.type = IIO_POSITIONRELATIVE,				\
392 		.modified = 1,						\
393 		.channel = num,						\
394 		.channel2 = mod,					\
395 		.scan_index = num,					\
396 		.scan_type = {						\
397 			.sign = 'u',					\
398 			.realbits = 12,					\
399 			.storagebits = 16,				\
400 		},							\
401 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
402 		.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
403 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
404 		.info_mask_shared_by_all_available =			\
405 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
406 		.datasheet_name = name,					\
407 	}
408 #define AT91_SAMA5D2_CHAN_PRESSURE(num, name)				\
409 	{								\
410 		.type = IIO_PRESSURE,					\
411 		.channel = num,						\
412 		.scan_index = num,					\
413 		.scan_type = {						\
414 			.sign = 'u',					\
415 			.realbits = 12,					\
416 			.storagebits = 16,				\
417 		},							\
418 		.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),		\
419 		.info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ)|\
420 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
421 		.info_mask_shared_by_all_available =			\
422 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
423 		.datasheet_name = name,					\
424 	}
425 
426 #define AT91_SAMA5D2_CHAN_TEMP(num, name, addr)				\
427 	{								\
428 		.type = IIO_TEMP,					\
429 		.channel = num,						\
430 		.address =  addr,					\
431 		.scan_index = num,					\
432 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED),	\
433 		.info_mask_shared_by_all =				\
434 				BIT(IIO_CHAN_INFO_PROCESSED) |		\
435 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
436 		.info_mask_shared_by_all_available =			\
437 				BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO),	\
438 		.datasheet_name = name,					\
439 	}
440 
441 #define at91_adc_readl(st, reg)						\
442 	readl_relaxed((st)->base + (st)->soc_info.platform->layout->reg)
443 #define at91_adc_read_chan(st, reg)					\
444 	readl_relaxed((st)->base + reg)
445 #define at91_adc_writel(st, reg, val)					\
446 	writel_relaxed(val, (st)->base + (st)->soc_info.platform->layout->reg)
447 
448 /**
449  * struct at91_adc_platform - at91-sama5d2 platform information struct
450  * @layout:		pointer to the reg layout struct
451  * @adc_channels:	pointer to an array of channels for registering in
452  *			the iio subsystem
453  * @nr_channels:	number of physical channels available
454  * @touch_chan_x:	index of the touchscreen X channel
455  * @touch_chan_y:	index of the touchscreen Y channel
456  * @touch_chan_p:	index of the touchscreen P channel
457  * @max_channels:	number of total channels
458  * @max_index:		highest channel index (highest index may be higher
459  *			than the total channel number)
460  * @hw_trig_cnt:	number of possible hardware triggers
461  * @osr_mask:		oversampling ratio bitmask on EMR register
462  * @oversampling_avail:	available oversampling values
463  * @oversampling_avail_no: number of available oversampling values
464  * @chan_realbits:	realbits for registered channels
465  * @temp_chan:		temperature channel index
466  * @temp_sensor:	temperature sensor supported
467  */
468 struct at91_adc_platform {
469 	const struct at91_adc_reg_layout	*layout;
470 	const struct iio_chan_spec		(*adc_channels)[];
471 	unsigned int				nr_channels;
472 	unsigned int				touch_chan_x;
473 	unsigned int				touch_chan_y;
474 	unsigned int				touch_chan_p;
475 	unsigned int				max_channels;
476 	unsigned int				max_index;
477 	unsigned int				hw_trig_cnt;
478 	unsigned int				osr_mask;
479 	unsigned int				oversampling_avail[5];
480 	unsigned int				oversampling_avail_no;
481 	unsigned int				chan_realbits;
482 	unsigned int				temp_chan;
483 	bool					temp_sensor;
484 };
485 
486 /**
487  * struct at91_adc_temp_sensor_clb - at91-sama5d2 temperature sensor
488  * calibration data structure
489  * @p1: P1 calibration temperature
490  * @p4: P4 calibration voltage
491  * @p6: P6 calibration voltage
492  */
493 struct at91_adc_temp_sensor_clb {
494 	u32 p1;
495 	u32 p4;
496 	u32 p6;
497 };
498 
499 /**
500  * enum at91_adc_ts_clb_idx - calibration indexes in NVMEM buffer
501  * @AT91_ADC_TS_CLB_IDX_P1: index for P1
502  * @AT91_ADC_TS_CLB_IDX_P4: index for P4
503  * @AT91_ADC_TS_CLB_IDX_P6: index for P6
504  * @AT91_ADC_TS_CLB_IDX_MAX: max index for temperature calibration packet in OTP
505  */
506 enum at91_adc_ts_clb_idx {
507 	AT91_ADC_TS_CLB_IDX_P1 = 2,
508 	AT91_ADC_TS_CLB_IDX_P4 = 5,
509 	AT91_ADC_TS_CLB_IDX_P6 = 7,
510 	AT91_ADC_TS_CLB_IDX_MAX = 19,
511 };
512 
513 /* Temperature sensor calibration - Vtemp voltage sensitivity to temperature. */
514 #define AT91_ADC_TS_VTEMP_DT		(2080U)
515 
516 /**
517  * struct at91_adc_soc_info - at91-sama5d2 soc information struct
518  * @startup_time:	device startup time
519  * @min_sample_rate:	minimum sample rate in Hz
520  * @max_sample_rate:	maximum sample rate in Hz
521  * @platform:		pointer to the platform structure
522  * @temp_sensor_clb:	temperature sensor calibration data structure
523  */
524 struct at91_adc_soc_info {
525 	unsigned			startup_time;
526 	unsigned			min_sample_rate;
527 	unsigned			max_sample_rate;
528 	const struct at91_adc_platform	*platform;
529 	struct at91_adc_temp_sensor_clb	temp_sensor_clb;
530 };
531 
532 struct at91_adc_trigger {
533 	char				*name;
534 	unsigned int			trgmod_value;
535 	unsigned int			edge_type;
536 	bool				hw_trig;
537 };
538 
539 /**
540  * struct at91_adc_dma - at91-sama5d2 dma information struct
541  * @dma_chan:		the dma channel acquired
542  * @rx_buf:		dma coherent allocated area
543  * @rx_dma_buf:		dma handler for the buffer
544  * @phys_addr:		physical address of the ADC base register
545  * @buf_idx:		index inside the dma buffer where reading was last done
546  * @rx_buf_sz:		size of buffer used by DMA operation
547  * @watermark:		number of conversions to copy before DMA triggers irq
548  * @dma_ts:		hold the start timestamp of dma operation
549  */
550 struct at91_adc_dma {
551 	struct dma_chan			*dma_chan;
552 	u8				*rx_buf;
553 	dma_addr_t			rx_dma_buf;
554 	phys_addr_t			phys_addr;
555 	int				buf_idx;
556 	int				rx_buf_sz;
557 	int				watermark;
558 	s64				dma_ts;
559 };
560 
561 /**
562  * struct at91_adc_touch - at91-sama5d2 touchscreen information struct
563  * @sample_period_val:		the value for periodic trigger interval
564  * @touching:			is the pen touching the screen or not
565  * @x_pos:			temporary placeholder for pressure computation
566  * @channels_bitmask:		bitmask with the touchscreen channels enabled
567  * @workq:			workqueue for buffer data pushing
568  */
569 struct at91_adc_touch {
570 	u16				sample_period_val;
571 	bool				touching;
572 	u16				x_pos;
573 	unsigned long			channels_bitmask;
574 	struct work_struct		workq;
575 };
576 
577 /**
578  * struct at91_adc_temp - at91-sama5d2 temperature information structure
579  * @sample_period_val:	sample period value
580  * @saved_sample_rate:	saved sample rate
581  * @saved_oversampling:	saved oversampling
582  */
583 struct at91_adc_temp {
584 	u16				sample_period_val;
585 	u16				saved_sample_rate;
586 	u16				saved_oversampling;
587 };
588 
589 struct at91_adc_state {
590 	void __iomem			*base;
591 	int				irq;
592 	struct clk			*per_clk;
593 	struct regulator		*reg;
594 	struct regulator		*vref;
595 	int				vref_uv;
596 	unsigned int			current_sample_rate;
597 	struct iio_trigger		*trig;
598 	const struct at91_adc_trigger	*selected_trig;
599 	const struct iio_chan_spec	*chan;
600 	bool				conversion_done;
601 	u32				conversion_value;
602 	unsigned int			oversampling_ratio;
603 	struct at91_adc_soc_info	soc_info;
604 	wait_queue_head_t		wq_data_available;
605 	struct at91_adc_dma		dma_st;
606 	struct at91_adc_touch		touch_st;
607 	struct at91_adc_temp		temp_st;
608 	struct iio_dev			*indio_dev;
609 	struct device			*dev;
610 	/* We assume 32 channels for now, has to be increased if needed. */
611 	IIO_DECLARE_BUFFER_WITH_TS(u16, buffer, 32);
612 	/*
613 	 * lock to prevent concurrent 'single conversion' requests through
614 	 * sysfs.
615 	 */
616 	struct mutex			lock;
617 };
618 
619 static const struct at91_adc_trigger at91_adc_trigger_list[] = {
620 	{
621 		.name = "external_rising",
622 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_RISE,
623 		.edge_type = IRQ_TYPE_EDGE_RISING,
624 		.hw_trig = true,
625 	},
626 	{
627 		.name = "external_falling",
628 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_FALL,
629 		.edge_type = IRQ_TYPE_EDGE_FALLING,
630 		.hw_trig = true,
631 	},
632 	{
633 		.name = "external_any",
634 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_EXT_TRIG_ANY,
635 		.edge_type = IRQ_TYPE_EDGE_BOTH,
636 		.hw_trig = true,
637 	},
638 	{
639 		.name = "software",
640 		.trgmod_value = AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER,
641 		.edge_type = IRQ_TYPE_NONE,
642 		.hw_trig = false,
643 	},
644 };
645 
646 static const struct iio_chan_spec at91_sama5d2_adc_channels[] = {
647 	AT91_SAMA5D2_CHAN_SINGLE(0, 0, 0x50),
648 	AT91_SAMA5D2_CHAN_SINGLE(1, 1, 0x54),
649 	AT91_SAMA5D2_CHAN_SINGLE(2, 2, 0x58),
650 	AT91_SAMA5D2_CHAN_SINGLE(3, 3, 0x5c),
651 	AT91_SAMA5D2_CHAN_SINGLE(4, 4, 0x60),
652 	AT91_SAMA5D2_CHAN_SINGLE(5, 5, 0x64),
653 	AT91_SAMA5D2_CHAN_SINGLE(6, 6, 0x68),
654 	AT91_SAMA5D2_CHAN_SINGLE(7, 7, 0x6c),
655 	AT91_SAMA5D2_CHAN_SINGLE(8, 8, 0x70),
656 	AT91_SAMA5D2_CHAN_SINGLE(9, 9, 0x74),
657 	AT91_SAMA5D2_CHAN_SINGLE(10, 10, 0x78),
658 	AT91_SAMA5D2_CHAN_SINGLE(11, 11, 0x7c),
659 	/* original ABI has the differential channels with a gap in between */
660 	AT91_SAMA5D2_CHAN_DIFF(12, 0, 1, 0x50),
661 	AT91_SAMA5D2_CHAN_DIFF(14, 2, 3, 0x58),
662 	AT91_SAMA5D2_CHAN_DIFF(16, 4, 5, 0x60),
663 	AT91_SAMA5D2_CHAN_DIFF(18, 6, 7, 0x68),
664 	AT91_SAMA5D2_CHAN_DIFF(20, 8, 9, 0x70),
665 	AT91_SAMA5D2_CHAN_DIFF(22, 10, 11, 0x78),
666 	IIO_CHAN_SOFT_TIMESTAMP(23),
667 	AT91_SAMA5D2_CHAN_TOUCH(24, "x", IIO_MOD_X),
668 	AT91_SAMA5D2_CHAN_TOUCH(25, "y", IIO_MOD_Y),
669 	AT91_SAMA5D2_CHAN_PRESSURE(26, "pressure"),
670 };
671 
672 static const struct iio_chan_spec at91_sama7g5_adc_channels[] = {
673 	AT91_SAMA7G5_CHAN_SINGLE(0, 0, 0x60),
674 	AT91_SAMA7G5_CHAN_SINGLE(1, 1, 0x64),
675 	AT91_SAMA7G5_CHAN_SINGLE(2, 2, 0x68),
676 	AT91_SAMA7G5_CHAN_SINGLE(3, 3, 0x6c),
677 	AT91_SAMA7G5_CHAN_SINGLE(4, 4, 0x70),
678 	AT91_SAMA7G5_CHAN_SINGLE(5, 5, 0x74),
679 	AT91_SAMA7G5_CHAN_SINGLE(6, 6, 0x78),
680 	AT91_SAMA7G5_CHAN_SINGLE(7, 7, 0x7c),
681 	AT91_SAMA7G5_CHAN_SINGLE(8, 8, 0x80),
682 	AT91_SAMA7G5_CHAN_SINGLE(9, 9, 0x84),
683 	AT91_SAMA7G5_CHAN_SINGLE(10, 10, 0x88),
684 	AT91_SAMA7G5_CHAN_SINGLE(11, 11, 0x8c),
685 	AT91_SAMA7G5_CHAN_SINGLE(12, 12, 0x90),
686 	AT91_SAMA7G5_CHAN_SINGLE(13, 13, 0x94),
687 	AT91_SAMA7G5_CHAN_SINGLE(14, 14, 0x98),
688 	AT91_SAMA7G5_CHAN_SINGLE(15, 15, 0x9c),
689 	AT91_SAMA7G5_CHAN_DIFF(16, 0, 1, 0x60),
690 	AT91_SAMA7G5_CHAN_DIFF(17, 2, 3, 0x68),
691 	AT91_SAMA7G5_CHAN_DIFF(18, 4, 5, 0x70),
692 	AT91_SAMA7G5_CHAN_DIFF(19, 6, 7, 0x78),
693 	AT91_SAMA7G5_CHAN_DIFF(20, 8, 9, 0x80),
694 	AT91_SAMA7G5_CHAN_DIFF(21, 10, 11, 0x88),
695 	AT91_SAMA7G5_CHAN_DIFF(22, 12, 13, 0x90),
696 	AT91_SAMA7G5_CHAN_DIFF(23, 14, 15, 0x98),
697 	IIO_CHAN_SOFT_TIMESTAMP(24),
698 	AT91_SAMA5D2_CHAN_TEMP(AT91_SAMA7G5_ADC_TEMP_CHANNEL, "temp", 0xdc),
699 };
700 
701 static const struct at91_adc_platform sama5d2_platform = {
702 	.layout = &sama5d2_layout,
703 	.adc_channels = &at91_sama5d2_adc_channels,
704 #define AT91_SAMA5D2_SINGLE_CHAN_CNT 12
705 #define AT91_SAMA5D2_DIFF_CHAN_CNT 6
706 	.nr_channels = AT91_SAMA5D2_SINGLE_CHAN_CNT +
707 		       AT91_SAMA5D2_DIFF_CHAN_CNT,
708 #define AT91_SAMA5D2_TOUCH_X_CHAN_IDX	(AT91_SAMA5D2_SINGLE_CHAN_CNT + \
709 					AT91_SAMA5D2_DIFF_CHAN_CNT * 2)
710 	.touch_chan_x = AT91_SAMA5D2_TOUCH_X_CHAN_IDX,
711 #define AT91_SAMA5D2_TOUCH_Y_CHAN_IDX	(AT91_SAMA5D2_TOUCH_X_CHAN_IDX + 1)
712 	.touch_chan_y = AT91_SAMA5D2_TOUCH_Y_CHAN_IDX,
713 #define AT91_SAMA5D2_TOUCH_P_CHAN_IDX	(AT91_SAMA5D2_TOUCH_Y_CHAN_IDX + 1)
714 	.touch_chan_p = AT91_SAMA5D2_TOUCH_P_CHAN_IDX,
715 #define AT91_SAMA5D2_MAX_CHAN_IDX	AT91_SAMA5D2_TOUCH_P_CHAN_IDX
716 	.max_channels = ARRAY_SIZE(at91_sama5d2_adc_channels),
717 	.max_index = AT91_SAMA5D2_MAX_CHAN_IDX,
718 #define AT91_SAMA5D2_HW_TRIG_CNT	3
719 	.hw_trig_cnt = AT91_SAMA5D2_HW_TRIG_CNT,
720 	.osr_mask = GENMASK(17, 16),
721 	.oversampling_avail = { 1, 4, 16, },
722 	.oversampling_avail_no = 3,
723 	.chan_realbits = 14,
724 };
725 
726 static const struct at91_adc_platform sama7g5_platform = {
727 	.layout = &sama7g5_layout,
728 	.adc_channels = &at91_sama7g5_adc_channels,
729 #define AT91_SAMA7G5_SINGLE_CHAN_CNT	16
730 #define AT91_SAMA7G5_DIFF_CHAN_CNT	8
731 #define AT91_SAMA7G5_TEMP_CHAN_CNT	1
732 	.nr_channels = AT91_SAMA7G5_SINGLE_CHAN_CNT +
733 		       AT91_SAMA7G5_DIFF_CHAN_CNT +
734 		       AT91_SAMA7G5_TEMP_CHAN_CNT,
735 #define AT91_SAMA7G5_MAX_CHAN_IDX	(AT91_SAMA7G5_SINGLE_CHAN_CNT + \
736 					AT91_SAMA7G5_DIFF_CHAN_CNT + \
737 					AT91_SAMA7G5_TEMP_CHAN_CNT)
738 	.max_channels = ARRAY_SIZE(at91_sama7g5_adc_channels),
739 	.max_index = AT91_SAMA7G5_MAX_CHAN_IDX,
740 #define AT91_SAMA7G5_HW_TRIG_CNT	3
741 	.hw_trig_cnt = AT91_SAMA7G5_HW_TRIG_CNT,
742 	.osr_mask = GENMASK(18, 16),
743 	.oversampling_avail = { 1, 4, 16, 64, 256, },
744 	.oversampling_avail_no = 5,
745 	.chan_realbits = 16,
746 	.temp_sensor = true,
747 	.temp_chan = AT91_SAMA7G5_ADC_TEMP_CHANNEL,
748 };
749 
750 static int at91_adc_chan_xlate(struct iio_dev *indio_dev, int chan)
751 {
752 	int i;
753 
754 	for (i = 0; i < indio_dev->num_channels; i++) {
755 		if (indio_dev->channels[i].scan_index == chan)
756 			return i;
757 	}
758 	return -EINVAL;
759 }
760 
761 static inline struct iio_chan_spec const *
762 at91_adc_chan_get(struct iio_dev *indio_dev, int chan)
763 {
764 	int index = at91_adc_chan_xlate(indio_dev, chan);
765 
766 	if (index < 0)
767 		return NULL;
768 	return indio_dev->channels + index;
769 }
770 
771 static inline int at91_adc_fwnode_xlate(struct iio_dev *indio_dev,
772 					const struct fwnode_reference_args *iiospec)
773 {
774 	return at91_adc_chan_xlate(indio_dev, iiospec->args[0]);
775 }
776 
777 static unsigned int at91_adc_active_scan_mask_to_reg(struct iio_dev *indio_dev)
778 {
779 	u32 mask = 0;
780 	u8 bit;
781 	struct at91_adc_state *st = iio_priv(indio_dev);
782 
783 	for_each_set_bit(bit, indio_dev->active_scan_mask,
784 			 indio_dev->num_channels) {
785 		struct iio_chan_spec const *chan =
786 			 at91_adc_chan_get(indio_dev, bit);
787 		mask |= BIT(chan->channel);
788 	}
789 
790 	return mask & GENMASK(st->soc_info.platform->nr_channels, 0);
791 }
792 
793 static void at91_adc_cor(struct at91_adc_state *st,
794 			 struct iio_chan_spec const *chan)
795 {
796 	u32 cor, cur_cor;
797 
798 	cor = BIT(chan->channel) | BIT(chan->channel2);
799 
800 	cur_cor = at91_adc_readl(st, COR);
801 	cor <<= st->soc_info.platform->layout->COR_diff_offset;
802 	if (chan->differential)
803 		at91_adc_writel(st, COR, cur_cor | cor);
804 	else
805 		at91_adc_writel(st, COR, cur_cor & ~cor);
806 }
807 
808 static void at91_adc_irq_status(struct at91_adc_state *st, u32 *status,
809 				u32 *eoc)
810 {
811 	*status = at91_adc_readl(st, ISR);
812 	if (st->soc_info.platform->layout->EOC_ISR)
813 		*eoc = at91_adc_readl(st, EOC_ISR);
814 	else
815 		*eoc = *status;
816 }
817 
818 static void at91_adc_irq_mask(struct at91_adc_state *st, u32 *status, u32 *eoc)
819 {
820 	*status = at91_adc_readl(st, IMR);
821 	if (st->soc_info.platform->layout->EOC_IMR)
822 		*eoc = at91_adc_readl(st, EOC_IMR);
823 	else
824 		*eoc = *status;
825 }
826 
827 static void at91_adc_eoc_dis(struct at91_adc_state *st, unsigned int channel)
828 {
829 	/*
830 	 * On some products having the EOC bits in a separate register,
831 	 * errata recommends not writing this register (EOC_IDR).
832 	 * On products having the EOC bits in the IDR register, it's fine to write it.
833 	 */
834 	if (!st->soc_info.platform->layout->EOC_IDR)
835 		at91_adc_writel(st, IDR, BIT(channel));
836 }
837 
838 static void at91_adc_eoc_ena(struct at91_adc_state *st, unsigned int channel)
839 {
840 	if (!st->soc_info.platform->layout->EOC_IDR)
841 		at91_adc_writel(st, IER, BIT(channel));
842 	else
843 		at91_adc_writel(st, EOC_IER, BIT(channel));
844 }
845 
846 static int at91_adc_config_emr(struct at91_adc_state *st,
847 			       u32 oversampling_ratio, u32 trackx)
848 {
849 	/* configure the extended mode register */
850 	unsigned int emr, osr;
851 	unsigned int osr_mask = st->soc_info.platform->osr_mask;
852 	int i, ret;
853 
854 	/* Check against supported oversampling values. */
855 	for (i = 0; i < st->soc_info.platform->oversampling_avail_no; i++) {
856 		if (oversampling_ratio == st->soc_info.platform->oversampling_avail[i])
857 			break;
858 	}
859 	if (i == st->soc_info.platform->oversampling_avail_no)
860 		return -EINVAL;
861 
862 	/* select oversampling ratio from configuration */
863 	switch (oversampling_ratio) {
864 	case 1:
865 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_1SAMPLES,
866 					   osr_mask);
867 		break;
868 	case 4:
869 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_4SAMPLES,
870 					   osr_mask);
871 		break;
872 	case 16:
873 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_16SAMPLES,
874 					   osr_mask);
875 		break;
876 	case 64:
877 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_64SAMPLES,
878 					   osr_mask);
879 		break;
880 	case 256:
881 		osr = AT91_SAMA5D2_EMR_OSR(AT91_SAMA5D2_EMR_OSR_256SAMPLES,
882 					   osr_mask);
883 		break;
884 	}
885 
886 	ret = pm_runtime_resume_and_get(st->dev);
887 	if (ret < 0)
888 		return ret;
889 
890 	emr = at91_adc_readl(st, EMR);
891 	/* select oversampling per single trigger event */
892 	emr |= AT91_SAMA5D2_EMR_ASTE(1);
893 	/* delete leftover content if it's the case */
894 	emr &= ~(osr_mask | AT91_SAMA5D2_TRACKX_MASK);
895 	/* Update osr and trackx. */
896 	emr |= osr | AT91_SAMA5D2_TRACKX(trackx);
897 	at91_adc_writel(st, EMR, emr);
898 
899 	pm_runtime_put_autosuspend(st->dev);
900 
901 	st->oversampling_ratio = oversampling_ratio;
902 
903 	return 0;
904 }
905 
906 static int at91_adc_adjust_val_osr(struct at91_adc_state *st, int *val)
907 {
908 	int nbits, diff;
909 
910 	if (st->oversampling_ratio == 1)
911 		nbits = 12;
912 	else if (st->oversampling_ratio == 4)
913 		nbits = 13;
914 	else if (st->oversampling_ratio == 16)
915 		nbits = 14;
916 	else if (st->oversampling_ratio == 64)
917 		nbits = 15;
918 	else if (st->oversampling_ratio == 256)
919 		nbits = 16;
920 	else
921 		/* Should not happen. */
922 		return -EINVAL;
923 
924 	/*
925 	 * We have nbits of real data and channel is registered as
926 	 * st->soc_info.platform->chan_realbits, so shift left diff bits.
927 	 */
928 	diff = st->soc_info.platform->chan_realbits - nbits;
929 	*val <<= diff;
930 
931 	return IIO_VAL_INT;
932 }
933 
934 static void at91_adc_adjust_val_osr_array(struct at91_adc_state *st, void *buf,
935 					  int len)
936 {
937 	int i = 0, val;
938 	u16 *buf_u16 = (u16 *) buf;
939 
940 	/*
941 	 * We are converting each two bytes (each sample).
942 	 * First convert the byte based array to u16, and convert each sample
943 	 * separately.
944 	 * Each value is two bytes in an array of chars, so to not shift
945 	 * more than we need, save the value separately.
946 	 * len is in bytes, so divide by two to get number of samples.
947 	 */
948 	while (i < len / 2) {
949 		val = buf_u16[i];
950 		at91_adc_adjust_val_osr(st, &val);
951 		buf_u16[i] = val;
952 		i++;
953 	}
954 }
955 
956 static int at91_adc_configure_touch(struct at91_adc_state *st, bool state)
957 {
958 	u32 clk_khz = st->current_sample_rate / 1000;
959 	int i = 0, ret;
960 	u16 pendbc;
961 	u32 tsmr, acr;
962 
963 	if (state) {
964 		ret = pm_runtime_resume_and_get(st->dev);
965 		if (ret < 0)
966 			return ret;
967 	} else {
968 		/* disabling touch IRQs and setting mode to no touch enabled */
969 		at91_adc_writel(st, IDR,
970 				AT91_SAMA5D2_IER_PEN | AT91_SAMA5D2_IER_NOPEN);
971 		at91_adc_writel(st, TSMR, 0);
972 
973 		pm_runtime_put_autosuspend(st->dev);
974 		return 0;
975 	}
976 	/*
977 	 * debounce time is in microseconds, we need it in milliseconds to
978 	 * multiply with kilohertz, so, divide by 1000, but after the multiply.
979 	 * round up to make sure pendbc is at least 1
980 	 */
981 	pendbc = round_up(AT91_SAMA5D2_TOUCH_PEN_DETECT_DEBOUNCE_US *
982 			  clk_khz / 1000, 1);
983 
984 	/* get the required exponent */
985 	while (pendbc >> i++)
986 		;
987 
988 	pendbc = i;
989 
990 	tsmr = AT91_SAMA5D2_TSMR_TSMODE_4WIRE_PRESS;
991 
992 	tsmr |= AT91_SAMA5D2_TSMR_TSAV(2) & AT91_SAMA5D2_TSMR_TSAV_MASK;
993 	tsmr |= AT91_SAMA5D2_TSMR_PENDBC(pendbc) &
994 		AT91_SAMA5D2_TSMR_PENDBC_MASK;
995 	tsmr |= AT91_SAMA5D2_TSMR_NOTSDMA;
996 	tsmr |= AT91_SAMA5D2_TSMR_PENDET_ENA;
997 	tsmr |= AT91_SAMA5D2_TSMR_TSFREQ(2) & AT91_SAMA5D2_TSMR_TSFREQ_MASK;
998 
999 	at91_adc_writel(st, TSMR, tsmr);
1000 
1001 	acr =  at91_adc_readl(st, ACR);
1002 	acr &= ~AT91_SAMA5D2_ACR_PENDETSENS_MASK;
1003 	acr |= 0x02 & AT91_SAMA5D2_ACR_PENDETSENS_MASK;
1004 	at91_adc_writel(st, ACR, acr);
1005 
1006 	/* Sample Period Time = (TRGPER + 1) / ADCClock */
1007 	st->touch_st.sample_period_val =
1008 				 round_up((AT91_SAMA5D2_TOUCH_SAMPLE_PERIOD_US *
1009 				 clk_khz / 1000) - 1, 1);
1010 	/* enable pen detect IRQ */
1011 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_PEN);
1012 
1013 	return 0;
1014 }
1015 
1016 static u16 at91_adc_touch_pos(struct at91_adc_state *st, int reg)
1017 {
1018 	u32 val = 0;
1019 	u32 scale, result, pos;
1020 
1021 	/*
1022 	 * to obtain the actual position we must divide by scale
1023 	 * and multiply with max, where
1024 	 * max = 2^AT91_SAMA5D2_MAX_POS_BITS - 1
1025 	 */
1026 	/* first half of register is the x or y, second half is the scale */
1027 	if (reg == st->soc_info.platform->layout->XPOSR)
1028 		val = at91_adc_readl(st, XPOSR);
1029 	else if (reg == st->soc_info.platform->layout->YPOSR)
1030 		val = at91_adc_readl(st, YPOSR);
1031 
1032 	if (!val)
1033 		dev_dbg(&st->indio_dev->dev, "pos is 0\n");
1034 
1035 	pos = val & AT91_SAMA5D2_XYZ_MASK;
1036 	result = (pos << AT91_SAMA5D2_MAX_POS_BITS) - pos;
1037 	scale = (val >> 16) & AT91_SAMA5D2_XYZ_MASK;
1038 	if (scale == 0) {
1039 		dev_err(&st->indio_dev->dev, "scale is 0\n");
1040 		return 0;
1041 	}
1042 	result /= scale;
1043 
1044 	return result;
1045 }
1046 
1047 static u16 at91_adc_touch_x_pos(struct at91_adc_state *st)
1048 {
1049 	st->touch_st.x_pos = at91_adc_touch_pos(st, st->soc_info.platform->layout->XPOSR);
1050 	return st->touch_st.x_pos;
1051 }
1052 
1053 static u16 at91_adc_touch_y_pos(struct at91_adc_state *st)
1054 {
1055 	return at91_adc_touch_pos(st, st->soc_info.platform->layout->YPOSR);
1056 }
1057 
1058 static u16 at91_adc_touch_pressure(struct at91_adc_state *st)
1059 {
1060 	u32 val;
1061 	u32 z1, z2;
1062 	u32 pres;
1063 	u32 rxp = 1;
1064 	u32 factor = 1000;
1065 
1066 	/* calculate the pressure */
1067 	val = at91_adc_readl(st, PRESSR);
1068 	z1 = val & AT91_SAMA5D2_XYZ_MASK;
1069 	z2 = (val >> 16) & AT91_SAMA5D2_XYZ_MASK;
1070 
1071 	if (z1 != 0)
1072 		pres = rxp * (st->touch_st.x_pos * factor / 1024) *
1073 			(z2 * factor / z1 - factor) /
1074 			factor;
1075 	else
1076 		pres = 0xFFFF;       /* no pen contact */
1077 
1078 	/*
1079 	 * The pressure from device grows down, minimum is 0xFFFF, maximum 0x0.
1080 	 * We compute it this way, but let's return it in the expected way,
1081 	 * growing from 0 to 0xFFFF.
1082 	 */
1083 	return 0xFFFF - pres;
1084 }
1085 
1086 static int at91_adc_read_position(struct at91_adc_state *st, int chan, u16 *val)
1087 {
1088 	*val = 0;
1089 	if (!st->touch_st.touching)
1090 		return -ENODATA;
1091 	if (chan == st->soc_info.platform->touch_chan_x)
1092 		*val = at91_adc_touch_x_pos(st);
1093 	else if (chan == st->soc_info.platform->touch_chan_y)
1094 		*val = at91_adc_touch_y_pos(st);
1095 	else
1096 		return -ENODATA;
1097 
1098 	return IIO_VAL_INT;
1099 }
1100 
1101 static int at91_adc_read_pressure(struct at91_adc_state *st, int chan, u16 *val)
1102 {
1103 	*val = 0;
1104 	if (!st->touch_st.touching)
1105 		return -ENODATA;
1106 	if (chan == st->soc_info.platform->touch_chan_p)
1107 		*val = at91_adc_touch_pressure(st);
1108 	else
1109 		return -ENODATA;
1110 
1111 	return IIO_VAL_INT;
1112 }
1113 
1114 static void at91_adc_configure_trigger_registers(struct at91_adc_state *st,
1115 						 bool state)
1116 {
1117 	u32 status = at91_adc_readl(st, TRGR);
1118 
1119 	/* clear TRGMOD */
1120 	status &= ~AT91_SAMA5D2_TRGR_TRGMOD_MASK;
1121 
1122 	if (state)
1123 		status |= st->selected_trig->trgmod_value;
1124 
1125 	/* set/unset hw trigger */
1126 	at91_adc_writel(st, TRGR, status);
1127 }
1128 
1129 static int at91_adc_configure_trigger(struct iio_trigger *trig, bool state)
1130 {
1131 	struct iio_dev *indio = iio_trigger_get_drvdata(trig);
1132 	struct at91_adc_state *st = iio_priv(indio);
1133 	int ret;
1134 
1135 	if (state) {
1136 		ret = pm_runtime_resume_and_get(st->dev);
1137 		if (ret < 0)
1138 			return ret;
1139 	}
1140 
1141 	at91_adc_configure_trigger_registers(st, state);
1142 
1143 	if (!state)
1144 		pm_runtime_put_autosuspend(st->dev);
1145 
1146 	return 0;
1147 }
1148 
1149 static void at91_adc_reenable_trigger(struct iio_trigger *trig)
1150 {
1151 	struct iio_dev *indio = iio_trigger_get_drvdata(trig);
1152 	struct at91_adc_state *st = iio_priv(indio);
1153 
1154 	/* if we are using DMA, we must not reenable irq after each trigger */
1155 	if (st->dma_st.dma_chan)
1156 		return;
1157 
1158 	enable_irq(st->irq);
1159 
1160 	/* Needed to ACK the DRDY interruption */
1161 	at91_adc_readl(st, LCDR);
1162 }
1163 
1164 static const struct iio_trigger_ops at91_adc_trigger_ops = {
1165 	.set_trigger_state = &at91_adc_configure_trigger,
1166 	.reenable = &at91_adc_reenable_trigger,
1167 	.validate_device = iio_trigger_validate_own_device,
1168 };
1169 
1170 static int at91_adc_dma_size_done(struct at91_adc_state *st)
1171 {
1172 	struct dma_tx_state state;
1173 	enum dma_status status;
1174 	int i, size;
1175 
1176 	status = dmaengine_tx_status(st->dma_st.dma_chan,
1177 				     st->dma_st.dma_chan->cookie,
1178 				     &state);
1179 	if (status != DMA_IN_PROGRESS)
1180 		return 0;
1181 
1182 	/* Transferred length is size in bytes from end of buffer */
1183 	i = st->dma_st.rx_buf_sz - state.residue;
1184 
1185 	/* Return available bytes */
1186 	if (i >= st->dma_st.buf_idx)
1187 		size = i - st->dma_st.buf_idx;
1188 	else
1189 		size = st->dma_st.rx_buf_sz + i - st->dma_st.buf_idx;
1190 	return size;
1191 }
1192 
1193 static void at91_dma_buffer_done(void *data)
1194 {
1195 	struct iio_dev *indio_dev = data;
1196 
1197 	iio_trigger_poll_nested(indio_dev->trig);
1198 }
1199 
1200 static int at91_adc_dma_start(struct iio_dev *indio_dev)
1201 {
1202 	struct at91_adc_state *st = iio_priv(indio_dev);
1203 	struct dma_async_tx_descriptor *desc;
1204 	dma_cookie_t cookie;
1205 	int ret;
1206 	u8 bit;
1207 
1208 	if (!st->dma_st.dma_chan)
1209 		return 0;
1210 
1211 	/* we start a new DMA, so set buffer index to start */
1212 	st->dma_st.buf_idx = 0;
1213 
1214 	/*
1215 	 * compute buffer size w.r.t. watermark and enabled channels.
1216 	 * scan_bytes is aligned so we need an exact size for DMA
1217 	 */
1218 	st->dma_st.rx_buf_sz = 0;
1219 
1220 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1221 			 indio_dev->num_channels) {
1222 		struct iio_chan_spec const *chan =
1223 					 at91_adc_chan_get(indio_dev, bit);
1224 
1225 		if (!chan)
1226 			continue;
1227 
1228 		st->dma_st.rx_buf_sz += chan->scan_type.storagebits / 8;
1229 	}
1230 	st->dma_st.rx_buf_sz *= st->dma_st.watermark;
1231 
1232 	/* Prepare a DMA cyclic transaction */
1233 	desc = dmaengine_prep_dma_cyclic(st->dma_st.dma_chan,
1234 					 st->dma_st.rx_dma_buf,
1235 					 st->dma_st.rx_buf_sz,
1236 					 st->dma_st.rx_buf_sz / 2,
1237 					 DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT);
1238 
1239 	if (!desc) {
1240 		dev_err(&indio_dev->dev, "cannot prepare DMA cyclic\n");
1241 		return -EBUSY;
1242 	}
1243 
1244 	desc->callback = at91_dma_buffer_done;
1245 	desc->callback_param = indio_dev;
1246 
1247 	cookie = dmaengine_submit(desc);
1248 	ret = dma_submit_error(cookie);
1249 	if (ret) {
1250 		dev_err(&indio_dev->dev, "cannot submit DMA cyclic\n");
1251 		dmaengine_terminate_async(st->dma_st.dma_chan);
1252 		return ret;
1253 	}
1254 
1255 	/* enable general overrun error signaling */
1256 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_GOVRE);
1257 	/* Issue pending DMA requests */
1258 	dma_async_issue_pending(st->dma_st.dma_chan);
1259 
1260 	/* consider current time as DMA start time for timestamps */
1261 	st->dma_st.dma_ts = iio_get_time_ns(indio_dev);
1262 
1263 	dev_dbg(&indio_dev->dev, "DMA cyclic started\n");
1264 
1265 	return 0;
1266 }
1267 
1268 static bool at91_adc_buffer_check_use_irq(struct iio_dev *indio,
1269 					  struct at91_adc_state *st)
1270 {
1271 	/* if using DMA, we do not use our own IRQ (we use DMA-controller) */
1272 	if (st->dma_st.dma_chan)
1273 		return false;
1274 	/* if the trigger is not ours, then it has its own IRQ */
1275 	if (iio_trigger_validate_own_device(indio->trig, indio))
1276 		return false;
1277 	return true;
1278 }
1279 
1280 static bool at91_adc_current_chan_is_touch(struct iio_dev *indio_dev)
1281 {
1282 	struct at91_adc_state *st = iio_priv(indio_dev);
1283 
1284 	return !!bitmap_subset(indio_dev->active_scan_mask,
1285 			       &st->touch_st.channels_bitmask,
1286 			       st->soc_info.platform->max_index + 1);
1287 }
1288 
1289 static int at91_adc_buffer_prepare(struct iio_dev *indio_dev)
1290 {
1291 	int ret;
1292 	u8 bit;
1293 	struct at91_adc_state *st = iio_priv(indio_dev);
1294 
1295 	/* check if we are enabling triggered buffer or the touchscreen */
1296 	if (at91_adc_current_chan_is_touch(indio_dev))
1297 		return at91_adc_configure_touch(st, true);
1298 
1299 	/* if we are not in triggered mode, we cannot enable the buffer. */
1300 	if (!(iio_device_get_current_mode(indio_dev) & INDIO_ALL_TRIGGERED_MODES))
1301 		return -EINVAL;
1302 
1303 	ret = pm_runtime_resume_and_get(st->dev);
1304 	if (ret < 0)
1305 		return ret;
1306 
1307 	/* we continue with the triggered buffer */
1308 	ret = at91_adc_dma_start(indio_dev);
1309 	if (ret) {
1310 		dev_err(&indio_dev->dev, "buffer prepare failed\n");
1311 		goto pm_runtime_put;
1312 	}
1313 
1314 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1315 			 indio_dev->num_channels) {
1316 		struct iio_chan_spec const *chan =
1317 					at91_adc_chan_get(indio_dev, bit);
1318 		if (!chan)
1319 			continue;
1320 		/* these channel types cannot be handled by this trigger */
1321 		if (chan->type == IIO_POSITIONRELATIVE ||
1322 		    chan->type == IIO_PRESSURE ||
1323 		    chan->type == IIO_TEMP)
1324 			continue;
1325 
1326 		at91_adc_cor(st, chan);
1327 
1328 		at91_adc_writel(st, CHER, BIT(chan->channel));
1329 	}
1330 
1331 	if (at91_adc_buffer_check_use_irq(indio_dev, st))
1332 		at91_adc_writel(st, IER, AT91_SAMA5D2_IER_DRDY);
1333 
1334 pm_runtime_put:
1335 	pm_runtime_put_autosuspend(st->dev);
1336 	return ret;
1337 }
1338 
1339 static int at91_adc_buffer_postdisable(struct iio_dev *indio_dev)
1340 {
1341 	struct at91_adc_state *st = iio_priv(indio_dev);
1342 	int ret;
1343 	u8 bit;
1344 
1345 	/* check if we are disabling triggered buffer or the touchscreen */
1346 	if (at91_adc_current_chan_is_touch(indio_dev))
1347 		return at91_adc_configure_touch(st, false);
1348 
1349 	/* if we are not in triggered mode, nothing to do here */
1350 	if (!(iio_device_get_current_mode(indio_dev) & INDIO_ALL_TRIGGERED_MODES))
1351 		return -EINVAL;
1352 
1353 	ret = pm_runtime_resume_and_get(st->dev);
1354 	if (ret < 0)
1355 		return ret;
1356 
1357 	/*
1358 	 * For each enable channel we must disable it in hardware.
1359 	 * In the case of DMA, we must read the last converted value
1360 	 * to clear EOC status and not get a possible interrupt later.
1361 	 * This value is being read by DMA from LCDR anyway, so it's not lost.
1362 	 */
1363 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1364 			 indio_dev->num_channels) {
1365 		struct iio_chan_spec const *chan =
1366 					at91_adc_chan_get(indio_dev, bit);
1367 
1368 		if (!chan)
1369 			continue;
1370 		/* these channel types are virtual, no need to do anything */
1371 		if (chan->type == IIO_POSITIONRELATIVE ||
1372 		    chan->type == IIO_PRESSURE ||
1373 		    chan->type == IIO_TEMP)
1374 			continue;
1375 
1376 		at91_adc_writel(st, CHDR, BIT(chan->channel));
1377 
1378 		if (st->dma_st.dma_chan)
1379 			at91_adc_read_chan(st, chan->address);
1380 	}
1381 
1382 	if (at91_adc_buffer_check_use_irq(indio_dev, st))
1383 		at91_adc_writel(st, IDR, AT91_SAMA5D2_IER_DRDY);
1384 
1385 	/* read overflow register to clear possible overflow status */
1386 	at91_adc_readl(st, OVER);
1387 
1388 	/* if we are using DMA we must clear registers and end DMA */
1389 	if (st->dma_st.dma_chan)
1390 		dmaengine_terminate_sync(st->dma_st.dma_chan);
1391 
1392 	pm_runtime_put_autosuspend(st->dev);
1393 
1394 	return 0;
1395 }
1396 
1397 static const struct iio_buffer_setup_ops at91_buffer_setup_ops = {
1398 	.postdisable = &at91_adc_buffer_postdisable,
1399 };
1400 
1401 static struct iio_trigger *at91_adc_allocate_trigger(struct iio_dev *indio,
1402 						     char *trigger_name)
1403 {
1404 	struct iio_trigger *trig;
1405 	int ret;
1406 
1407 	trig = devm_iio_trigger_alloc(&indio->dev, "%s-dev%d-%s", indio->name,
1408 				iio_device_id(indio), trigger_name);
1409 	if (!trig)
1410 		return ERR_PTR(-ENOMEM);
1411 
1412 	trig->dev.parent = indio->dev.parent;
1413 	iio_trigger_set_drvdata(trig, indio);
1414 	trig->ops = &at91_adc_trigger_ops;
1415 
1416 	ret = devm_iio_trigger_register(&indio->dev, trig);
1417 	if (ret)
1418 		return ERR_PTR(ret);
1419 
1420 	return trig;
1421 }
1422 
1423 static void at91_adc_trigger_handler_nodma(struct iio_dev *indio_dev,
1424 					   struct iio_poll_func *pf)
1425 {
1426 	struct at91_adc_state *st = iio_priv(indio_dev);
1427 	int i = 0;
1428 	int val;
1429 	u8 bit;
1430 	u32 mask = at91_adc_active_scan_mask_to_reg(indio_dev);
1431 	unsigned int timeout = 50;
1432 	u32 status, imr, eoc = 0, eoc_imr;
1433 
1434 	/*
1435 	 * Check if the conversion is ready. If not, wait a little bit, and
1436 	 * in case of timeout exit with an error.
1437 	 */
1438 	while (((eoc & mask) != mask) && timeout) {
1439 		at91_adc_irq_status(st, &status, &eoc);
1440 		at91_adc_irq_mask(st, &imr, &eoc_imr);
1441 		usleep_range(50, 100);
1442 		timeout--;
1443 	}
1444 
1445 	/* Cannot read data, not ready. Continue without reporting data */
1446 	if (!timeout)
1447 		return;
1448 
1449 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1450 			 indio_dev->num_channels) {
1451 		struct iio_chan_spec const *chan =
1452 					at91_adc_chan_get(indio_dev, bit);
1453 
1454 		if (!chan)
1455 			continue;
1456 		/*
1457 		 * Our external trigger only supports the voltage channels.
1458 		 * In case someone requested a different type of channel
1459 		 * just put zeroes to buffer.
1460 		 * This should not happen because we check the scan mode
1461 		 * and scan mask when we enable the buffer, and we don't allow
1462 		 * the buffer to start with a mixed mask (voltage and something
1463 		 * else).
1464 		 * Thus, emit a warning.
1465 		 */
1466 		if (chan->type == IIO_VOLTAGE) {
1467 			val = at91_adc_read_chan(st, chan->address);
1468 			at91_adc_adjust_val_osr(st, &val);
1469 			st->buffer[i] = val;
1470 		} else {
1471 			st->buffer[i] = 0;
1472 			WARN(true, "This trigger cannot handle this type of channel");
1473 		}
1474 		i++;
1475 	}
1476 	iio_push_to_buffers_with_timestamp(indio_dev, st->buffer,
1477 					   pf->timestamp);
1478 }
1479 
1480 static void at91_adc_trigger_handler_dma(struct iio_dev *indio_dev)
1481 {
1482 	struct at91_adc_state *st = iio_priv(indio_dev);
1483 	int transferred_len = at91_adc_dma_size_done(st);
1484 	s64 ns = iio_get_time_ns(indio_dev);
1485 	s64 interval;
1486 	int sample_index = 0, sample_count, sample_size;
1487 
1488 	u32 status = at91_adc_readl(st, ISR);
1489 	/* if we reached this point, we cannot sample faster */
1490 	if (status & AT91_SAMA5D2_IER_GOVRE)
1491 		pr_info_ratelimited("%s: conversion overrun detected\n",
1492 				    indio_dev->name);
1493 
1494 	sample_size = div_s64(st->dma_st.rx_buf_sz, st->dma_st.watermark);
1495 
1496 	sample_count = div_s64(transferred_len, sample_size);
1497 
1498 	/*
1499 	 * interval between samples is total time since last transfer handling
1500 	 * divided by the number of samples (total size divided by sample size)
1501 	 */
1502 	interval = div_s64((ns - st->dma_st.dma_ts), sample_count);
1503 
1504 	while (transferred_len >= sample_size) {
1505 		/*
1506 		 * for all the values in the current sample,
1507 		 * adjust the values inside the buffer for oversampling
1508 		 */
1509 		at91_adc_adjust_val_osr_array(st,
1510 					&st->dma_st.rx_buf[st->dma_st.buf_idx],
1511 					sample_size);
1512 
1513 		iio_push_to_buffers_with_timestamp(indio_dev,
1514 				(st->dma_st.rx_buf + st->dma_st.buf_idx),
1515 				(st->dma_st.dma_ts + interval * sample_index));
1516 		/* adjust remaining length */
1517 		transferred_len -= sample_size;
1518 		/* adjust buffer index */
1519 		st->dma_st.buf_idx += sample_size;
1520 		/* in case of reaching end of buffer, reset index */
1521 		if (st->dma_st.buf_idx >= st->dma_st.rx_buf_sz)
1522 			st->dma_st.buf_idx = 0;
1523 		sample_index++;
1524 	}
1525 	/* adjust saved time for next transfer handling */
1526 	st->dma_st.dma_ts = iio_get_time_ns(indio_dev);
1527 }
1528 
1529 static irqreturn_t at91_adc_trigger_handler(int irq, void *p)
1530 {
1531 	struct iio_poll_func *pf = p;
1532 	struct iio_dev *indio_dev = pf->indio_dev;
1533 	struct at91_adc_state *st = iio_priv(indio_dev);
1534 
1535 	/*
1536 	 * If it's not our trigger, start a conversion now, as we are
1537 	 * actually polling the trigger now.
1538 	 */
1539 	if (iio_trigger_validate_own_device(indio_dev->trig, indio_dev))
1540 		at91_adc_writel(st, CR, AT91_SAMA5D2_CR_START);
1541 
1542 	if (st->dma_st.dma_chan)
1543 		at91_adc_trigger_handler_dma(indio_dev);
1544 	else
1545 		at91_adc_trigger_handler_nodma(indio_dev, pf);
1546 
1547 	iio_trigger_notify_done(indio_dev->trig);
1548 
1549 	return IRQ_HANDLED;
1550 }
1551 
1552 static unsigned at91_adc_startup_time(unsigned startup_time_min,
1553 				      unsigned adc_clk_khz)
1554 {
1555 	static const unsigned int startup_lookup[] = {
1556 		  0,   8,  16,  24,
1557 		 64,  80,  96, 112,
1558 		512, 576, 640, 704,
1559 		768, 832, 896, 960
1560 		};
1561 	unsigned ticks_min, i;
1562 
1563 	/*
1564 	 * Since the adc frequency is checked before, there is no reason
1565 	 * to not meet the startup time constraint.
1566 	 */
1567 
1568 	ticks_min = startup_time_min * adc_clk_khz / 1000;
1569 	for (i = 0; i < ARRAY_SIZE(startup_lookup); i++)
1570 		if (startup_lookup[i] > ticks_min)
1571 			break;
1572 
1573 	return i;
1574 }
1575 
1576 static void at91_adc_setup_samp_freq(struct iio_dev *indio_dev, unsigned freq,
1577 				     unsigned int startup_time,
1578 				     unsigned int tracktim)
1579 {
1580 	struct at91_adc_state *st = iio_priv(indio_dev);
1581 	unsigned f_per, prescal, startup, mr;
1582 	int ret;
1583 
1584 	f_per = clk_get_rate(st->per_clk);
1585 	prescal = (f_per / (2 * freq)) - 1;
1586 
1587 	startup = at91_adc_startup_time(startup_time, freq / 1000);
1588 
1589 	ret = pm_runtime_resume_and_get(st->dev);
1590 	if (ret < 0)
1591 		return;
1592 
1593 	mr = at91_adc_readl(st, MR);
1594 	mr &= ~(AT91_SAMA5D2_MR_STARTUP_MASK | AT91_SAMA5D2_MR_PRESCAL_MASK);
1595 	mr |= AT91_SAMA5D2_MR_STARTUP(startup);
1596 	mr |= AT91_SAMA5D2_MR_PRESCAL(prescal);
1597 	mr |= AT91_SAMA5D2_MR_TRACKTIM(tracktim);
1598 	at91_adc_writel(st, MR, mr);
1599 
1600 	pm_runtime_put_autosuspend(st->dev);
1601 
1602 	dev_dbg(&indio_dev->dev, "freq: %u, startup: %u, prescal: %u, tracktim=%u\n",
1603 		freq, startup, prescal, tracktim);
1604 	st->current_sample_rate = freq;
1605 }
1606 
1607 static inline unsigned at91_adc_get_sample_freq(struct at91_adc_state *st)
1608 {
1609 	return st->current_sample_rate;
1610 }
1611 
1612 static void at91_adc_touch_data_handler(struct iio_dev *indio_dev)
1613 {
1614 	struct at91_adc_state *st = iio_priv(indio_dev);
1615 	u8 bit;
1616 	u16 val;
1617 	int i = 0;
1618 
1619 	for_each_set_bit(bit, indio_dev->active_scan_mask,
1620 			 st->soc_info.platform->max_index + 1) {
1621 		struct iio_chan_spec const *chan =
1622 					 at91_adc_chan_get(indio_dev, bit);
1623 
1624 		if (chan->type == IIO_POSITIONRELATIVE)
1625 			at91_adc_read_position(st, chan->channel, &val);
1626 		else if (chan->type == IIO_PRESSURE)
1627 			at91_adc_read_pressure(st, chan->channel, &val);
1628 		else
1629 			continue;
1630 		st->buffer[i] = val;
1631 		i++;
1632 	}
1633 	/*
1634 	 * Schedule work to push to buffers.
1635 	 * This is intended to push to the callback buffer that another driver
1636 	 * registered. We are still in a handler from our IRQ. If we push
1637 	 * directly, it means the other driver has it's callback called
1638 	 * from our IRQ context. Which is something we better avoid.
1639 	 * Let's schedule it after our IRQ is completed.
1640 	 */
1641 	schedule_work(&st->touch_st.workq);
1642 }
1643 
1644 static void at91_adc_pen_detect_interrupt(struct at91_adc_state *st)
1645 {
1646 	at91_adc_writel(st, IDR, AT91_SAMA5D2_IER_PEN);
1647 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_NOPEN |
1648 			AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1649 			AT91_SAMA5D2_IER_PRDY);
1650 	at91_adc_writel(st, TRGR, AT91_SAMA5D2_TRGR_TRGMOD_PERIODIC |
1651 			AT91_SAMA5D2_TRGR_TRGPER(st->touch_st.sample_period_val));
1652 	st->touch_st.touching = true;
1653 }
1654 
1655 static void at91_adc_no_pen_detect_interrupt(struct iio_dev *indio_dev)
1656 {
1657 	struct at91_adc_state *st = iio_priv(indio_dev);
1658 
1659 	at91_adc_writel(st, TRGR, AT91_SAMA5D2_TRGR_TRGMOD_NO_TRIGGER);
1660 	at91_adc_writel(st, IDR, AT91_SAMA5D2_IER_NOPEN |
1661 			AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1662 			AT91_SAMA5D2_IER_PRDY);
1663 	st->touch_st.touching = false;
1664 
1665 	at91_adc_touch_data_handler(indio_dev);
1666 
1667 	at91_adc_writel(st, IER, AT91_SAMA5D2_IER_PEN);
1668 }
1669 
1670 static void at91_adc_workq_handler(struct work_struct *workq)
1671 {
1672 	struct at91_adc_touch *touch_st = container_of(workq,
1673 					struct at91_adc_touch, workq);
1674 	struct at91_adc_state *st = container_of(touch_st,
1675 					struct at91_adc_state, touch_st);
1676 	struct iio_dev *indio_dev = st->indio_dev;
1677 
1678 	iio_push_to_buffers(indio_dev, st->buffer);
1679 }
1680 
1681 static irqreturn_t at91_adc_interrupt(int irq, void *private)
1682 {
1683 	struct iio_dev *indio = private;
1684 	struct at91_adc_state *st = iio_priv(indio);
1685 	u32 status, eoc, imr, eoc_imr;
1686 	u32 rdy_mask = AT91_SAMA5D2_IER_XRDY | AT91_SAMA5D2_IER_YRDY |
1687 			AT91_SAMA5D2_IER_PRDY;
1688 
1689 	at91_adc_irq_status(st, &status, &eoc);
1690 	at91_adc_irq_mask(st, &imr, &eoc_imr);
1691 
1692 	if (!(status & imr) && !(eoc & eoc_imr))
1693 		return IRQ_NONE;
1694 	if (status & AT91_SAMA5D2_IER_PEN) {
1695 		/* pen detected IRQ */
1696 		at91_adc_pen_detect_interrupt(st);
1697 	} else if ((status & AT91_SAMA5D2_IER_NOPEN)) {
1698 		/* nopen detected IRQ */
1699 		at91_adc_no_pen_detect_interrupt(indio);
1700 	} else if ((status & AT91_SAMA5D2_ISR_PENS) &&
1701 		   ((status & rdy_mask) == rdy_mask)) {
1702 		/* periodic trigger IRQ - during pen sense */
1703 		at91_adc_touch_data_handler(indio);
1704 	} else if (status & AT91_SAMA5D2_ISR_PENS) {
1705 		/*
1706 		 * touching, but the measurements are not ready yet.
1707 		 * read and ignore.
1708 		 */
1709 		status = at91_adc_readl(st, XPOSR);
1710 		status = at91_adc_readl(st, YPOSR);
1711 		status = at91_adc_readl(st, PRESSR);
1712 	} else if (iio_buffer_enabled(indio) &&
1713 		   (status & AT91_SAMA5D2_IER_DRDY)) {
1714 		/* triggered buffer without DMA */
1715 		disable_irq_nosync(irq);
1716 		iio_trigger_poll(indio->trig);
1717 	} else if (iio_buffer_enabled(indio) && st->dma_st.dma_chan) {
1718 		/* triggered buffer with DMA - should not happen */
1719 		disable_irq_nosync(irq);
1720 		WARN(true, "Unexpected irq occurred\n");
1721 	} else if (!iio_buffer_enabled(indio)) {
1722 		/* software requested conversion */
1723 		st->conversion_value = at91_adc_read_chan(st, st->chan->address);
1724 		st->conversion_done = true;
1725 		wake_up_interruptible(&st->wq_data_available);
1726 	}
1727 	return IRQ_HANDLED;
1728 }
1729 
1730 /* This needs to be called with direct mode claimed and st->lock locked. */
1731 static int at91_adc_read_info_raw(struct iio_dev *indio_dev,
1732 				  struct iio_chan_spec const *chan, int *val)
1733 {
1734 	struct at91_adc_state *st = iio_priv(indio_dev);
1735 	u16 tmp_val;
1736 	int ret;
1737 
1738 	ret = pm_runtime_resume_and_get(st->dev);
1739 	if (ret < 0)
1740 		return ret;
1741 
1742 	/*
1743 	 * Keep in mind that we cannot use software trigger or touchscreen
1744 	 * if external trigger is enabled
1745 	 */
1746 	if (chan->type == IIO_POSITIONRELATIVE) {
1747 		ret = at91_adc_read_position(st, chan->channel,
1748 					     &tmp_val);
1749 		*val = tmp_val;
1750 		if (ret > 0)
1751 			ret = at91_adc_adjust_val_osr(st, val);
1752 
1753 		goto pm_runtime_put;
1754 	}
1755 	if (chan->type == IIO_PRESSURE) {
1756 		ret = at91_adc_read_pressure(st, chan->channel,
1757 					     &tmp_val);
1758 		*val = tmp_val;
1759 		if (ret > 0)
1760 			ret = at91_adc_adjust_val_osr(st, val);
1761 
1762 		goto pm_runtime_put;
1763 	}
1764 
1765 	/* in this case we have a voltage or temperature channel */
1766 
1767 	st->chan = chan;
1768 
1769 	at91_adc_cor(st, chan);
1770 	at91_adc_writel(st, CHER, BIT(chan->channel));
1771 	/*
1772 	 * TEMPMR.TEMPON needs to update after CHER otherwise if none
1773 	 * of the channels are enabled and TEMPMR.TEMPON = 1 will
1774 	 * trigger DRDY interruption while preparing for temperature read.
1775 	 */
1776 	if (chan->type == IIO_TEMP)
1777 		at91_adc_writel(st, TEMPMR, AT91_SAMA5D2_TEMPMR_TEMPON);
1778 	at91_adc_eoc_ena(st, chan->channel);
1779 	at91_adc_writel(st, CR, AT91_SAMA5D2_CR_START);
1780 
1781 	ret = wait_event_interruptible_timeout(st->wq_data_available,
1782 					       st->conversion_done,
1783 					       msecs_to_jiffies(1000));
1784 	if (ret == 0)
1785 		ret = -ETIMEDOUT;
1786 
1787 	if (ret > 0) {
1788 		*val = st->conversion_value;
1789 		ret = at91_adc_adjust_val_osr(st, val);
1790 		if (chan->scan_type.sign == 's')
1791 			*val = sign_extend32(*val,
1792 					     chan->scan_type.realbits - 1);
1793 		st->conversion_done = false;
1794 	}
1795 
1796 	at91_adc_eoc_dis(st, st->chan->channel);
1797 	if (chan->type == IIO_TEMP)
1798 		at91_adc_writel(st, TEMPMR, 0U);
1799 	at91_adc_writel(st, CHDR, BIT(chan->channel));
1800 
1801 	/* Needed to ACK the DRDY interruption */
1802 	at91_adc_readl(st, LCDR);
1803 
1804 pm_runtime_put:
1805 	pm_runtime_put_autosuspend(st->dev);
1806 	return ret;
1807 }
1808 
1809 static int at91_adc_read_info_locked(struct iio_dev *indio_dev,
1810 				     struct iio_chan_spec const *chan, int *val)
1811 {
1812 	struct at91_adc_state *st = iio_priv(indio_dev);
1813 
1814 	guard(mutex)(&st->lock);
1815 
1816 	return at91_adc_read_info_raw(indio_dev, chan, val);
1817 }
1818 
1819 static void at91_adc_temp_sensor_configure(struct at91_adc_state *st,
1820 					   bool start)
1821 {
1822 	u32 sample_rate, oversampling_ratio;
1823 	u32 startup_time, tracktim, trackx;
1824 
1825 	if (start) {
1826 		/*
1827 		 * Configure the sensor for best accuracy: 10MHz frequency,
1828 		 * oversampling rate of 256, tracktim=0xf and trackx=1.
1829 		 */
1830 		sample_rate = 10 * MEGA;
1831 		oversampling_ratio = 256;
1832 		startup_time = AT91_SAMA5D2_MR_STARTUP_TS_MIN;
1833 		tracktim = AT91_SAMA5D2_MR_TRACKTIM_TS;
1834 		trackx = AT91_SAMA5D2_TRACKX_TS;
1835 
1836 		st->temp_st.saved_sample_rate = st->current_sample_rate;
1837 		st->temp_st.saved_oversampling = st->oversampling_ratio;
1838 	} else {
1839 		/* Go back to previous settings. */
1840 		sample_rate = st->temp_st.saved_sample_rate;
1841 		oversampling_ratio = st->temp_st.saved_oversampling;
1842 		startup_time = st->soc_info.startup_time;
1843 		tracktim = 0;
1844 		trackx = 0;
1845 	}
1846 
1847 	at91_adc_setup_samp_freq(st->indio_dev, sample_rate, startup_time,
1848 				 tracktim);
1849 	at91_adc_config_emr(st, oversampling_ratio, trackx);
1850 }
1851 
1852 static int at91_adc_read_temp(struct iio_dev *indio_dev,
1853 			      struct iio_chan_spec const *chan, int *val)
1854 {
1855 	struct at91_adc_state *st = iio_priv(indio_dev);
1856 	struct at91_adc_temp_sensor_clb *clb = &st->soc_info.temp_sensor_clb;
1857 	u64 div1, div2;
1858 	u32 tmp;
1859 	int ret, vbg, vtemp;
1860 
1861 	guard(mutex)(&st->lock);
1862 
1863 	ret = pm_runtime_resume_and_get(st->dev);
1864 	if (ret < 0)
1865 		return ret;
1866 
1867 	at91_adc_temp_sensor_configure(st, true);
1868 
1869 	/* Read VBG. */
1870 	tmp = at91_adc_readl(st, ACR);
1871 	tmp |= AT91_SAMA5D2_ACR_SRCLCH;
1872 	at91_adc_writel(st, ACR, tmp);
1873 	ret = at91_adc_read_info_raw(indio_dev, chan, &vbg);
1874 	if (ret < 0)
1875 		goto restore_config;
1876 
1877 	/* Read VTEMP. */
1878 	tmp &= ~AT91_SAMA5D2_ACR_SRCLCH;
1879 	at91_adc_writel(st, ACR, tmp);
1880 	ret = at91_adc_read_info_raw(indio_dev, chan, &vtemp);
1881 
1882 restore_config:
1883 	/* Revert previous settings. */
1884 	at91_adc_temp_sensor_configure(st, false);
1885 	pm_runtime_put_autosuspend(st->dev);
1886 	if (ret < 0)
1887 		return ret;
1888 
1889 	/*
1890 	 * Temp[milli] = p1[milli] + (vtemp * clb->p6 - clb->p4 * vbg)/
1891 	 *			     (vbg * AT91_ADC_TS_VTEMP_DT)
1892 	 */
1893 	div1 = DIV_ROUND_CLOSEST_ULL(((u64)vtemp * clb->p6), vbg);
1894 	div1 = DIV_ROUND_CLOSEST_ULL((div1 * 1000), AT91_ADC_TS_VTEMP_DT);
1895 	div2 = DIV_ROUND_CLOSEST_ULL((u64)clb->p4, AT91_ADC_TS_VTEMP_DT);
1896 	div2 *= 1000;
1897 	*val = clb->p1 + (int)div1 - (int)div2;
1898 
1899 	return ret;
1900 }
1901 
1902 static int at91_adc_read_raw(struct iio_dev *indio_dev,
1903 			     struct iio_chan_spec const *chan,
1904 			     int *val, int *val2, long mask)
1905 {
1906 	struct at91_adc_state *st = iio_priv(indio_dev);
1907 	int ret;
1908 
1909 	switch (mask) {
1910 	case IIO_CHAN_INFO_RAW:
1911 		if (!iio_device_claim_direct(indio_dev))
1912 			return -EBUSY;
1913 
1914 		ret = at91_adc_read_info_locked(indio_dev, chan, val);
1915 		iio_device_release_direct(indio_dev);
1916 		return ret;
1917 
1918 	case IIO_CHAN_INFO_SCALE:
1919 		*val = st->vref_uv / 1000;
1920 		if (chan->differential)
1921 			*val *= 2;
1922 		*val2 = chan->scan_type.realbits;
1923 		return IIO_VAL_FRACTIONAL_LOG2;
1924 
1925 	case IIO_CHAN_INFO_PROCESSED:
1926 		if (chan->type != IIO_TEMP)
1927 			return -EINVAL;
1928 		if (!iio_device_claim_direct(indio_dev))
1929 			return -EBUSY;
1930 
1931 		ret = at91_adc_read_temp(indio_dev, chan, val);
1932 		iio_device_release_direct(indio_dev);
1933 
1934 		return ret;
1935 
1936 	case IIO_CHAN_INFO_SAMP_FREQ:
1937 		*val = at91_adc_get_sample_freq(st);
1938 		return IIO_VAL_INT;
1939 
1940 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1941 		*val = st->oversampling_ratio;
1942 		return IIO_VAL_INT;
1943 
1944 	default:
1945 		return -EINVAL;
1946 	}
1947 }
1948 
1949 static int at91_adc_write_raw(struct iio_dev *indio_dev,
1950 			      struct iio_chan_spec const *chan,
1951 			      int val, int val2, long mask)
1952 {
1953 	struct at91_adc_state *st = iio_priv(indio_dev);
1954 	int ret;
1955 
1956 	switch (mask) {
1957 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1958 		/* if no change, optimize out */
1959 		if (val == st->oversampling_ratio)
1960 			return 0;
1961 
1962 		if (!iio_device_claim_direct(indio_dev))
1963 			return -EBUSY;
1964 		mutex_lock(&st->lock);
1965 		/* update ratio */
1966 		ret = at91_adc_config_emr(st, val, 0);
1967 		mutex_unlock(&st->lock);
1968 		iio_device_release_direct(indio_dev);
1969 		return ret;
1970 	case IIO_CHAN_INFO_SAMP_FREQ:
1971 		if (val < st->soc_info.min_sample_rate ||
1972 		    val > st->soc_info.max_sample_rate)
1973 			return -EINVAL;
1974 
1975 		if (!iio_device_claim_direct(indio_dev))
1976 			return -EBUSY;
1977 		mutex_lock(&st->lock);
1978 		at91_adc_setup_samp_freq(indio_dev, val,
1979 					 st->soc_info.startup_time, 0);
1980 		mutex_unlock(&st->lock);
1981 		iio_device_release_direct(indio_dev);
1982 		return 0;
1983 	default:
1984 		return -EINVAL;
1985 	}
1986 }
1987 
1988 static int at91_adc_read_avail(struct iio_dev *indio_dev,
1989 			       struct iio_chan_spec const *chan,
1990 			       const int **vals, int *type, int *length,
1991 			       long mask)
1992 {
1993 	struct at91_adc_state *st = iio_priv(indio_dev);
1994 
1995 	switch (mask) {
1996 	case IIO_CHAN_INFO_OVERSAMPLING_RATIO:
1997 		*vals = (int *)st->soc_info.platform->oversampling_avail;
1998 		*type = IIO_VAL_INT;
1999 		*length = st->soc_info.platform->oversampling_avail_no;
2000 		return IIO_AVAIL_LIST;
2001 	default:
2002 		return -EINVAL;
2003 	}
2004 }
2005 
2006 static void at91_adc_dma_init(struct at91_adc_state *st)
2007 {
2008 	struct device *dev = &st->indio_dev->dev;
2009 	struct dma_slave_config config = {0};
2010 	/* we have 2 bytes for each channel */
2011 	unsigned int sample_size = st->soc_info.platform->nr_channels * 2;
2012 	/*
2013 	 * We make the buffer double the size of the fifo,
2014 	 * such that DMA uses one half of the buffer (full fifo size)
2015 	 * and the software uses the other half to read/write.
2016 	 */
2017 	unsigned int pages = DIV_ROUND_UP(AT91_HWFIFO_MAX_SIZE *
2018 					  sample_size * 2, PAGE_SIZE);
2019 
2020 	if (st->dma_st.dma_chan)
2021 		return;
2022 
2023 	st->dma_st.dma_chan = dma_request_chan(dev, "rx");
2024 	if (IS_ERR(st->dma_st.dma_chan))  {
2025 		dev_info(dev, "can't get DMA channel\n");
2026 		st->dma_st.dma_chan = NULL;
2027 		goto dma_exit;
2028 	}
2029 
2030 	st->dma_st.rx_buf = dma_alloc_coherent(st->dma_st.dma_chan->device->dev,
2031 					       pages * PAGE_SIZE,
2032 					       &st->dma_st.rx_dma_buf,
2033 					       GFP_KERNEL);
2034 	if (!st->dma_st.rx_buf) {
2035 		dev_info(dev, "can't allocate coherent DMA area\n");
2036 		goto dma_chan_disable;
2037 	}
2038 
2039 	/* Configure DMA channel to read data register */
2040 	config.direction = DMA_DEV_TO_MEM;
2041 	config.src_addr = (phys_addr_t)(st->dma_st.phys_addr
2042 			  + st->soc_info.platform->layout->LCDR);
2043 	config.src_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES;
2044 	config.src_maxburst = 1;
2045 	config.dst_maxburst = 1;
2046 
2047 	if (dmaengine_slave_config(st->dma_st.dma_chan, &config)) {
2048 		dev_info(dev, "can't configure DMA slave\n");
2049 		goto dma_free_area;
2050 	}
2051 
2052 	dev_info(dev, "using %s for rx DMA transfers\n",
2053 		 dma_chan_name(st->dma_st.dma_chan));
2054 
2055 	return;
2056 
2057 dma_free_area:
2058 	dma_free_coherent(st->dma_st.dma_chan->device->dev, pages * PAGE_SIZE,
2059 			  st->dma_st.rx_buf, st->dma_st.rx_dma_buf);
2060 dma_chan_disable:
2061 	dma_release_channel(st->dma_st.dma_chan);
2062 	st->dma_st.dma_chan = NULL;
2063 dma_exit:
2064 	dev_info(dev, "continuing without DMA support\n");
2065 }
2066 
2067 static void at91_adc_dma_disable(struct at91_adc_state *st)
2068 {
2069 	struct device *dev = &st->indio_dev->dev;
2070 	/* we have 2 bytes for each channel */
2071 	unsigned int sample_size = st->soc_info.platform->nr_channels * 2;
2072 	unsigned int pages = DIV_ROUND_UP(AT91_HWFIFO_MAX_SIZE *
2073 					  sample_size * 2, PAGE_SIZE);
2074 
2075 	/* if we are not using DMA, just return */
2076 	if (!st->dma_st.dma_chan)
2077 		return;
2078 
2079 	/* wait for all transactions to be terminated first*/
2080 	dmaengine_terminate_sync(st->dma_st.dma_chan);
2081 
2082 	dma_free_coherent(st->dma_st.dma_chan->device->dev, pages * PAGE_SIZE,
2083 			  st->dma_st.rx_buf, st->dma_st.rx_dma_buf);
2084 	dma_release_channel(st->dma_st.dma_chan);
2085 	st->dma_st.dma_chan = NULL;
2086 
2087 	dev_info(dev, "continuing without DMA support\n");
2088 }
2089 
2090 static int at91_adc_set_watermark(struct iio_dev *indio_dev, unsigned int val)
2091 {
2092 	struct at91_adc_state *st = iio_priv(indio_dev);
2093 	int ret;
2094 
2095 	if (val > AT91_HWFIFO_MAX_SIZE)
2096 		val = AT91_HWFIFO_MAX_SIZE;
2097 
2098 	if (!st->selected_trig->hw_trig) {
2099 		dev_dbg(&indio_dev->dev, "we need hw trigger for DMA\n");
2100 		return 0;
2101 	}
2102 
2103 	dev_dbg(&indio_dev->dev, "new watermark is %u\n", val);
2104 	st->dma_st.watermark = val;
2105 
2106 	/*
2107 	 * The logic here is: if we have watermark 1, it means we do
2108 	 * each conversion with it's own IRQ, thus we don't need DMA.
2109 	 * If the watermark is higher, we do DMA to do all the transfers in bulk
2110 	 */
2111 
2112 	if (val == 1)
2113 		at91_adc_dma_disable(st);
2114 	else if (val > 1)
2115 		at91_adc_dma_init(st);
2116 
2117 	/*
2118 	 * We can start the DMA only after setting the watermark and
2119 	 * having the DMA initialization completed
2120 	 */
2121 	ret = at91_adc_buffer_prepare(indio_dev);
2122 	if (ret)
2123 		at91_adc_dma_disable(st);
2124 
2125 	return ret;
2126 }
2127 
2128 static int at91_adc_update_scan_mode(struct iio_dev *indio_dev,
2129 				     const unsigned long *scan_mask)
2130 {
2131 	struct at91_adc_state *st = iio_priv(indio_dev);
2132 
2133 	if (bitmap_subset(scan_mask, &st->touch_st.channels_bitmask,
2134 			  st->soc_info.platform->max_index + 1))
2135 		return 0;
2136 	/*
2137 	 * if the new bitmap is a combination of touchscreen and regular
2138 	 * channels, then we are not fine
2139 	 */
2140 	if (bitmap_intersects(&st->touch_st.channels_bitmask, scan_mask,
2141 			      st->soc_info.platform->max_index + 1))
2142 		return -EINVAL;
2143 	return 0;
2144 }
2145 
2146 static void at91_adc_hw_init(struct iio_dev *indio_dev)
2147 {
2148 	struct at91_adc_state *st = iio_priv(indio_dev);
2149 
2150 	at91_adc_writel(st, CR, AT91_SAMA5D2_CR_SWRST);
2151 	if (st->soc_info.platform->layout->EOC_IDR)
2152 		at91_adc_writel(st, EOC_IDR, 0xffffffff);
2153 	at91_adc_writel(st, IDR, 0xffffffff);
2154 	/*
2155 	 * Transfer field must be set to 2 according to the datasheet and
2156 	 * allows different analog settings for each channel.
2157 	 */
2158 	at91_adc_writel(st, MR,
2159 			AT91_SAMA5D2_MR_TRANSFER(2) | AT91_SAMA5D2_MR_ANACH);
2160 
2161 	at91_adc_setup_samp_freq(indio_dev, st->soc_info.min_sample_rate,
2162 				 st->soc_info.startup_time, 0);
2163 
2164 	/* configure extended mode register */
2165 	at91_adc_config_emr(st, st->oversampling_ratio, 0);
2166 }
2167 
2168 static ssize_t at91_adc_get_fifo_state(struct device *dev,
2169 				       struct device_attribute *attr, char *buf)
2170 {
2171 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
2172 	struct at91_adc_state *st = iio_priv(indio_dev);
2173 
2174 	return sysfs_emit(buf, "%d\n", !!st->dma_st.dma_chan);
2175 }
2176 
2177 static ssize_t at91_adc_get_watermark(struct device *dev,
2178 				      struct device_attribute *attr, char *buf)
2179 {
2180 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
2181 	struct at91_adc_state *st = iio_priv(indio_dev);
2182 
2183 	return sysfs_emit(buf, "%d\n", st->dma_st.watermark);
2184 }
2185 
2186 static IIO_DEVICE_ATTR(hwfifo_enabled, 0444,
2187 		       at91_adc_get_fifo_state, NULL, 0);
2188 static IIO_DEVICE_ATTR(hwfifo_watermark, 0444,
2189 		       at91_adc_get_watermark, NULL, 0);
2190 
2191 IIO_STATIC_CONST_DEVICE_ATTR(hwfifo_watermark_min, "2");
2192 IIO_STATIC_CONST_DEVICE_ATTR(hwfifo_watermark_max, AT91_HWFIFO_MAX_SIZE_STR);
2193 
2194 static const struct iio_dev_attr *at91_adc_fifo_attributes[] = {
2195 	&iio_dev_attr_hwfifo_watermark_min,
2196 	&iio_dev_attr_hwfifo_watermark_max,
2197 	&iio_dev_attr_hwfifo_watermark,
2198 	&iio_dev_attr_hwfifo_enabled,
2199 	NULL,
2200 };
2201 
2202 static const struct iio_info at91_adc_info = {
2203 	.read_avail = &at91_adc_read_avail,
2204 	.read_raw = &at91_adc_read_raw,
2205 	.write_raw = &at91_adc_write_raw,
2206 	.update_scan_mode = &at91_adc_update_scan_mode,
2207 	.fwnode_xlate = &at91_adc_fwnode_xlate,
2208 	.hwfifo_set_watermark = &at91_adc_set_watermark,
2209 };
2210 
2211 static int at91_adc_buffer_and_trigger_init(struct device *dev,
2212 					    struct iio_dev *indio)
2213 {
2214 	struct at91_adc_state *st = iio_priv(indio);
2215 	const struct iio_dev_attr **fifo_attrs;
2216 	int ret;
2217 
2218 	if (st->selected_trig->hw_trig)
2219 		fifo_attrs = at91_adc_fifo_attributes;
2220 	else
2221 		fifo_attrs = NULL;
2222 
2223 	ret = devm_iio_triggered_buffer_setup_ext(&indio->dev, indio,
2224 		&iio_pollfunc_store_time, &at91_adc_trigger_handler,
2225 		IIO_BUFFER_DIRECTION_IN, &at91_buffer_setup_ops, fifo_attrs);
2226 	if (ret < 0) {
2227 		dev_err(dev, "couldn't initialize the buffer.\n");
2228 		return ret;
2229 	}
2230 
2231 	if (!st->selected_trig->hw_trig)
2232 		return 0;
2233 
2234 	st->trig = at91_adc_allocate_trigger(indio, st->selected_trig->name);
2235 	if (IS_ERR(st->trig)) {
2236 		dev_err(dev, "could not allocate trigger\n");
2237 		return PTR_ERR(st->trig);
2238 	}
2239 
2240 	/*
2241 	 * Initially the iio buffer has a length of 2 and
2242 	 * a watermark of 1
2243 	 */
2244 	st->dma_st.watermark = 1;
2245 
2246 	return 0;
2247 }
2248 
2249 static int at91_adc_temp_sensor_init(struct at91_adc_state *st,
2250 				     struct device *dev)
2251 {
2252 	struct at91_adc_temp_sensor_clb *clb = &st->soc_info.temp_sensor_clb;
2253 	struct nvmem_cell *temp_calib;
2254 	u32 *buf;
2255 	size_t len;
2256 	int ret = 0;
2257 
2258 	if (!st->soc_info.platform->temp_sensor)
2259 		return 0;
2260 
2261 	/* Get the calibration data from NVMEM. */
2262 	temp_calib = devm_nvmem_cell_get(dev, "temperature_calib");
2263 	if (IS_ERR(temp_calib)) {
2264 		ret = PTR_ERR(temp_calib);
2265 		if (ret != -ENOENT)
2266 			dev_err(dev, "Failed to get temperature_calib cell!\n");
2267 		return ret;
2268 	}
2269 
2270 	buf = nvmem_cell_read(temp_calib, &len);
2271 	if (IS_ERR(buf)) {
2272 		dev_err(dev, "Failed to read calibration data!\n");
2273 		return PTR_ERR(buf);
2274 	}
2275 	if (len < AT91_ADC_TS_CLB_IDX_MAX * 4) {
2276 		dev_err(dev, "Invalid calibration data!\n");
2277 		ret = -EINVAL;
2278 		goto free_buf;
2279 	}
2280 
2281 	/* Store calibration data for later use. */
2282 	clb->p1 = buf[AT91_ADC_TS_CLB_IDX_P1];
2283 	clb->p4 = buf[AT91_ADC_TS_CLB_IDX_P4];
2284 	clb->p6 = buf[AT91_ADC_TS_CLB_IDX_P6];
2285 
2286 	/*
2287 	 * We prepare here the conversion to milli to avoid doing it on hotpath.
2288 	 */
2289 	clb->p1 = clb->p1 * 1000;
2290 
2291 free_buf:
2292 	kfree(buf);
2293 	return ret;
2294 }
2295 
2296 static int at91_adc_probe(struct platform_device *pdev)
2297 {
2298 	struct device *dev = &pdev->dev;
2299 	struct iio_dev *indio_dev;
2300 	struct at91_adc_state *st;
2301 	struct resource	*res;
2302 	int ret, i, num_channels;
2303 	u32 edge_type = IRQ_TYPE_NONE;
2304 
2305 	indio_dev = devm_iio_device_alloc(&pdev->dev, sizeof(*st));
2306 	if (!indio_dev)
2307 		return -ENOMEM;
2308 
2309 	st = iio_priv(indio_dev);
2310 	st->indio_dev = indio_dev;
2311 
2312 	st->soc_info.platform = device_get_match_data(dev);
2313 
2314 	ret = at91_adc_temp_sensor_init(st, &pdev->dev);
2315 	/* Don't register temperature channel if initialization failed. */
2316 	if (ret)
2317 		num_channels = st->soc_info.platform->max_channels - 1;
2318 	else
2319 		num_channels = st->soc_info.platform->max_channels;
2320 
2321 	indio_dev->name = dev_name(&pdev->dev);
2322 	indio_dev->modes = INDIO_DIRECT_MODE | INDIO_BUFFER_SOFTWARE;
2323 	indio_dev->info = &at91_adc_info;
2324 	indio_dev->channels = *st->soc_info.platform->adc_channels;
2325 	indio_dev->num_channels = num_channels;
2326 
2327 	bitmap_set(&st->touch_st.channels_bitmask,
2328 		   st->soc_info.platform->touch_chan_x, 1);
2329 	bitmap_set(&st->touch_st.channels_bitmask,
2330 		   st->soc_info.platform->touch_chan_y, 1);
2331 	bitmap_set(&st->touch_st.channels_bitmask,
2332 		   st->soc_info.platform->touch_chan_p, 1);
2333 
2334 	st->oversampling_ratio = 1;
2335 
2336 	ret = device_property_read_u32(dev, "atmel,min-sample-rate-hz",
2337 				       &st->soc_info.min_sample_rate);
2338 	if (ret) {
2339 		dev_err(&pdev->dev,
2340 			"invalid or missing value for atmel,min-sample-rate-hz\n");
2341 		return ret;
2342 	}
2343 
2344 	ret = device_property_read_u32(dev, "atmel,max-sample-rate-hz",
2345 				       &st->soc_info.max_sample_rate);
2346 	if (ret) {
2347 		dev_err(&pdev->dev,
2348 			"invalid or missing value for atmel,max-sample-rate-hz\n");
2349 		return ret;
2350 	}
2351 
2352 	ret = device_property_read_u32(dev, "atmel,startup-time-ms",
2353 				       &st->soc_info.startup_time);
2354 	if (ret) {
2355 		dev_err(&pdev->dev,
2356 			"invalid or missing value for atmel,startup-time-ms\n");
2357 		return ret;
2358 	}
2359 
2360 	ret = device_property_read_u32(dev, "atmel,trigger-edge-type",
2361 				       &edge_type);
2362 	if (ret) {
2363 		dev_dbg(&pdev->dev,
2364 			"atmel,trigger-edge-type not specified, only software trigger available\n");
2365 	}
2366 
2367 	st->selected_trig = NULL;
2368 
2369 	/* find the right trigger, or no trigger at all */
2370 	for (i = 0; i < st->soc_info.platform->hw_trig_cnt + 1; i++)
2371 		if (at91_adc_trigger_list[i].edge_type == edge_type) {
2372 			st->selected_trig = &at91_adc_trigger_list[i];
2373 			break;
2374 		}
2375 
2376 	if (!st->selected_trig) {
2377 		dev_err(&pdev->dev, "invalid external trigger edge value\n");
2378 		return -EINVAL;
2379 	}
2380 
2381 	init_waitqueue_head(&st->wq_data_available);
2382 	mutex_init(&st->lock);
2383 	INIT_WORK(&st->touch_st.workq, at91_adc_workq_handler);
2384 
2385 	st->base = devm_platform_get_and_ioremap_resource(pdev, 0, &res);
2386 	if (IS_ERR(st->base))
2387 		return PTR_ERR(st->base);
2388 
2389 	/* if we plan to use DMA, we need the physical address of the regs */
2390 	st->dma_st.phys_addr = res->start;
2391 
2392 	st->irq = platform_get_irq(pdev, 0);
2393 	if (st->irq < 0)
2394 		return st->irq;
2395 
2396 	st->per_clk = devm_clk_get(&pdev->dev, "adc_clk");
2397 	if (IS_ERR(st->per_clk))
2398 		return PTR_ERR(st->per_clk);
2399 
2400 	st->reg = devm_regulator_get(&pdev->dev, "vddana");
2401 	if (IS_ERR(st->reg))
2402 		return PTR_ERR(st->reg);
2403 
2404 	st->vref = devm_regulator_get(&pdev->dev, "vref");
2405 	if (IS_ERR(st->vref))
2406 		return PTR_ERR(st->vref);
2407 
2408 	ret = devm_request_irq(&pdev->dev, st->irq, at91_adc_interrupt, 0,
2409 			       pdev->dev.driver->name, indio_dev);
2410 	if (ret)
2411 		return ret;
2412 
2413 	ret = regulator_enable(st->reg);
2414 	if (ret)
2415 		return ret;
2416 
2417 	ret = regulator_enable(st->vref);
2418 	if (ret)
2419 		goto reg_disable;
2420 
2421 	st->vref_uv = regulator_get_voltage(st->vref);
2422 	if (st->vref_uv <= 0) {
2423 		ret = -EINVAL;
2424 		goto vref_disable;
2425 	}
2426 
2427 	ret = clk_prepare_enable(st->per_clk);
2428 	if (ret)
2429 		goto vref_disable;
2430 
2431 	platform_set_drvdata(pdev, indio_dev);
2432 	st->dev = &pdev->dev;
2433 	pm_runtime_set_autosuspend_delay(st->dev, 500);
2434 	pm_runtime_use_autosuspend(st->dev);
2435 	pm_runtime_set_active(st->dev);
2436 	pm_runtime_enable(st->dev);
2437 	pm_runtime_get_noresume(st->dev);
2438 
2439 	at91_adc_hw_init(indio_dev);
2440 
2441 	ret = at91_adc_buffer_and_trigger_init(&pdev->dev, indio_dev);
2442 	if (ret < 0)
2443 		goto err_pm_disable;
2444 
2445 	if (dma_coerce_mask_and_coherent(&indio_dev->dev, DMA_BIT_MASK(32)))
2446 		dev_info(&pdev->dev, "cannot set DMA mask to 32-bit\n");
2447 
2448 	ret = iio_device_register(indio_dev);
2449 	if (ret < 0)
2450 		goto dma_disable;
2451 
2452 	if (st->selected_trig->hw_trig)
2453 		dev_info(&pdev->dev, "setting up trigger as %s\n",
2454 			 st->selected_trig->name);
2455 
2456 	dev_info(&pdev->dev, "version: %x\n",
2457 		 readl_relaxed(st->base + st->soc_info.platform->layout->VERSION));
2458 
2459 	pm_runtime_put_autosuspend(st->dev);
2460 
2461 	return 0;
2462 
2463 dma_disable:
2464 	at91_adc_dma_disable(st);
2465 err_pm_disable:
2466 	pm_runtime_put_noidle(st->dev);
2467 	pm_runtime_disable(st->dev);
2468 	pm_runtime_set_suspended(st->dev);
2469 	pm_runtime_dont_use_autosuspend(st->dev);
2470 	clk_disable_unprepare(st->per_clk);
2471 vref_disable:
2472 	regulator_disable(st->vref);
2473 reg_disable:
2474 	regulator_disable(st->reg);
2475 	return ret;
2476 }
2477 
2478 static void at91_adc_remove(struct platform_device *pdev)
2479 {
2480 	struct iio_dev *indio_dev = platform_get_drvdata(pdev);
2481 	struct at91_adc_state *st = iio_priv(indio_dev);
2482 
2483 	iio_device_unregister(indio_dev);
2484 
2485 	at91_adc_dma_disable(st);
2486 
2487 	pm_runtime_disable(st->dev);
2488 	pm_runtime_set_suspended(st->dev);
2489 	clk_disable_unprepare(st->per_clk);
2490 
2491 	regulator_disable(st->vref);
2492 	regulator_disable(st->reg);
2493 }
2494 
2495 static int at91_adc_suspend(struct device *dev)
2496 {
2497 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2498 	struct at91_adc_state *st = iio_priv(indio_dev);
2499 	int ret;
2500 
2501 	ret = pm_runtime_resume_and_get(st->dev);
2502 	if (ret < 0)
2503 		return ret;
2504 
2505 	if (iio_buffer_enabled(indio_dev))
2506 		at91_adc_buffer_postdisable(indio_dev);
2507 
2508 	/*
2509 	 * Do a sofware reset of the ADC before we go to suspend.
2510 	 * this will ensure that all pins are free from being muxed by the ADC
2511 	 * and can be used by for other devices.
2512 	 * Otherwise, ADC will hog them and we can't go to suspend mode.
2513 	 */
2514 	at91_adc_writel(st, CR, AT91_SAMA5D2_CR_SWRST);
2515 
2516 	pm_runtime_mark_last_busy(st->dev);
2517 	pm_runtime_put_noidle(st->dev);
2518 	clk_disable_unprepare(st->per_clk);
2519 	regulator_disable(st->vref);
2520 	regulator_disable(st->reg);
2521 
2522 	return pinctrl_pm_select_sleep_state(dev);
2523 }
2524 
2525 static int at91_adc_resume(struct device *dev)
2526 {
2527 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2528 	struct at91_adc_state *st = iio_priv(indio_dev);
2529 	int ret;
2530 
2531 	ret = pinctrl_pm_select_default_state(dev);
2532 	if (ret)
2533 		goto resume_failed;
2534 
2535 	ret = regulator_enable(st->reg);
2536 	if (ret)
2537 		goto resume_failed;
2538 
2539 	ret = regulator_enable(st->vref);
2540 	if (ret)
2541 		goto reg_disable_resume;
2542 
2543 	ret = clk_prepare_enable(st->per_clk);
2544 	if (ret)
2545 		goto vref_disable_resume;
2546 
2547 	pm_runtime_get_noresume(st->dev);
2548 
2549 	at91_adc_hw_init(indio_dev);
2550 
2551 	/* reconfiguring trigger hardware state */
2552 	if (iio_buffer_enabled(indio_dev)) {
2553 		ret = at91_adc_buffer_prepare(indio_dev);
2554 		if (ret)
2555 			goto pm_runtime_put;
2556 
2557 		at91_adc_configure_trigger_registers(st, true);
2558 	}
2559 
2560 	pm_runtime_put_autosuspend(st->dev);
2561 
2562 	return 0;
2563 
2564 pm_runtime_put:
2565 	pm_runtime_mark_last_busy(st->dev);
2566 	pm_runtime_put_noidle(st->dev);
2567 	clk_disable_unprepare(st->per_clk);
2568 vref_disable_resume:
2569 	regulator_disable(st->vref);
2570 reg_disable_resume:
2571 	regulator_disable(st->reg);
2572 resume_failed:
2573 	dev_err(&indio_dev->dev, "failed to resume\n");
2574 	return ret;
2575 }
2576 
2577 static int at91_adc_runtime_suspend(struct device *dev)
2578 {
2579 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2580 	struct at91_adc_state *st = iio_priv(indio_dev);
2581 
2582 	clk_disable(st->per_clk);
2583 
2584 	return 0;
2585 }
2586 
2587 static int at91_adc_runtime_resume(struct device *dev)
2588 {
2589 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
2590 	struct at91_adc_state *st = iio_priv(indio_dev);
2591 
2592 	return clk_enable(st->per_clk);
2593 }
2594 
2595 static const struct dev_pm_ops at91_adc_pm_ops = {
2596 	SYSTEM_SLEEP_PM_OPS(at91_adc_suspend, at91_adc_resume)
2597 	RUNTIME_PM_OPS(at91_adc_runtime_suspend, at91_adc_runtime_resume,
2598 		       NULL)
2599 };
2600 
2601 static const struct of_device_id at91_adc_dt_match[] = {
2602 	{
2603 		.compatible = "atmel,sama5d2-adc",
2604 		.data = (const void *)&sama5d2_platform,
2605 	}, {
2606 		.compatible = "microchip,sama7g5-adc",
2607 		.data = (const void *)&sama7g5_platform,
2608 	}, {
2609 		/* sentinel */
2610 	}
2611 };
2612 MODULE_DEVICE_TABLE(of, at91_adc_dt_match);
2613 
2614 static struct platform_driver at91_adc_driver = {
2615 	.probe = at91_adc_probe,
2616 	.remove = at91_adc_remove,
2617 	.driver = {
2618 		.name = "at91-sama5d2_adc",
2619 		.of_match_table = at91_adc_dt_match,
2620 		.pm = pm_ptr(&at91_adc_pm_ops),
2621 	},
2622 };
2623 module_platform_driver(at91_adc_driver)
2624 
2625 MODULE_AUTHOR("Ludovic Desroches <ludovic.desroches@microchip.com>");
2626 MODULE_AUTHOR("Eugen Hristev <eugen.hristev@microchip.com");
2627 MODULE_DESCRIPTION("Atmel AT91 SAMA5D2 ADC");
2628 MODULE_LICENSE("GPL v2");
2629