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